Skip to main content

qk_cache/
hash.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::ffi::OsString;
3use std::fs::File;
4use std::io::{Read, Write};
5use std::path::{Path, PathBuf};
6use std::sync::atomic::AtomicBool;
7use std::sync::{Arc, Mutex};
8use std::time::{Duration, Instant, SystemTime};
9
10use anyhow::{Context, Result, bail};
11use foldhash::{HashMap, HashMapExt, HashSet};
12use qk_config::Workspace;
13use qk_executor::{Capture, Display, Outcome, PreparedTask, execute_captured, read_capture};
14use qk_graph::ProjectGraph;
15use qk_lockfile::Lockfile;
16use qk_taskgraph::{Task, TaskGraph};
17use serde_json::{Value, json};
18
19use crate::ignored::Group;
20use crate::inputs::{
21    Declared, Inferred, JsonFields, Resolved, TsConfig, manifest_for_dependents,
22    workspace_without_resolution,
23};
24use crate::paths::{self, Outputs, Pattern};
25
26pub fn digest_file(path: &Path) -> Result<String> {
27    let mut hasher = blake3::Hasher::new();
28    let mut reader = File::open(path)?;
29    let mut buffer = [0; 64 * 1024];
30    loop {
31        let count = reader.read(&mut buffer)?;
32        if count == 0 {
33            break;
34        }
35        hasher.update(&buffer[..count]);
36    }
37    Ok(hasher.finalize().to_hex().to_string())
38}
39
40/// Metadata that changes whenever a file's content can have changed: size,
41/// modification time and, on Unix, change time, inode and mode.
42#[derive(Clone, PartialEq, serde::Serialize, serde::Deserialize)]
43struct Stamp(Vec<i64>);
44
45impl Stamp {
46    fn new(metadata: &std::fs::Metadata) -> Self {
47        let modified = metadata
48            .modified()
49            .ok()
50            .and_then(|time| time.duration_since(SystemTime::UNIX_EPOCH).ok())
51            .map_or(-1, |duration| duration.as_nanos() as i64);
52        #[allow(unused_mut)]
53        let mut values = vec![metadata.len() as i64, modified];
54        #[cfg(unix)]
55        {
56            use std::os::unix::fs::MetadataExt;
57            values.extend([
58                metadata.ctime(),
59                metadata.ctime_nsec(),
60                metadata.ino() as i64,
61                i64::from(metadata.mode()),
62            ]);
63        }
64        Self(values)
65    }
66
67    /// Membership stamps also use change time: restoring a directory's mtime
68    /// must not allow changes inside a coarse timestamp window to go unnoticed.
69    fn membership_settled(&self) -> bool {
70        #[cfg(unix)]
71        let width = 6;
72        #[cfg(not(unix))]
73        let width = 2;
74        self.0.chunks_exact(width).all(|values| {
75            let modified = SystemTime::UNIX_EPOCH + Duration::from_nanos(values[1].max(0) as u64);
76            let settled = |time| {
77                SystemTime::now()
78                    .duration_since(time)
79                    .is_ok_and(|age| age > Duration::from_secs(2))
80            };
81            if values[1] < 0 || !settled(modified) {
82                return false;
83            }
84            #[cfg(unix)]
85            {
86                let changed = SystemTime::UNIX_EPOCH
87                    + Duration::new(values[2].max(0) as u64, values[3].max(0) as u32);
88                values[2] >= 0 && settled(changed)
89            }
90            #[cfg(not(unix))]
91            true
92        })
93    }
94
95    /// A file written within the timestamp resolution window could change again
96    /// without changing its stamp, so recent files are always re-read.
97    fn settled(&self) -> bool {
98        let modified = SystemTime::UNIX_EPOCH + Duration::from_nanos(self.0[1].max(0) as u64);
99        self.0[1] >= 0
100            && SystemTime::now()
101                .duration_since(modified)
102                .is_ok_and(|age| age > Duration::from_secs(2))
103    }
104}
105
106/// Digests persisted between runs in the worktree's state, keyed by path and
107/// stamp, so a warm run reads only the files that changed. Stamps include the
108/// inode, so they belong to one worktree.
109fn digests_path(root: &Path) -> PathBuf {
110    paths::worktree_state(root).join("digests.json")
111}
112
113#[derive(PartialEq, Eq, Hash)]
114struct RuntimeKey {
115    command: String,
116    environment: BTreeMap<OsString, OsString>,
117}
118
119/// Workspace state shared by every fingerprint in one run. Inspection uses the
120/// initial candidate list; execution fingerprints refresh membership so files
121/// added or removed during the run cannot escape input verification.
122pub struct Snapshot {
123    pub(crate) files: BTreeSet<String>,
124    extra_candidates: BTreeSet<String>,
125    membership: Mutex<Option<Arc<Membership>>>,
126    membership_prefixes: Mutex<HashMap<String, Arc<Vec<PathBuf>>>>,
127    source_exclusions: Vec<Outputs>,
128    /// Every task's scratch directories, among `source_exclusions`, which no
129    /// input reads, `includeIgnored` ones included.
130    scratch: Vec<Outputs>,
131    cache_relative: Option<PathBuf>,
132    projects: ProjectGraph,
133    /// Each project by its root, to find the project owning a file.
134    roots: BTreeMap<String, String>,
135    generated_tasks: Vec<(Task, Outputs)>,
136    task_dependencies: BTreeMap<String, BTreeSet<String>>,
137    /// Each task's servers, by project and declared inputs: see [`servers`].
138    servers: BTreeMap<String, Vec<(String, Vec<Value>)>>,
139    source_ignore: Arc<SourceIgnore>,
140    canonical_root: PathBuf,
141    workspace_prefix: Option<PathBuf>,
142    patterns: Mutex<HashMap<(String, bool, bool), Arc<Pattern>>>,
143    digests: Mutex<HashMap<String, (Stamp, String)>>,
144    /// Files `includeIgnored` filesets read, whose digests are saved beside
145    /// those of `files`, which may not list them.
146    ignored_files: Mutex<BTreeSet<String>>,
147    /// Whether `digests` gained entries worth saving.
148    digests_changed: std::sync::atomic::AtomicBool,
149    /// Directories already checked not to be symlinks.
150    directories: Mutex<HashSet<PathBuf>>,
151    /// Runtime input results by command and environment, computed once per run like Nx.
152    runtime: Mutex<HashMap<RuntimeKey, Arc<Mutex<Option<Value>>>>>,
153    /// The parsed pnpm lockfile, replaced whenever its content changes.
154    lockfile: Mutex<Option<Arc<Installed>>>,
155    /// Each dependency task's output files, listed when a task first asks and
156    /// dropped once a task whose outputs overlap them is done.
157    dependency_outputs: Mutex<HashMap<String, Arc<DependencyOutputs>>>,
158    /// Counts drops, so a listing taken while a task finished is not kept.
159    outputs_written: std::sync::atomic::AtomicU64,
160}
161
162/// Membership depends on directory entries and Git/ignore listing policy, not
163/// on every source file's contents. Empty directories must also be watched.
164#[derive(Clone)]
165struct Membership {
166    files: Arc<BTreeSet<String>>,
167    source_ignore: Arc<SourceIgnore>,
168    stamps: BTreeMap<PathBuf, Option<Stamp>>,
169    directories: BTreeSet<PathBuf>,
170    directory_entries: BTreeMap<PathBuf, BTreeSet<(OsString, u8)>>,
171    root: PathBuf,
172    outputs: Vec<Outputs>,
173    output_anchors: BTreeMap<PathBuf, Vec<usize>>,
174    excluded_roots: BTreeSet<PathBuf>,
175    cache: Option<PathBuf>,
176    policies: BTreeSet<PathBuf>,
177    git_policies: BTreeSet<PathBuf>,
178    ignore_contents: BTreeMap<PathBuf, String>,
179    settled: bool,
180    /// When the refresh that produced this inventory began listing.
181    listed: Option<Instant>,
182}
183
184/// A candidate listing and the ignore policy captured with it. Keeping both
185/// alive prevents a concurrent refresh from changing dependency-output selection.
186#[derive(Clone)]
187struct Candidates {
188    files: Arc<BTreeSet<String>>,
189    source_ignore: Arc<SourceIgnore>,
190}
191
192impl Membership {
193    /// Inventory source directories and policy stamps before a new listing.
194    fn new(
195        root: &Path,
196        files: &BTreeSet<String>,
197        source_ignore: &Arc<SourceIgnore>,
198        outputs: &[Outputs],
199        cache: Option<&Path>,
200        git_policies: Option<&BTreeSet<PathBuf>>,
201    ) -> Result<Self> {
202        let excluded: BTreeSet<_> = outputs
203            .iter()
204            .flat_map(Outputs::complete_roots)
205            .map(PathBuf::from)
206            .collect();
207        let excluded_roots = excluded.clone();
208        let walk_root = root.to_owned();
209        let walk_cache = cache.map(PathBuf::from);
210        let mut directories = BTreeSet::new();
211        let mut stamps = BTreeMap::new();
212        for entry in ignore::WalkBuilder::new(root)
213            .hidden(false)
214            .parents(false)
215            .git_global(false)
216            .require_git(false)
217            .ignore(false)
218            .git_ignore(false)
219            .git_exclude(false)
220            .follow_links(false)
221            .filter_entry(move |entry| {
222                let relative = entry
223                    .path()
224                    .strip_prefix(&walk_root)
225                    .unwrap_or(entry.path());
226                !matches!(
227                    entry.file_name().to_str(),
228                    Some(".git" | ".qk" | "node_modules")
229                ) && walk_cache
230                    .as_ref()
231                    .is_none_or(|cache| !relative.starts_with(cache))
232                    && !relative.ancestors().any(|path| excluded.contains(path))
233            })
234            .build()
235        {
236            let entry = entry?;
237            if entry.file_type().is_some_and(|kind| kind.is_dir()) {
238                let directory = entry.path().to_owned();
239                stamps.insert(directory.clone(), membership_stamp(&directory)?);
240                directories.insert(directory);
241            }
242        }
243        // Git lists tracked files even beneath ignored directories. Watching
244        // only the ignore walker would miss deletion/rename of those files.
245        for path in files {
246            for parent in Path::new(path).ancestors().skip(1) {
247                let directory = root.join(parent);
248                if directories.insert(directory.clone()) {
249                    stamps.insert(directory.clone(), membership_stamp(&directory)?);
250                }
251            }
252        }
253        let mut policies = BTreeSet::new();
254        for directory in &directories {
255            for name in [".gitignore", ".nxignore"] {
256                let path = directory.join(name);
257                // Creation of a new ignore file changes its directory stamp.
258                // Existing rules can be edited without changing the directory.
259                if membership_stamp(&path)?.is_some() {
260                    policies.insert(path);
261                }
262            }
263        }
264        for directory in root.ancestors() {
265            policies.insert(directory.join(".gitignore"));
266            // Also detect a newly initialized repository or changed worktree pointer.
267            policies.insert(directory.join(".git"));
268        }
269        let git_policies = git_policies
270            .cloned()
271            .unwrap_or_else(|| git_membership_policies(root));
272        policies.extend(git_policies.iter().cloned());
273        for policy in &policies {
274            stamps.insert(policy.clone(), membership_stamp(policy)?);
275        }
276        // Capture contents before listing, so a later policy change cannot be
277        // mistaken for the rules that produced that listing.
278        let mut ignore_contents = BTreeMap::new();
279        for policy in &policies {
280            if matches!(
281                policy.file_name().and_then(|name| name.to_str()),
282                Some(".gitignore" | ".nxignore")
283            ) && let Some(content) = ignore_content(policy, &stamps[policy])?
284            {
285                ignore_contents.insert(policy.clone(), content);
286            }
287        }
288        let mut output_anchors: BTreeMap<PathBuf, Vec<usize>> = BTreeMap::new();
289        for (index, outputs) in outputs.iter().enumerate() {
290            for anchor in outputs.anchors() {
291                output_anchors
292                    .entry(PathBuf::from(anchor))
293                    .or_default()
294                    .push(index);
295            }
296        }
297        let mut membership = Self {
298            files: Arc::new(BTreeSet::new()),
299            source_ignore: source_ignore.clone(),
300            stamps,
301            directories,
302            directory_entries: BTreeMap::new(),
303            root: root.to_owned(),
304            outputs: outputs.to_vec(),
305            output_anchors,
306            excluded_roots,
307            cache: cache.map(PathBuf::from),
308            policies,
309            git_policies,
310            ignore_contents,
311            settled: false,
312            listed: None,
313        };
314        for directory in &membership.directories {
315            if let Some(entries) = membership.entries(directory)? {
316                membership
317                    .directory_entries
318                    .insert(directory.clone(), entries);
319            }
320        }
321        Ok(membership)
322    }
323
324    /// Names and types that can affect source membership in this directory.
325    /// Output files may be skipped, but partially excluded output directories
326    /// must remain visible because they can contain source files or ignore rules.
327    fn entries(&self, directory: &Path) -> Result<Option<BTreeSet<(OsString, u8)>>> {
328        let entries = match std::fs::read_dir(directory) {
329            Ok(entries) => entries,
330            Err(error)
331                if matches!(
332                    error.kind(),
333                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
334                ) =>
335            {
336                return Ok(None);
337            }
338            Err(error) => return Err(error.into()),
339        };
340        let relative_directory = directory.strip_prefix(&self.root).unwrap_or(directory);
341        let mut outputs = BTreeSet::new();
342        for ancestor in relative_directory.ancestors() {
343            if let Some(indices) = self.output_anchors.get(ancestor) {
344                outputs.extend(indices.iter().copied());
345            }
346        }
347        for (_, indices) in self
348            .output_anchors
349            .range(relative_directory.to_owned()..)
350            .take_while(|(anchor, _)| anchor.starts_with(relative_directory))
351        {
352            outputs.extend(indices.iter().copied());
353        }
354        let mut names = BTreeSet::new();
355        for entry in entries {
356            let entry = entry?;
357            let name = entry.file_name();
358            let path = entry.path();
359            let relative = path.strip_prefix(&self.root).unwrap_or(&path);
360            if matches!(name.to_str(), Some(".git" | ".qk" | "node_modules"))
361                || self
362                    .cache
363                    .as_ref()
364                    .is_some_and(|cache| relative.starts_with(cache))
365                || relative
366                    .ancestors()
367                    .any(|root| self.excluded_roots.contains(root))
368            {
369                continue;
370            }
371            // A policy created between policy discovery and name capture must
372            // get its own stamp before its in-place edits can permit reuse.
373            if matches!(name.to_str(), Some(".gitignore" | ".nxignore"))
374                && !self.policies.contains(&path)
375            {
376                return Ok(None);
377            }
378            let kind = entry.file_type()?;
379            // An empty directory created after the inventory walk would not
380            // appear among source files. Never bless its parent signature until
381            // that directory is itself watched by the inventory.
382            if kind.is_dir() && !self.directories.contains(&path) {
383                return Ok(None);
384            }
385            if !kind.is_dir()
386                && !matches!(name.to_str(), Some(".gitignore" | ".nxignore"))
387                && relative.to_str().is_some_and(|path| {
388                    outputs
389                        .iter()
390                        .any(|index| self.outputs[*index].matches(path))
391                })
392            {
393                continue;
394            }
395            names.insert((
396                name,
397                if kind.is_dir() {
398                    1
399                } else if kind.is_symlink() {
400                    2
401                } else {
402                    0
403                },
404            ));
405        }
406        Ok(Some(names))
407    }
408
409    /// Check source-relevant directory membership and every listing policy.
410    /// Recent directory stamps require fresh entry names; recent ignore files
411    /// require matching contents, while other listing policies must settle.
412    fn state(&self, prefixes: Option<&[PathBuf]>) -> Result<(bool, bool)> {
413        let mut settled = true;
414        let selected = prefixes.map(|prefixes| {
415            let mut selected = BTreeSet::new();
416            for prefix in prefixes {
417                for ancestor in prefix.ancestors() {
418                    if let Some(directory) = self.directories.get(ancestor) {
419                        selected.insert(directory);
420                    }
421                }
422                selected.extend(
423                    self.directories
424                        .range(prefix.clone()..)
425                        .take_while(|directory| directory.starts_with(prefix)),
426                );
427            }
428            selected
429        });
430        let paths: Box<dyn Iterator<Item = (&PathBuf, bool)>> = match selected {
431            Some(selected) => Box::new(
432                selected
433                    .into_iter()
434                    .map(|path| (path, true))
435                    .chain(self.policies.iter().map(|path| (path, false))),
436            ),
437            None => Box::new(
438                self.stamps
439                    .keys()
440                    .map(|path| (path, self.directories.contains(path))),
441            ),
442        };
443        for (path, directory) in paths {
444            let before = &self.stamps[path];
445            let after = membership_stamp(path)?;
446            if directory {
447                if after.is_some() && !self.directory_entries.contains_key(path) {
448                    return Ok((false, false));
449                }
450                // Output publication changes its parent's timestamp too. Check
451                // source-relevant names rather than relisting the whole workspace.
452                // Recent directories are always read, even with an equal stamp:
453                // coarse timestamps can conceal an addition or removal.
454                if *before != after
455                    || after
456                        .as_ref()
457                        .is_some_and(|stamp| !stamp.membership_settled())
458                {
459                    let entries = self.entries(path)?;
460                    if entries.as_ref() != self.directory_entries.get(path)
461                        || membership_stamp(path)? != after
462                    {
463                        return Ok((false, false));
464                    }
465                }
466            } else {
467                let recent = after
468                    .as_ref()
469                    .is_some_and(|stamp| !stamp.membership_settled());
470                if (*before != after || recent)
471                    && let Some(content) = self.ignore_contents.get(path)
472                {
473                    if ignore_content(path, &after)?.as_ref() != Some(content) {
474                        return Ok((false, false));
475                    }
476                    continue;
477                }
478                if *before != after {
479                    return Ok((false, false));
480                }
481                settled &= !recent;
482            }
483        }
484        Ok((true, settled))
485    }
486
487    /// Retain a matched listing and policy for use after releasing the lock.
488    fn candidates(&self) -> Candidates {
489        Candidates {
490            files: self.files.clone(),
491            source_ignore: self.source_ignore.clone(),
492        }
493    }
494}
495
496/// Find Git index, exclusion and config files that can change source visibility,
497/// including absent policy files whose later creation must invalidate reuse.
498fn git_membership_policies(root: &Path) -> BTreeSet<PathBuf> {
499    let mut policies = BTreeSet::new();
500    if let Ok(output) = paths::git(
501        root,
502        &[
503            "rev-parse",
504            "--path-format=absolute",
505            "--git-path",
506            "index",
507            "--git-path",
508            "info/exclude",
509            "--git-path",
510            "config",
511            "--git-path",
512            "config.worktree",
513        ],
514    ) && output.status.success()
515        && let Ok(paths) = String::from_utf8(output.stdout)
516    {
517        policies.extend(paths.lines().map(PathBuf::from));
518    }
519    // Config can include other files. Track every origin used by Git, as
520    // well as currently missing standard config and excludes files.
521    if let Ok(output) = paths::git(root, &["config", "--null", "--show-origin", "--list"])
522        && output.status.success()
523    {
524        // NUL mode emits raw origins, without Git's C-style path quoting,
525        // and separates each origin from its key/newline/value record. Values
526        // may themselves contain newlines (including include/excludes paths).
527        let output = String::from_utf8_lossy(&output.stdout);
528        let mut fields = output.split_terminator('\0');
529        while let (Some(origin), Some(entry)) = (fields.next(), fields.next()) {
530            if let Some(path) = origin.strip_prefix("file:") {
531                let origin = root.join(path);
532                if let Some((name, value)) = entry.split_once('\n')
533                    && name.starts_with("include")
534                    && name.ends_with(".path")
535                {
536                    let included = if let Some(relative) = value.strip_prefix("~/") {
537                        std::env::var_os("HOME")
538                            .map(PathBuf::from)
539                            .unwrap_or_default()
540                            .join(relative)
541                    } else {
542                        origin.parent().unwrap_or(root).join(value)
543                    };
544                    // Git omits missing includes from the origin listing, but
545                    // creating one later can change core.excludesfile.
546                    policies.insert(included);
547                }
548                policies.insert(origin);
549            }
550        }
551    }
552    if let Ok(output) = paths::git(
553        root,
554        &["config", "--null", "--path", "--get", "core.excludesfile"],
555    ) && output.status.success()
556        && let Ok(path) = String::from_utf8(output.stdout)
557    {
558        policies.insert(root.join(path.strip_suffix('\0').unwrap_or(&path)));
559    }
560    for variable in ["GIT_CONFIG_SYSTEM", "GIT_CONFIG_GLOBAL"] {
561        if let Some(path) = std::env::var_os(variable) {
562            policies.insert(PathBuf::from(path));
563        }
564    }
565    policies.insert(PathBuf::from("/etc/gitconfig"));
566    if let Some(home) = std::env::var_os("HOME") {
567        let home = PathBuf::from(home);
568        policies.insert(home.join(".gitconfig"));
569        let config = std::env::var_os("XDG_CONFIG_HOME")
570            .map(PathBuf::from)
571            .unwrap_or_else(|| home.join(".config"));
572        policies.insert(config.join("git/config"));
573        policies.insert(config.join("git/ignore"));
574    }
575    policies
576}
577
578/// Read a regular ignore policy only when the captured metadata remains stable.
579/// A digest read after a listing must never replace the pre-listing digest.
580fn ignore_content(path: &Path, expected: &Option<Stamp>) -> Result<Option<String>> {
581    if expected.is_none() || membership_stamp(path)? != *expected {
582        return Ok(None);
583    }
584    match std::fs::symlink_metadata(path) {
585        Ok(metadata) if metadata.is_file() => {}
586        Ok(_) => return Ok(None),
587        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
588        Err(error) => return Err(error.into()),
589    }
590    let content = match std::fs::read(path) {
591        Ok(content) => content,
592        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
593        Err(error) => return Err(error.into()),
594    };
595    Ok((membership_stamp(path)? == *expected).then(|| blake3::hash(&content).to_hex().to_string()))
596}
597
598/// Stamp a directory or listing policy, including a symlink's resolved target.
599fn membership_stamp(path: &Path) -> Result<Option<Stamp>> {
600    match std::fs::symlink_metadata(path) {
601        Ok(metadata) => {
602            let mut stamp = Stamp::new(&metadata);
603            if metadata.is_symlink() {
604                // Follow the current chain on every check. In-place target
605                // edits or retargeted intermediate links can change policy.
606                match std::fs::metadata(path) {
607                    Ok(target) => stamp.0.extend(Stamp::new(&target).0),
608                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => stamp.0[1] = -1,
609                    Err(error) => return Err(error.into()),
610                }
611            }
612            Ok(Some(stamp))
613        }
614        Err(error)
615            if matches!(
616                error.kind(),
617                std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
618            ) =>
619        {
620            Ok(None)
621        }
622        Err(error) => Err(error).with_context(|| format!("cannot inspect {}", path.display())),
623    }
624}
625
626/// One dependency task's output files, and the value of each one a pattern
627/// has selected so far.
628struct DependencyOutputs {
629    anchors: Vec<String>,
630    files: Vec<String>,
631    values: Mutex<HashMap<String, Value>>,
632}
633
634/// One revision of `pnpm-lock.yaml`, with digests of what it installs computed
635/// once and shared by every task that asks.
636struct Installed {
637    content: String,
638    /// `None` when the file cannot be read as a pnpm v9 lockfile.
639    lockfile: Option<Lockfile>,
640    digests: Mutex<HashMap<String, String>>,
641}
642
643impl Installed {
644    fn digest(&self, key: &str, fingerprints: impl FnOnce() -> BTreeSet<String>) -> String {
645        if let Some(digest) = self.digests.lock().unwrap().get(key) {
646            return digest.clone();
647        }
648        let mut hasher = blake3::Hasher::new();
649        for fingerprint in fingerprints() {
650            hasher.update(fingerprint.as_bytes());
651            hasher.update(b"\n");
652        }
653        let digest = hasher.finalize().to_hex().to_string();
654        self.digests
655            .lock()
656            .unwrap()
657            .insert(key.to_owned(), digest.clone());
658        digest
659    }
660}
661
662impl Snapshot {
663    pub fn new(workspace: &Workspace, graph: &TaskGraph, cache_path: &Path) -> Result<Self> {
664        // Every early task needs these, so loading saved digests and parsing
665        // the lockfile overlap listing files.
666        let canonical_root = workspace.root.canonicalize()?;
667        let (files, lockfile, (digests, workspace_prefix)) = std::thread::scope(|scope| {
668            let lockfile = scope.spawn(|| parse_lockfile(&workspace.root.join("pnpm-lock.yaml")));
669            let digests = scope.spawn(|| {
670                let digests = load_digests(&workspace.root);
671                let workspace_prefix = paths::git_path(&workspace.root, "--show-toplevel")
672                    .and_then(|root| root.canonicalize().ok())
673                    .and_then(|root| canonical_root.strip_prefix(root).ok().map(PathBuf::from));
674                (digests, workspace_prefix)
675            });
676            let files = source_files(&workspace.root);
677            (
678                files,
679                lockfile.join().expect("lockfile thread panicked"),
680                digests.join().expect("digest thread panicked"),
681            )
682        });
683        let mut files = files?;
684        let cache_relative = cache_path
685            .strip_prefix(&workspace.root)
686            .ok()
687            .map(PathBuf::from);
688        // Keep the patterns, not only the artifacts present at startup: new
689        // outputs and warm scratch files must be excluded on every refresh.
690        let mut source_exclusions: Vec<_> = graph
691            .tasks
692            .values()
693            .filter_map(|task| Outputs::new(workspace, task).ok())
694            .filter(Outputs::is_explicit)
695            .collect();
696        for task in graph.tasks.values() {
697            let Ok(entries) = crate::warm::config(workspace, task) else {
698                continue;
699            };
700            if let Ok(paths) = Outputs::from_paths(&crate::warm::kept_paths(&entries)) {
701                source_exclusions.push(paths);
702            }
703        }
704        // Scratch directories, which each run empties: what is in them is no
705        // input, before or after the task runs.
706        let mut scratch_paths = Vec::new();
707        for task in graph.tasks.values() {
708            let scratch: Vec<String> = crate::scratch::directories(workspace, task)
709                .unwrap_or_default()
710                .iter()
711                .filter_map(|directory| {
712                    let relative = directory.strip_prefix(&workspace.root).ok()?.to_str()?;
713                    let named = crate::glob::escape(&relative.replace('\\', "/"));
714                    Some([named.clone(), format!("{named}/**")])
715                })
716                .flatten()
717                .collect();
718            if !scratch.is_empty()
719                && let Ok(paths) = Outputs::from_paths(&scratch)
720            {
721                source_exclusions.push(paths.clone());
722                scratch_paths.push(paths);
723            }
724        }
725        exclude_artifacts(&mut files, &source_exclusions, cache_relative.as_deref());
726        Ok(Self {
727            files,
728            extra_candidates: BTreeSet::new(),
729            membership: Mutex::default(),
730            membership_prefixes: Mutex::default(),
731            source_exclusions,
732            scratch: scratch_paths,
733            cache_relative,
734            projects: ProjectGraph::build(workspace)?,
735            roots: workspace
736                .projects
737                .values()
738                .map(|project| (project.root.clone(), project.name.clone()))
739                .collect(),
740            source_ignore: Arc::new(SourceIgnore::new(&workspace.root)?),
741            generated_tasks: graph
742                .tasks
743                .values()
744                .filter_map(|task| {
745                    let outputs = Outputs::new(workspace, task).ok()?;
746                    outputs.is_explicit().then(|| (task.clone(), outputs))
747                })
748                .collect(),
749            task_dependencies: graph
750                .tasks
751                .iter()
752                .map(|(id, task)| (id.clone(), task.dependencies.clone()))
753                .collect(),
754            servers: graph
755                .tasks
756                .keys()
757                .map(|id| (id.clone(), servers(graph, id)))
758                .collect(),
759            canonical_root,
760            workspace_prefix,
761            patterns: Mutex::default(),
762            digests: Mutex::new(digests),
763            digests_changed: Default::default(),
764            ignored_files: Mutex::default(),
765            directories: Mutex::default(),
766            runtime: Mutex::default(),
767            lockfile: Mutex::new(lockfile),
768            dependency_outputs: Mutex::default(),
769            outputs_written: Default::default(),
770        })
771    }
772
773    /// Restrict directory checks to the positive fileset prefixes a task reads.
774    fn membership_prefixes(&self, workspace: &Workspace, task: &Task) -> Result<Arc<Vec<PathBuf>>> {
775        let mut prefixes = self.membership_prefixes.lock().unwrap();
776        if let Some(prefixes) = prefixes.get(&task.id) {
777            return Ok(prefixes.clone());
778        }
779        let empty = BTreeSet::new();
780        let cancelled = AtomicBool::new(false);
781        let mut resolver = Resolver::new(self, workspace, None, &cancelled, &empty);
782        resolver.task_inputs(task)?;
783        let paths = Arc::new(
784            resolver
785                .scopes
786                .values()
787                .flat_map(|scope| &scope.patterns)
788                .filter(|pattern| !pattern.excluded)
789                .map(|pattern| &pattern.prefix)
790                .chain(resolver.json_globs.iter().map(|glob| &glob.prefix))
791                .map(|prefix| workspace.root.join(prefix))
792                .collect(),
793        );
794        prefixes.insert(task.id.clone(), Arc::clone(&paths));
795        Ok(paths)
796    }
797
798    /// Reuse membership while source directories and listing policy are unchanged.
799    /// Content changes are checked separately by the file digest cache.
800    #[cfg(test)]
801    fn current_files(&self, root: &Path) -> Result<Arc<BTreeSet<String>>> {
802        Ok(self.current_files_for(root, None, "test")?.files)
803    }
804
805    /// Refresh candidates as needed, returning their policy in the same snapshot.
806    fn current_files_for(
807        &self,
808        root: &Path,
809        prefixes: Option<&[PathBuf]>,
810        task: &str,
811    ) -> Result<Candidates> {
812        let requested = Instant::now();
813        loop {
814            let previous = self.membership.lock().unwrap().clone();
815            // Immutable entries let independent fingerprints validate their
816            // directory stamps concurrently. Only a refresh needs serialization.
817            let (unchanged, settled) = match &previous {
818                Some(entry) => entry.state(prefixes)?,
819                None => (false, false),
820            };
821            if settled && previous.as_ref().unwrap().settled {
822                return Ok(previous.as_ref().unwrap().candidates());
823            }
824            // A refresh holds this lock while it lists the workspace, so time
825            // spent here is time waiting for another task's listing.
826            let waiting = crate::profile::span(task, "inventory_wait");
827            let mut cached = self.membership.lock().unwrap();
828            drop(waiting);
829            // A listing that began after this call reflects every change made
830            // before it, so it is as current as one made now. Tasks queued
831            // behind a refresh share the next one instead of each listing the
832            // workspace in turn.
833            if let Some(entry) = &*cached
834                && entry.listed.is_some_and(|listed| listed >= requested)
835            {
836                return Ok(entry.candidates());
837            }
838            let current = match (&previous, &*cached) {
839                (Some(previous), Some(current)) => Arc::ptr_eq(previous, current),
840                (None, None) => true,
841                _ => false,
842            };
843            if !current {
844                // Another fingerprint refreshed while this one validated.
845                // Recheck that newer inventory before making any replacement.
846                continue;
847            }
848            drop(previous);
849            let _listing = crate::profile::span(task, "inventory_list");
850            let listed = Instant::now();
851            // Recent listing policies may conceal edits on coarse filesystems.
852            // Re-list sources while they settle, then rebuild the directory inventory
853            // once before enabling reuse (including any newly created empty dirs).
854            // Recent directories are checked by freshly reading their child names.
855            let rebuilt = !unchanged || settled;
856            let mut membership = if !rebuilt {
857                Arc::unwrap_or_clone(cached.take().unwrap())
858            } else {
859                // Capture directories before listing files, then compare afterward.
860                // An addition during listing must not hide behind a newer stamp.
861                Membership::new(
862                    root,
863                    cached.as_ref().map_or(&self.files, |entry| &entry.files),
864                    &self.source_ignore,
865                    &self.source_exclusions,
866                    self.cache_relative.as_deref(),
867                    cached
868                        .as_ref()
869                        .filter(|entry| unchanged && entry.settled)
870                        .map(|entry| &entry.git_policies),
871                )?
872            };
873            let mut files = source_files(root)?;
874            exclude_artifacts(
875                &mut files,
876                &self.source_exclusions,
877                self.cache_relative.as_deref(),
878            );
879            let ignore = SourceIgnore::new(root)?;
880            files.extend(
881                self.extra_candidates
882                    .iter()
883                    .filter(|path| !ignore.matches(path))
884                    .cloned(),
885            );
886            membership.source_ignore = Arc::new(ignore);
887            membership.files = Arc::new(files);
888            let candidates = membership.candidates();
889            // An unstable inventory or recent policy never enables the fast path.
890            // Keep candidates so a rebuild also watches tracked, ignored parents.
891            let covered = candidates.files.iter().all(|path| {
892                Path::new(path)
893                    .ancestors()
894                    .skip(1)
895                    .all(|parent| membership.stamps.contains_key(&root.join(parent)))
896            });
897            membership.settled = rebuilt && covered && membership.state(None)?.1;
898            membership.listed = Some(listed);
899            *cached = Some(Arc::new(membership));
900            return Ok(candidates);
901        }
902    }
903
904    /// Saves the digests of files that still exist, for the next run.
905    pub fn save_digests(&self, root: &Path) {
906        if !self
907            .digests_changed
908            .load(std::sync::atomic::Ordering::Relaxed)
909        {
910            return;
911        }
912        let digests = self.digests.lock().unwrap();
913        let ignored = self.ignored_files.lock().unwrap();
914        let entries: BTreeMap<&String, (&Stamp, &String)> = digests
915            .iter()
916            .filter(|(path, _)| self.files.contains(*path) || ignored.contains(*path))
917            .map(|(path, (stamp, digest))| (path, (stamp, digest)))
918            .collect();
919        let path = digests_path(root);
920        let saved = (|| -> Result<()> {
921            let directory = path.parent().context("digests have a directory")?;
922            std::fs::create_dir_all(directory)?;
923            let mut file = tempfile::NamedTempFile::new_in(directory)?;
924            {
925                let mut writer = std::io::BufWriter::new(file.as_file_mut());
926                serde_json::to_writer(&mut writer, &json!({"version": 1, "entries": entries}))?;
927                writer.flush()?;
928            }
929            file.persist(&path)?;
930            Ok(())
931        })();
932        if let Err(error) = saved {
933            qk_executor::status!("qk: could not save file digests: {error:#}");
934        }
935    }
936
937    /// `paths::safe_parents`, checking each directory once per run.
938    fn safe_parents(&self, root: &Path, path: &str) -> Result<()> {
939        paths::validate_path(path)?;
940        let mut current = root.to_owned();
941        for part in Path::new(path)
942            .parent()
943            .into_iter()
944            .flat_map(Path::components)
945        {
946            current.push(part);
947            if self.directories.lock().unwrap().contains(&current) {
948                continue;
949            }
950            match std::fs::symlink_metadata(&current) {
951                Ok(metadata) if metadata.file_type().is_symlink() => {
952                    bail!("input parent is a symlink: {}", current.display())
953                }
954                Ok(metadata) if !metadata.is_dir() => {
955                    bail!("input parent is not a directory: {}", current.display())
956                }
957                Ok(_) => {
958                    self.directories.lock().unwrap().insert(current.clone());
959                }
960                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
961                Err(error) => return Err(error.into()),
962            }
963        }
964        Ok(())
965    }
966
967    fn installed(&self, root: &Path, task: &str) -> Result<Option<Arc<Installed>>> {
968        let absolute = root.join("pnpm-lock.yaml");
969        let Ok(metadata) = std::fs::symlink_metadata(&absolute) else {
970            return Ok(None);
971        };
972        if !metadata.is_file() {
973            return Ok(None);
974        }
975        let content = self.digest("pnpm-lock.yaml", &absolute, &metadata)?;
976        let mut current = self.lockfile.lock().unwrap();
977        if let Some(installed) = &*current
978            && installed.content == content
979        {
980            return Ok(Some(installed.clone()));
981        }
982        let parsing = crate::profile::span(task, "lockfile_parse");
983        let parsed = parse_lockfile(&absolute);
984        drop(parsing);
985        let Some(installed) = parsed else {
986            return Ok(None);
987        };
988        *current = Some(installed.clone());
989        Ok(Some(installed))
990    }
991
992    /// Adds paths to the candidate files, such as files deleted since a base
993    /// revision.
994    pub fn with_candidates(mut self, paths: &[String]) -> Self {
995        self.files.extend(
996            paths
997                .iter()
998                .filter(|path| !self.source_ignore.matches(path))
999                .cloned(),
1000        );
1001        self.extra_candidates.extend(paths.iter().cloned());
1002        self
1003    }
1004
1005    fn pattern(&self, pattern: &str, negated: bool) -> Result<Arc<Pattern>> {
1006        self.compiled(pattern, negated, false)
1007    }
1008
1009    /// A fileset's pattern, see [`Pattern::fileset`].
1010    fn fileset_pattern(&self, pattern: &str, negated: bool) -> Result<Arc<Pattern>> {
1011        self.compiled(pattern, negated, true)
1012    }
1013
1014    fn compiled(&self, pattern: &str, negated: bool, fileset: bool) -> Result<Arc<Pattern>> {
1015        let key = (pattern.to_owned(), negated, fileset);
1016        if let Some(pattern) = self.patterns.lock().unwrap().get(&key) {
1017            return Ok(pattern.clone());
1018        }
1019        let compiled = Arc::new(if fileset {
1020            Pattern::fileset(pattern, negated)?
1021        } else {
1022            Pattern::new(pattern, negated)?
1023        });
1024        self.patterns.lock().unwrap().insert(key, compiled.clone());
1025        Ok(compiled)
1026    }
1027
1028    fn digest(&self, path: &str, absolute: &Path, metadata: &std::fs::Metadata) -> Result<String> {
1029        let stamp = Stamp::new(metadata);
1030        if let Some((known, digest)) = self.digests.lock().unwrap().get(path)
1031            && *known == stamp
1032        {
1033            return Ok(digest.clone());
1034        }
1035        let digest = digest_file(absolute)?;
1036        // Re-check after reading so a concurrent write is never recorded as settled.
1037        let after = Stamp::new(&std::fs::symlink_metadata(absolute)?);
1038        if after == stamp && stamp.settled() {
1039            self.digests
1040                .lock()
1041                .unwrap()
1042                .insert(path.to_owned(), (stamp, digest.clone()));
1043            self.digests_changed
1044                .store(true, std::sync::atomic::Ordering::Relaxed);
1045        }
1046        Ok(digest)
1047    }
1048
1049    /// `task`'s output files that are not directories, as listed since the
1050    /// last task that could have written them was done.
1051    fn dependency_outputs(
1052        &self,
1053        workspace: &Workspace,
1054        task: &Task,
1055    ) -> Result<Arc<DependencyOutputs>> {
1056        if let Some(outputs) = self.dependency_outputs.lock().unwrap().get(&task.id) {
1057            return Ok(outputs.clone());
1058        }
1059        let written = self
1060            .outputs_written
1061            .load(std::sync::atomic::Ordering::SeqCst);
1062        let outputs = Arc::new(self.fresh_dependency_outputs(workspace, task)?);
1063        let mut listed = self.dependency_outputs.lock().unwrap();
1064        if self
1065            .outputs_written
1066            .load(std::sync::atomic::Ordering::SeqCst)
1067            != written
1068        {
1069            return Ok(outputs);
1070        }
1071        Ok(listed.entry(task.id.clone()).or_insert(outputs).clone())
1072    }
1073
1074    /// Re-list artifacts for verification, without reusing earlier content values.
1075    fn fresh_dependency_outputs(
1076        &self,
1077        workspace: &Workspace,
1078        task: &Task,
1079    ) -> Result<DependencyOutputs> {
1080        let declared = Outputs::new(workspace, task)?;
1081        let mut files = Vec::new();
1082        for entry in declared.entries(&workspace.root)? {
1083            let (path, metadata) = entry?;
1084            if !metadata.is_dir() {
1085                files.push(path);
1086            }
1087        }
1088        Ok(DependencyOutputs {
1089            anchors: declared.anchors().map(str::to_owned).collect(),
1090            files,
1091            values: Mutex::default(),
1092        })
1093    }
1094
1095    /// Drops the listings `task` may have changed, once it is done. Without
1096    /// its outputs, every listing goes.
1097    pub(crate) fn outputs_written(&self, workspace: &Workspace, task: &Task) {
1098        let anchors: Option<Vec<String>> = Outputs::new(workspace, task)
1099            .ok()
1100            .filter(Outputs::is_explicit)
1101            .map(|outputs| outputs.anchors().map(str::to_owned).collect());
1102        let overlap = |a: &str, b: &str| {
1103            a == b
1104                || b.strip_prefix(a).is_some_and(|rest| rest.starts_with('/'))
1105                || a.strip_prefix(b).is_some_and(|rest| rest.starts_with('/'))
1106        };
1107        let mut listed = self.dependency_outputs.lock().unwrap();
1108        self.outputs_written
1109            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1110        listed.retain(|_, outputs| {
1111            anchors.as_ref().is_some_and(|written| {
1112                !written
1113                    .iter()
1114                    .any(|a| outputs.anchors.iter().any(|b| overlap(a, b)))
1115            })
1116        });
1117    }
1118
1119    /// A file an `includeIgnored` fileset read, by the content it points to
1120    /// wherever that is, as Nx reads it; `None` when it is gone.
1121    fn ignored_value(&self, root: &Path, path: &str) -> Result<Option<Value>> {
1122        let absolute = root.join(path);
1123        let metadata = match std::fs::metadata(&absolute) {
1124            Ok(metadata) if metadata.is_file() => metadata,
1125            Ok(_) => return Ok(None),
1126            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1127            Err(error) => return Err(error.into()),
1128        };
1129        let mode = crate::store::mode(&metadata) & 0o111 != 0;
1130        self.ignored_files.lock().unwrap().insert(path.to_owned());
1131        Ok(Some(
1132            json!({"content":self.digest(path, &absolute, &metadata)?, "mode":mode}),
1133        ))
1134    }
1135
1136    /// A file a recording read, keyed as an input file is.
1137    pub(crate) fn recorded_value(&self, root: &Path, path: &str) -> Result<Value> {
1138        self.file_value(root, path)
1139    }
1140
1141    fn file_value(&self, root: &Path, path: &str) -> Result<Value> {
1142        self.file_value_with_links(root, path, &mut BTreeSet::new())
1143    }
1144
1145    fn file_value_with_links(
1146        &self,
1147        root: &Path,
1148        path: &str,
1149        visiting: &mut BTreeSet<PathBuf>,
1150    ) -> Result<Value> {
1151        self.safe_parents(root, path)?;
1152        let absolute = root.join(path);
1153        let metadata = std::fs::symlink_metadata(&absolute)?;
1154        if metadata.file_type().is_symlink() {
1155            let target = std::fs::read_link(&absolute)?;
1156            // A dangling link is keyed as such, so the key changes once it resolves.
1157            let Ok(resolved) = absolute.canonicalize() else {
1158                return Ok(json!({"link":target, "dangling":true}));
1159            };
1160            let Ok(relative) = resolved.strip_prefix(&self.canonical_root) else {
1161                bail!("input symlink resolves outside the workspace: {path}");
1162            };
1163            if resolved.is_file() {
1164                let metadata = std::fs::metadata(&resolved)?;
1165                let key = paths::relative(Path::new(""), relative)?;
1166                return Ok(
1167                    json!({"link":target, "content":self.digest(&key, &resolved, &metadata)?,
1168                    "mode":crate::store::mode(&metadata) & 0o111 != 0}),
1169                );
1170            }
1171            let relative = paths::relative(Path::new(""), relative)?;
1172            if relative.is_empty() {
1173                bail!("input symlink resolves to the workspace root: {path}");
1174            }
1175            if !visiting.insert(resolved.clone()) {
1176                bail!("directory input symlink cycle: {path}");
1177            }
1178            let mut contents = BTreeMap::new();
1179            // Selecting the link explicitly reads its target, even when source
1180            // discovery ignores that target or another link is nested inside it.
1181            for entry in walkdir::WalkDir::new(&resolved).follow_links(false) {
1182                let entry = entry?;
1183                if entry.file_type().is_dir() {
1184                    continue;
1185                }
1186                let file = paths::relative(&self.canonical_root, entry.path())?;
1187                let value = self.file_value_with_links(&self.canonical_root, &file, visiting)?;
1188                contents.insert(
1189                    file.strip_prefix(&relative).unwrap_or(&file).to_owned(),
1190                    value,
1191                );
1192            }
1193            visiting.remove(&resolved);
1194            return Ok(json!({"link":target, "directory":contents}));
1195        }
1196        if !metadata.is_file() {
1197            bail!("input is not a regular file: {path}");
1198        }
1199        // Only the executable bit, which is all git records: other permission
1200        // bits follow the checkout's umask and would keep machines apart.
1201        let mode = crate::store::mode(&metadata) & 0o111 != 0;
1202        Ok(json!({"content":self.digest(path, &absolute, &metadata)?, "mode":mode}))
1203    }
1204}
1205
1206/// Reads and parses a pnpm lockfile, `None` when there is none. One qk cannot
1207/// read is reported, and kept as unreadable so tasks key its whole content.
1208fn parse_lockfile(path: &Path) -> Option<Arc<Installed>> {
1209    let text = std::fs::read_to_string(path).ok()?;
1210    let lockfile = match Lockfile::parse(&text) {
1211        Ok(lockfile) => Some(lockfile),
1212        Err(error) => {
1213            qk_executor::status!("qk: pnpm-lock.yaml: keying tasks by the whole file ({error:#})");
1214            None
1215        }
1216    };
1217    Some(Arc::new(Installed {
1218        content: blake3::hash(text.as_bytes()).to_hex().to_string(),
1219        lockfile,
1220        digests: Mutex::default(),
1221    }))
1222}
1223
1224fn load_digests(root: &Path) -> HashMap<String, (Stamp, String)> {
1225    #[derive(serde::Deserialize)]
1226    struct Saved {
1227        version: u32,
1228        entries: HashMap<String, (Stamp, String)>,
1229    }
1230    std::fs::read(digests_path(root))
1231        .ok()
1232        .and_then(|bytes| serde_json::from_slice::<Saved>(&bytes).ok())
1233        .filter(|saved| saved.version == 1)
1234        .map(|saved| saved.entries)
1235        .unwrap_or_default()
1236}
1237
1238/// Apply the same source policy to startup and refreshed file membership.
1239/// Remove declared artifacts and cache storage from a refreshed source listing.
1240fn exclude_artifacts(files: &mut BTreeSet<String>, outputs: &[Outputs], cache: Option<&Path>) {
1241    let mut generated = BTreeSet::new();
1242    for outputs in outputs {
1243        for anchor in outputs.anchors() {
1244            generated.extend(
1245                under(files, anchor)
1246                    .filter(|path| outputs.matches(path))
1247                    .cloned(),
1248            );
1249        }
1250    }
1251    files.retain(|path| {
1252        !generated.contains(path) && cache.is_none_or(|cache| !Path::new(path).starts_with(cache))
1253    });
1254}
1255
1256/// Files equal to `prefix` or below it, using the sorted order of the set.
1257impl Snapshot {
1258    /// The project whose root most specifically contains `path`, as Nx assigns
1259    /// files to projects.
1260    fn owner(&self, path: &str) -> Option<&str> {
1261        let mut path = path;
1262        loop {
1263            if let Some(project) = self.roots.get(path) {
1264                return Some(project);
1265            }
1266            match path.rfind('/') {
1267                Some(slash) => path = &path[..slash],
1268                None if path != "." => path = ".",
1269                None => return None,
1270            }
1271        }
1272    }
1273}
1274
1275fn under<'a>(files: &'a BTreeSet<String>, prefix: &'a str) -> impl Iterator<Item = &'a String> {
1276    files
1277        .range::<str, _>((
1278            std::ops::Bound::Included(prefix),
1279            std::ops::Bound::Unbounded,
1280        ))
1281        .take_while(move |path| path.starts_with(prefix))
1282        .filter(move |path| path.len() == prefix.len() || path.as_bytes()[prefix.len()] == b'/')
1283}
1284
1285/// Compiled root ignore rules used by input discovery and project watching.
1286pub struct SourceIgnore(ignore::gitignore::Gitignore);
1287
1288impl SourceIgnore {
1289    /// Root ignore rules shared by caching and watch, including tracked files.
1290    pub fn new(root: &Path) -> Result<Self> {
1291        let mut builder = ignore::gitignore::GitignoreBuilder::new(root);
1292        for name in [".gitignore", ".nxignore"] {
1293            let path = root.join(name);
1294            if path.is_file()
1295                && let Some(error) = builder.add(path)
1296            {
1297                return Err(error.into());
1298            }
1299        }
1300        Ok(Self(builder.build()?))
1301    }
1302
1303    fn matches_directory(&self, path: &str) -> bool {
1304        self.matches(path) || self.0.matched(path, true).is_ignore()
1305    }
1306
1307    /// Whether a workspace-relative file or its parent is ignored.
1308    pub fn matches(&self, path: &str) -> bool {
1309        // A file whitelist cannot reinclude it beneath an excluded directory.
1310        Path::new(path)
1311            .ancestors()
1312            .skip(1)
1313            .take_while(|parent| !parent.as_os_str().is_empty())
1314            .any(|parent| self.0.matched(parent, true).is_ignore())
1315            || self.0.matched(path, false).is_ignore()
1316    }
1317}
1318
1319/// Source files visible to Nx, with runner state and root ignore rules removed.
1320pub fn source_files(root: &Path) -> Result<BTreeSet<String>> {
1321    let lines =
1322        |output: std::io::Result<std::process::Output>| -> Option<Result<BTreeSet<String>>> {
1323            let output = output.ok().filter(|output| output.status.success())?;
1324            Some(
1325                output
1326                    .stdout
1327                    .split(|byte| *byte == 0)
1328                    .filter(|path| !path.is_empty())
1329                    .map(|path| {
1330                        String::from_utf8(path.to_vec()).context("input paths must be UTF-8")
1331                    })
1332                    .collect(),
1333            )
1334        };
1335    // Tracked files deleted from the working tree are listed as cached; git
1336    // names them in a second listing, which is cheaper than checking each file.
1337    // Skip-worktree entries are listed whether or not they are on disk and never
1338    // as deleted, so those few are checked; `-v` tags them `S`.
1339    let (listed, deleted) = if root.join(".nxignore").is_file() {
1340        // Nx negations can reinclude Git-ignored files, so this policy needs
1341        // the walker regardless of what Git lists. Avoid launching Git here.
1342        (None, None)
1343    } else {
1344        std::thread::scope(|scope| {
1345            let deleted =
1346                scope.spawn(|| paths::git(root, &["ls-files", "--deleted", "-z", "--", "."]));
1347            let listed = paths::git(
1348                root,
1349                &[
1350                    "ls-files",
1351                    "-v",
1352                    "--cached",
1353                    "--others",
1354                    "--exclude-standard",
1355                    "-z",
1356                    "--",
1357                    ".",
1358                ],
1359            );
1360            (
1361                lines(listed),
1362                lines(deleted.join().expect("git listing thread panicked")),
1363            )
1364        })
1365    };
1366    let candidates = match (listed, deleted) {
1367        (Some(listed), Some(deleted)) => {
1368            let deleted = deleted?;
1369            let mut files = BTreeSet::new();
1370            for entry in listed? {
1371                let Some((tag, path)) = entry.split_once(' ') else {
1372                    bail!("unexpected git ls-files entry {entry:?}");
1373                };
1374                let absent =
1375                    matches!(tag, "S" | "s") && std::fs::symlink_metadata(root.join(path)).is_err();
1376                if !absent && !deleted.contains(path) {
1377                    files.insert(path.to_owned());
1378                }
1379            }
1380            files
1381        }
1382        _ => {
1383            let mut files = BTreeSet::new();
1384            for entry in ignore::WalkBuilder::new(root)
1385                .hidden(false)
1386                .parents(false)
1387                .git_global(false)
1388                .require_git(false)
1389                .ignore(false)
1390                .add_custom_ignore_filename(".nxignore")
1391                .follow_links(false)
1392                .filter_entry(|entry| {
1393                    !matches!(
1394                        entry.file_name().to_str(),
1395                        Some(".git" | ".qk" | "node_modules")
1396                    )
1397                })
1398                .build()
1399            {
1400                let entry = entry?;
1401                if entry.file_type().is_some_and(|kind| !kind.is_dir()) {
1402                    files.insert(paths::relative(root, entry.path())?);
1403                }
1404            }
1405            files
1406        }
1407    };
1408    let ignore = SourceIgnore::new(root)?;
1409    Ok(candidates
1410        .into_iter()
1411        .filter(|path| {
1412            !ignore.matches(path)
1413                && !path
1414                    .split('/')
1415                    .any(|part| matches!(part, ".git" | ".qk" | "node_modules"))
1416        })
1417        .collect())
1418}
1419
1420/// The text of `path` as a `json` input keys it: only `fields` when given,
1421/// without `exclude`. A `.yaml` or `.yml` file is read as YAML, and any other
1422/// as JSON or JSONC. `None` when it cannot be read so.
1423pub(crate) fn json_projection(path: &str, text: &str, fields: &JsonFields) -> Option<Value> {
1424    let mut value: Value = if path.ends_with(".yaml") || path.ends_with(".yml") {
1425        serde_yaml_ng::from_str(text).ok()?
1426    } else {
1427        jsonc_parser::parse_to_serde_value(text, &Default::default()).ok()?
1428    };
1429    if let Some(fields) = &fields.fields {
1430        let mut kept = json!({});
1431        for field in fields {
1432            if let Some(found) = json_path(&value, field) {
1433                set_json_path(&mut kept, field, found.clone());
1434            }
1435        }
1436        value = kept;
1437    }
1438    for field in &fields.exclude {
1439        remove_json_path(&mut value, field);
1440    }
1441    Some(value)
1442}
1443
1444fn json_path<'v>(value: &'v Value, path: &str) -> Option<&'v Value> {
1445    path.split('.')
1446        .try_fold(value, |value, part| value.get(part))
1447}
1448
1449fn set_json_path(target: &mut Value, path: &str, value: Value) {
1450    let mut parts = path.split('.').peekable();
1451    let mut current = target;
1452    while let Some(part) = parts.next() {
1453        let Value::Object(object) = current else {
1454            return;
1455        };
1456        if parts.peek().is_none() {
1457            object.insert(part.to_owned(), value);
1458            return;
1459        }
1460        current = object.entry(part).or_insert_with(|| json!({}));
1461    }
1462}
1463
1464fn remove_json_path(target: &mut Value, path: &str) {
1465    let (parent, last) = match path.rsplit_once('.') {
1466        Some((parent, last)) => (Some(parent), last),
1467        None => (None, path),
1468    };
1469    let parent = match parent {
1470        Some(parent) => parent
1471            .split('.')
1472            .try_fold(&mut *target, |value, part| value.get_mut(part)),
1473        None => Some(target),
1474    };
1475    if let Some(Value::Object(object)) = parent {
1476        object.remove(last);
1477    }
1478}
1479
1480struct FilePattern {
1481    matcher: Arc<Pattern>,
1482    prefix: String,
1483    /// The glob after `prefix`, the literal directory it starts with; `None`
1484    /// when the pattern names one path.
1485    rest: Option<String>,
1486    excluded: bool,
1487    /// The project a project fileset selects the files of.
1488    owner: Option<String>,
1489}
1490
1491/// The patterns of a task's declared filesets, by the scope they select in:
1492/// kept to tell whether a file where there is none would be selected, as
1493/// [`Coverage`] asks.
1494#[derive(Default)]
1495pub struct Selection {
1496    scopes: Vec<Vec<FilePattern>>,
1497}
1498
1499impl Selection {
1500    /// Whether a file at `path` would be selected, gitignore aside: an
1501    /// included pattern of a scope matches it, and none of that scope's
1502    /// exclusions does.
1503    fn selects(&self, snapshot: &Snapshot, path: &str) -> bool {
1504        let applies = |pattern: &FilePattern| {
1505            pattern.matcher.is_match(path)
1506                && (pattern.owner.is_none() || snapshot.owner(path) == pattern.owner.as_deref())
1507        };
1508        self.scopes.iter().any(|patterns| {
1509            patterns
1510                .iter()
1511                .any(|pattern| !pattern.excluded && applies(pattern))
1512                && !patterns
1513                    .iter()
1514                    .any(|pattern| pattern.excluded && applies(pattern))
1515        })
1516    }
1517
1518    /// Whether every entry `directory` could hold, at any depth, would be
1519    /// selected, gitignore aside: an included pattern of a scope takes all of
1520    /// what is under a directory at or above it, and none of that scope's
1521    /// exclusions reaches into it. `""` is the workspace root.
1522    fn selects_every_entry(&self, snapshot: &Snapshot, directory: &str) -> bool {
1523        let within = |prefix: &str| {
1524            prefix.is_empty()
1525                || directory == prefix
1526                || directory
1527                    .strip_prefix(prefix)
1528                    .is_some_and(|rest| rest.starts_with('/'))
1529        };
1530        let reaches = |prefix: &str| {
1531            within(prefix)
1532                || directory.is_empty()
1533                || prefix
1534                    .strip_prefix(directory)
1535                    .is_some_and(|rest| rest.starts_with('/'))
1536        };
1537        let owner = snapshot.owner(if directory.is_empty() { "." } else { directory });
1538        self.scopes.iter().any(|patterns| {
1539            patterns.iter().any(|pattern| {
1540                !pattern.excluded
1541                    && within(&pattern.prefix)
1542                    && matches!(pattern.rest.as_deref(), Some("**" | "**/*"))
1543                    && (pattern.owner.is_none() || owner == pattern.owner.as_deref())
1544            }) && !patterns
1545                .iter()
1546                .any(|pattern| pattern.excluded && reaches(&pattern.prefix))
1547        })
1548    }
1549}
1550
1551/// What a task's declared key holds of the workspace's files, to tell
1552/// whether it keys everything a recording says the task read, looked for
1553/// and listed: when it does, a result under the declared key is as sound as
1554/// qk's keys are without recordings. A file qk keys by part of its content,
1555/// such as a dependency's `package.json` or a `json` input, counts as keyed,
1556/// as it does for every task's key.
1557pub(crate) struct Coverage {
1558    resolved: Resolved,
1559    /// Each `dependentTasksOutputFiles` glob, with the declared outputs of
1560    /// the tasks it reads.
1561    dependency_outputs: Vec<(Arc<Pattern>, Vec<Outputs>)>,
1562}
1563
1564/// What `task`'s declared key covers: see [`Coverage`].
1565pub(crate) fn coverage(
1566    snapshot: &Snapshot,
1567    workspace: &Workspace,
1568    graph: &TaskGraph,
1569    task: &Task,
1570    prepared: &PreparedTask,
1571    cancelled: &AtomicBool,
1572) -> Result<Coverage> {
1573    let resolved = resolve(snapshot, workspace, task, Some(prepared), cancelled)?;
1574    let selections: Vec<(String, bool)> = resolved
1575        .dependency_output_inputs()
1576        .map(|(pattern, transitive)| (pattern.to_owned(), transitive))
1577        .collect();
1578    let mut dependency_outputs = Vec::new();
1579    for (pattern, transitive) in selections {
1580        let matcher = snapshot.pattern(&pattern, false)?;
1581        let mut selected = task.dependencies.clone();
1582        if transitive {
1583            let mut pending = selected.clone();
1584            while let Some(id) = pending.pop_first() {
1585                for dependency in &graph.tasks[&id].dependencies {
1586                    if selected.insert(dependency.clone()) {
1587                        pending.insert(dependency.clone());
1588                    }
1589                }
1590            }
1591        }
1592        let mut outputs = Vec::new();
1593        for id in selected {
1594            let declared = Outputs::new(workspace, &graph.tasks[&id])?;
1595            if declared.declared() {
1596                outputs.push(declared);
1597            }
1598        }
1599        dependency_outputs.push((matcher, outputs));
1600    }
1601    Ok(Coverage {
1602        resolved,
1603        dependency_outputs,
1604    })
1605}
1606
1607impl Coverage {
1608    /// Whether the declared key holds the content of the file at `path`, or
1609    /// what of it reaches tasks, by its declared inputs or by what qk adds.
1610    fn keyed(&self, path: &str) -> bool {
1611        let inferred = &self.resolved.inferred;
1612        self.resolved.is_whole_file(path)
1613            || self.resolved.is_json_input(path)
1614            || inferred.manifests.contains_key(path)
1615            || inferred.tsconfig.as_deref() == Some(path)
1616            || inferred.settings.contains(path)
1617            || inferred.project.contains(path)
1618            || (inferred.workspace_file && path == "pnpm-workspace.yaml")
1619            || (inferred.lockfile.is_some() && path == "pnpm-lock.yaml")
1620            || self.dependency_outputs.iter().any(|(matcher, outputs)| {
1621                matcher.is_match(path) && outputs.iter().any(|outputs| outputs.matches(path))
1622            })
1623    }
1624
1625    /// Whether the declared key covers every path of `set`: each file read
1626    /// or found is keyed, or a directory found holds a keyed file, so that
1627    /// its going changes the key; a file created where one was looked for
1628    /// would be selected, and is neither gitignored nor a declared output;
1629    /// and every entry a listed directory could gain or lose that is not
1630    /// gitignored would be selected, the directory being no declared output.
1631    /// A declared output never enters the declared files, unless a
1632    /// `dependentTasksOutputFiles` input keys it.
1633    /// `output` says whether a path is a declared output of any target.
1634    pub(crate) fn covers(
1635        &self,
1636        snapshot: &Snapshot,
1637        root: &Path,
1638        set: &crate::recorded::PathSet,
1639        output: &dyn Fn(&str) -> bool,
1640    ) -> bool {
1641        self.uncovered(snapshot, root, set, output).next().is_none()
1642    }
1643
1644    /// The paths of `set` the declared key does not cover, as
1645    /// [`Self::covers`] judges them, each with what the task did to it:
1646    /// `read`, `found`, `looked for` or `listed`.
1647    pub(crate) fn uncovered<'a>(
1648        &'a self,
1649        snapshot: &'a Snapshot,
1650        root: &'a Path,
1651        set: &'a crate::recorded::PathSet,
1652        output: &'a dyn Fn(&str) -> bool,
1653    ) -> impl Iterator<Item = (&'a str, &'static str)> + 'a {
1654        let selection = &self.resolved.declared.selection;
1655        fn directory(path: &str) -> &str {
1656            if path == "." { "" } else { path }
1657        }
1658        let holds_keyed = move |path: &str| {
1659            let path = directory(path);
1660            if path.is_empty() {
1661                return self.resolved.whole_files().next().is_some();
1662            }
1663            under(&self.resolved.declared.files, path).next().is_some()
1664                || under(&self.resolved.inferred.files, path).next().is_some()
1665        };
1666        let reads = set
1667            .reads
1668            .iter()
1669            .filter(move |path| !self.keyed(path))
1670            .map(|path| (path.as_str(), "read"));
1671        let present = set
1672            .present
1673            .iter()
1674            .filter(move |path| {
1675                !(self.keyed(path) || (root.join(path).is_dir() && holds_keyed(path)))
1676            })
1677            .map(|path| (path.as_str(), "found"));
1678        let absent = set
1679            .absent
1680            .iter()
1681            .filter(move |path| {
1682                !(self.keyed(path)
1683                    || (!snapshot.source_ignore.matches(path)
1684                        && !output(path)
1685                        && selection.selects(snapshot, path)))
1686            })
1687            .map(|path| (path.as_str(), "looked for"));
1688        let listings = set
1689            .listings
1690            .iter()
1691            .filter(move |path| {
1692                let path = directory(path);
1693                !((path.is_empty() || !output(path))
1694                    && selection.selects_every_entry(snapshot, path))
1695            })
1696            .map(|path| (path.as_str(), "listed"));
1697        reads.chain(present).chain(absent).chain(listings)
1698    }
1699}
1700
1701/// A `json` glob, kept to select dependency outputs once they are written.
1702struct JsonGlob {
1703    matcher: Arc<Pattern>,
1704    prefix: String,
1705    /// The project whose files it selects, or `None` for the workspace's.
1706    owner: Option<String>,
1707    fields: JsonFields,
1708}
1709
1710#[derive(Default)]
1711struct FileSelection {
1712    patterns: Vec<FilePattern>,
1713    included: BTreeSet<String>,
1714    excluded: BTreeSet<String>,
1715}
1716
1717#[derive(PartialEq, Eq, PartialOrd, Ord)]
1718enum FileScope {
1719    Workspace,
1720    Project(String),
1721}
1722
1723struct Resolver<'a> {
1724    workspace: &'a Workspace,
1725    snapshot: &'a Snapshot,
1726    candidates: &'a BTreeSet<String>,
1727    selected: BTreeSet<String>,
1728    scopes: BTreeMap<FileScope, FileSelection>,
1729    values: BTreeMap<String, Value>,
1730    json_fields: BTreeMap<String, Vec<JsonFields>>,
1731    json_globs: Vec<JsonGlob>,
1732    named_stack: Vec<(String, String)>,
1733    /// Dependency named inputs already expanded for `^` inputs.
1734    expanded: BTreeSet<(String, String)>,
1735    external: BTreeSet<String>,
1736    /// `includeIgnored` globs, resolved, by the project that reads them and
1737    /// whether they came with `dependencies: true`: each is one group, whose
1738    /// negations filter all of its positives.
1739    ignored: BTreeMap<(String, bool), Vec<String>>,
1740    external_declared: bool,
1741    /// Every project whose inputs were read, as Nx hashes each one's
1742    /// configuration.
1743    projects: BTreeSet<String>,
1744    /// `None` resolves which inputs a task has without evaluating env or
1745    /// runtime inputs.
1746    prepared: Option<&'a PreparedTask>,
1747    cancelled: &'a AtomicBool,
1748}
1749
1750impl<'a> Resolver<'a> {
1751    fn new(
1752        snapshot: &'a Snapshot,
1753        workspace: &'a Workspace,
1754        prepared: Option<&'a PreparedTask>,
1755        cancelled: &'a AtomicBool,
1756        candidates: &'a BTreeSet<String>,
1757    ) -> Self {
1758        Self {
1759            workspace,
1760            snapshot,
1761            candidates,
1762            selected: BTreeSet::new(),
1763            scopes: BTreeMap::new(),
1764            values: BTreeMap::new(),
1765            json_fields: BTreeMap::new(),
1766            json_globs: Vec::new(),
1767            named_stack: Vec::new(),
1768            expanded: BTreeSet::new(),
1769            external: BTreeSet::new(),
1770            ignored: BTreeMap::new(),
1771            external_declared: false,
1772            projects: BTreeSet::new(),
1773            prepared,
1774            cancelled,
1775        }
1776    }
1777
1778    fn task_inputs(&mut self, task: &Task) -> Result<()> {
1779        self.projects.insert(task.project.clone());
1780        for input in declared_inputs(task) {
1781            self.input(&task.project, &input)?;
1782        }
1783        // As in Nx, a continuous task serving this one counts its own inputs
1784        // here.
1785        let snapshot = self.snapshot;
1786        for (project, inputs) in snapshot.servers.get(&task.id).into_iter().flatten() {
1787            for input in inputs {
1788                self.input(project, input)
1789                    .with_context(|| format!("inputs of {project}, which serves this task"))?;
1790            }
1791        }
1792        Ok(())
1793    }
1794
1795    fn input(&mut self, project: &str, input: &Value) -> Result<()> {
1796        self.projects.insert(project.to_owned());
1797        // Nx 24's `always` keeps an input in a hash taken from an Ultracache
1798        // recording. qk hashes no recordings, so the input reads as without it.
1799        if let Value::Object(object) = input
1800            && let Some(always) = object.get("always")
1801        {
1802            // As in Nx, `always` keeps an input on purpose, so a project
1803            // pattern it selects nothing with is a mistake.
1804            if always.as_bool().context("input always must be boolean")?
1805                && let Some(Value::String(name)) = object.get("input")
1806                && let Some(projects) = object.get("projects")
1807            {
1808                let patterns: Vec<String> = match projects {
1809                    Value::String(pattern) => vec![pattern.clone()],
1810                    other => serde_json::from_value(other.clone())
1811                        .context("input projects must be a string or an array")?,
1812                };
1813                for pattern in patterns.iter().filter(|pattern| {
1814                    !pattern.starts_with('!')
1815                        && !matches!(pattern.as_str(), "self" | "dependencies")
1816                }) {
1817                    if qk_graph::select_projects(
1818                        &self.workspace.projects,
1819                        std::slice::from_ref(pattern),
1820                        &[],
1821                    )?
1822                    .is_empty()
1823                    {
1824                        bail!(
1825                            "the input {{\"input\": \"{name}\", \"projects\"}} with \"always\": true selects \"{pattern}\", which matches no project"
1826                        );
1827                    }
1828                }
1829            }
1830            let mut object = object.clone();
1831            object.remove("always");
1832            return self.input(project, &Value::Object(object));
1833        }
1834        match input {
1835            // As in Nx, `^{projectRoot}/…` and `^{workspaceRoot}/…` are a
1836            // fileset of every project the project depends on, directly or
1837            // not, and `^name` is `name` of each of them.
1838            Value::String(name)
1839                if name.starts_with("^{projectRoot}") || name.starts_with("^{workspaceRoot}") =>
1840            {
1841                self.dependency_fileset(project, &name[1..])?;
1842            }
1843            Value::String(name) if name.starts_with('^') => {
1844                self.dependencies_named(project, &name[1..])?;
1845            }
1846            // The object spellings of named inputs, as Nx reads them.
1847            Value::Object(object)
1848                if object.contains_key("input") && !object.contains_key("fileset") =>
1849            {
1850                let name = object["input"]
1851                    .as_str()
1852                    .context("input must name a named input")?;
1853                let projects = object.get("projects");
1854                let dependencies = object.get("dependencies") == Some(&json!(true))
1855                    || projects == Some(&json!("dependencies"));
1856                let listed = projects.filter(|projects| {
1857                    **projects != json!("self") && **projects != json!("dependencies")
1858                });
1859                if (dependencies || listed.is_some()) && !self.named_stack.is_empty() {
1860                    bail!("named inputs can only refer to named inputs of their own project");
1861                }
1862                if let Some(listed) = listed {
1863                    let patterns: Vec<String> = match listed {
1864                        Value::String(pattern) => vec![pattern.clone()],
1865                        other => serde_json::from_value(other.clone())
1866                            .context("input projects must be a string or an array")?,
1867                    };
1868                    // Nx's native hasher reads these patterns, not the
1869                    // `findMatchingProjects` the rest of Nx uses.
1870                    for selected in qk_config::find_matching_projects(
1871                        &patterns,
1872                        &self.workspace.projects,
1873                        qk_config::Reader::Native,
1874                    ) {
1875                        // As in Nx 24, `dependencies: true` beside `projects`
1876                        // is each selected project's `^name`, not its own.
1877                        if dependencies {
1878                            self.dependencies_named(&selected, name)?;
1879                        } else if self.expanded.insert((selected.clone(), name.to_owned())) {
1880                            self.named(&selected, name)?;
1881                        }
1882                    }
1883                } else if dependencies {
1884                    self.dependencies_named(project, name)?;
1885                } else {
1886                    self.named(project, name)?;
1887                }
1888            }
1889            Value::Object(object) if object.contains_key("fileset") => {
1890                if let Some(key) = object.keys().find(|key| {
1891                    !matches!(key.as_str(), "fileset" | "dependencies" | "includeIgnored")
1892                }) {
1893                    bail!("unsupported fileset input field {key:?}");
1894                }
1895                let flag = |name: &str| {
1896                    object
1897                        .get(name)
1898                        .map(|value| {
1899                            value
1900                                .as_bool()
1901                                .with_context(|| format!("{name} must be boolean"))
1902                        })
1903                        .transpose()
1904                        .map(Option::unwrap_or_default)
1905                };
1906                let (dependencies, include_ignored) =
1907                    (flag("dependencies")?, flag("includeIgnored")?);
1908                let pattern = object["fileset"]
1909                    .as_str()
1910                    .context("fileset input must be a glob")?
1911                    .to_owned();
1912                validate_fileset(&pattern)?;
1913                match (dependencies, include_ignored) {
1914                    (false, false) => self.fileset(project, &pattern)?,
1915                    (true, false) => self.dependency_fileset(project, &pattern)?,
1916                    (false, true) => self.ignored_fileset(project, &pattern, false),
1917                    (true, true) => {
1918                        if !self.named_stack.is_empty() {
1919                            bail!(
1920                                "named inputs can only refer to named inputs of their own project"
1921                            );
1922                        }
1923                        for dependency in self.dependency_closure(project) {
1924                            self.ignored_fileset(&dependency, &pattern, true);
1925                        }
1926                    }
1927                }
1928            }
1929            Value::Object(object)
1930                if object.len() == 1 && object.contains_key("workingDirectory") =>
1931            {
1932                let mode = object["workingDirectory"].as_str().unwrap_or_default();
1933                let directory = std::env::current_dir()?;
1934                let value = match mode {
1935                    "absolute" => directory.to_string_lossy().into_owned(),
1936                    "relative" => {
1937                        let root = self.workspace.root.canonicalize()?;
1938                        let directory = directory.canonicalize()?;
1939                        paths::relative(&root, &directory)
1940                            .unwrap_or_else(|_| directory.to_string_lossy().into_owned())
1941                    }
1942                    _ => bail!("workingDirectory must be \"relative\" or \"absolute\""),
1943                };
1944                self.values
1945                    .insert(format!("workingDirectory:{mode}"), json!(value));
1946            }
1947            Value::Object(object) if object.contains_key("json") => {
1948                self.json(project, object)?;
1949            }
1950            // As in Nx, a string names a named input when there is one, and is
1951            // a fileset otherwise.
1952            Value::String(name) if self.has_named(project, name) => self.named(project, name)?,
1953            Value::String(pattern) => {
1954                validate_fileset(pattern)?;
1955                self.fileset(project, pattern)?
1956            }
1957            Value::Object(object) if object.len() == 1 && object.contains_key("env") => {
1958                let name = object["env"]
1959                    .as_str()
1960                    .context("env input must name a variable")?;
1961                let Some(prepared) = self.prepared else {
1962                    self.values.insert(format!("env:{name}"), Value::Null);
1963                    return Ok(());
1964                };
1965                let value = prepared
1966                    .env
1967                    .get(std::ffi::OsStr::new(name))
1968                    .map(|value| {
1969                        value
1970                            .to_str()
1971                            .map(str::to_owned)
1972                            .context("declared env input must be UTF-8")
1973                    })
1974                    .transpose()?;
1975                self.values.insert(format!("env:{name}"), json!(value));
1976            }
1977            Value::Object(object) if object.len() == 1 && object.contains_key("runtime") => {
1978                let command = object["runtime"]
1979                    .as_str()
1980                    .context("runtime input must be a command")?;
1981                let Some(prepared) = self.prepared else {
1982                    self.values
1983                        .insert(format!("runtime:{command}"), Value::Null);
1984                    return Ok(());
1985                };
1986                let memo = RuntimeKey {
1987                    command: command.into(),
1988                    environment: prepared.runtime_env.clone(),
1989                };
1990                let slot = self
1991                    .snapshot
1992                    .runtime
1993                    .lock()
1994                    .unwrap()
1995                    .entry(memo)
1996                    .or_default()
1997                    .clone();
1998                let mut saved = slot.lock().unwrap();
1999                if let Some(value) = saved.as_ref() {
2000                    self.values
2001                        .insert(format!("runtime:{command}"), value.clone());
2002                    return Ok(());
2003                }
2004                let _profile = crate::profile::span(command, "runtime");
2005                let mut prepared = prepared.clone();
2006                prepared.env = prepared.runtime_env.clone();
2007                prepared.execution.clear();
2008                prepared.node_path = None;
2009                prepared.commands = vec![command.into()];
2010                prepared.cwd = self.workspace.root.clone();
2011                prepared.parallel = false;
2012                // Its output is hashed, so it must not depend on a terminal.
2013                prepared.pseudo_terminal = false;
2014                let log = tempfile::NamedTempFile::new()?;
2015                let capture = Capture::new(Some(log.as_file().try_clone()?), Display::Hidden);
2016                if execute_captured(&prepared, self.cancelled, Some(&capture))? != Outcome::Success
2017                {
2018                    bail!("runtime input did not succeed");
2019                }
2020                let mut stdout = blake3::Hasher::new();
2021                let mut stderr = blake3::Hasher::new();
2022                read_capture(File::open(log.path())?, |error, bytes| {
2023                    if error {
2024                        stderr.update(bytes);
2025                    } else {
2026                        stdout.update(bytes);
2027                    }
2028                    Ok(())
2029                })?;
2030                let value = json!([
2031                    stdout.finalize().to_hex().to_string(),
2032                    stderr.finalize().to_hex().to_string()
2033                ]);
2034                *saved = Some(value.clone());
2035                self.values.insert(format!("runtime:{command}"), value);
2036            }
2037            Value::Object(object) if object.contains_key("dependentTasksOutputFiles") => {
2038                if object
2039                    .keys()
2040                    .any(|key| !matches!(key.as_str(), "dependentTasksOutputFiles" | "transitive"))
2041                {
2042                    bail!("unsupported output input field");
2043                }
2044                let pattern = object["dependentTasksOutputFiles"]
2045                    .as_str()
2046                    .context("dependentTasksOutputFiles must be a glob")?;
2047                self.snapshot.pattern(pattern, false)?;
2048                let transitive = object
2049                    .get("transitive")
2050                    .map(|value| value.as_bool().context("transitive must be boolean"))
2051                    .transpose()?
2052                    .unwrap_or(false);
2053                // Resolved before execution too, so inspection can display the
2054                // selection without reading generated files. dependency_keys
2055                // hashes these files after the dependencies finish.
2056                let value = self
2057                    .values
2058                    .entry(format!("dependentTasksOutputFiles:{pattern}"))
2059                    .or_insert(json!(false));
2060                if transitive {
2061                    *value = json!(true);
2062                }
2063            }
2064            Value::Object(object)
2065                if object.len() == 1 && object.contains_key("externalDependencies") =>
2066            {
2067                let names: Vec<String> =
2068                    serde_json::from_value(object["externalDependencies"].clone())?;
2069                // As in Nx, a workspace project is no external dependency.
2070                if let Some(name) = names
2071                    .iter()
2072                    .find(|name| self.workspace.projects.contains_key(*name))
2073                {
2074                    if self.snapshot.projects.dependencies[project]
2075                        .iter()
2076                        .any(|edge| edge.target == *name)
2077                    {
2078                        bail!(
2079                            "the externalDependency {name:?} of {project} is not an external node and is already a dependency; remove it from the externalDependencies inputs"
2080                        );
2081                    }
2082                    bail!(
2083                        "the externalDependency {name:?} of {project} is not an external node; if it is a dependency, add it to the project's implicitDependencies"
2084                    );
2085                }
2086                self.external.extend(names);
2087                self.external_declared = true;
2088            }
2089            _ => bail!("unsupported task input declaration"),
2090        }
2091        Ok(())
2092    }
2093
2094    fn fileset(&mut self, project: &str, pattern: &str) -> Result<()> {
2095        self.projects.insert(project.to_owned());
2096        let (exclude, pattern) = pattern
2097            .strip_prefix('!')
2098            .map(|pattern| (true, pattern))
2099            .unwrap_or((false, pattern));
2100        // Nx hashes workspace files and each project's files in separate
2101        // scopes, a project's being only the files it owns: those of a project
2102        // nested in its root are that project's. A fileset is the project's
2103        // when it starts from `{projectRoot}/`, and the workspace's otherwise,
2104        // where only one starting from `{workspaceRoot}/` selects anything.
2105        let (scope, owner) = if pattern.starts_with("{projectRoot}/") {
2106            (
2107                FileScope::Project(project.to_owned()),
2108                Some(project.to_owned()),
2109            )
2110        } else if pattern.starts_with("{workspaceRoot}/") {
2111            (FileScope::Workspace, None)
2112        } else {
2113            return Ok(());
2114        };
2115        let pattern = paths::expand_glob(self.workspace, project, pattern)?;
2116        let matcher = self.snapshot.fileset_pattern(&pattern, exclude)?;
2117        let (prefix, rest) = crate::ignored::partition(pattern.trim_end_matches('/'));
2118        let rest = rest.map(str::to_owned);
2119        let candidates: Box<dyn Iterator<Item = &String>> = if prefix.is_empty() {
2120            Box::new(self.candidates.iter())
2121        } else {
2122            Box::new(under(self.candidates, &prefix))
2123        };
2124        let snapshot = self.snapshot;
2125        let selection = self.scopes.entry(scope).or_default();
2126        let selected = if exclude {
2127            &mut selection.excluded
2128        } else {
2129            &mut selection.included
2130        };
2131        selected.extend(
2132            candidates
2133                .filter(|file| matcher.is_match(file))
2134                .filter(|file| owner.is_none() || snapshot.owner(file) == owner.as_deref())
2135                .cloned(),
2136        );
2137        selection.patterns.push(FilePattern {
2138            matcher,
2139            prefix,
2140            rest,
2141            excluded: exclude,
2142            owner,
2143        });
2144        Ok(())
2145    }
2146
2147    /// An `includeIgnored` glob of `project`, with its tokens resolved as
2148    /// Nx's `resolve_files_glob` resolves them, to read from disk later.
2149    fn ignored_fileset(&mut self, project: &str, pattern: &str, dependencies: bool) {
2150        // The root and name go in escaped, as for every fileset; Nx inserts
2151        // them as they are.
2152        let root = &self.workspace.projects[project].root;
2153        let resolved = if root == "." {
2154            pattern.replace("{projectRoot}/", "")
2155        } else {
2156            pattern.replace("{projectRoot}", &crate::glob::escape(root))
2157        }
2158        .replace("{projectName}", &crate::glob::escape(project));
2159        let resolved = match resolved.strip_prefix("!{workspaceRoot}/") {
2160            Some(rest) => format!("!{rest}"),
2161            None => resolved
2162                .strip_prefix("{workspaceRoot}/")
2163                .map(str::to_owned)
2164                .unwrap_or(resolved),
2165        };
2166        self.ignored
2167            .entry((project.to_owned(), dependencies))
2168            .or_default()
2169            .push(resolved);
2170    }
2171
2172    /// A fileset of every project `project` depends on, directly or not.
2173    fn dependency_fileset(&mut self, project: &str, pattern: &str) -> Result<()> {
2174        if !self.named_stack.is_empty() {
2175            bail!("named inputs can only refer to named inputs of their own project");
2176        }
2177        for dependency in self.dependency_closure(project) {
2178            self.fileset(&dependency, pattern)?;
2179        }
2180        Ok(())
2181    }
2182
2183    /// Whether `name` names one of `project`'s named inputs.
2184    fn has_named(&self, project: &str, name: &str) -> bool {
2185        name == "default"
2186            || self.workspace.projects[project]
2187                .named_inputs
2188                .contains_key(name)
2189    }
2190
2191    /// Every project `project` depends on, directly or not.
2192    fn dependency_closure(&self, project: &str) -> BTreeSet<String> {
2193        let mut closure = BTreeSet::new();
2194        let mut pending = vec![project.to_owned()];
2195        while let Some(current) = pending.pop() {
2196            for edge in &self.snapshot.projects.dependencies[&current] {
2197                if edge.target != project && closure.insert(edge.target.clone()) {
2198                    pending.push(edge.target.clone());
2199                }
2200            }
2201        }
2202        closure
2203    }
2204
2205    /// As in Nx, `^name` is `name` of every project the project depends on.
2206    fn dependencies_named(&mut self, project: &str, name: &str) -> Result<()> {
2207        for dependency in self.dependency_closure(project) {
2208            if self.expanded.insert((dependency.clone(), name.to_owned())) {
2209                self.named(&dependency, name)?;
2210            }
2211        }
2212        Ok(())
2213    }
2214
2215    /// A JSON input: the fields of a JSON file, rather than all of it, or of
2216    /// each file a glob selects. `fields` keeps only the named dotted paths;
2217    /// `excludeFields` removes them.
2218    fn json(&mut self, project: &str, object: &serde_json::Map<String, Value>) -> Result<()> {
2219        for key in object.keys() {
2220            if !matches!(key.as_str(), "json" | "fields" | "excludeFields") {
2221                bail!("unsupported json input field {key:?}");
2222            }
2223        }
2224        let declared = object["json"]
2225            .as_str()
2226            .context("json input must name a file")?;
2227        validate_fileset(declared)?;
2228        let path = paths::expand_glob(self.workspace, project, declared)?;
2229        let list = |name: &str| -> Result<Option<Vec<String>>> {
2230            object
2231                .get(name)
2232                .map(|value| {
2233                    serde_json::from_value(value.clone())
2234                        .with_context(|| format!("json input {name} must be an array of strings"))
2235                })
2236                .transpose()
2237        };
2238        let fields = JsonFields {
2239            fields: list("fields")?,
2240            exclude: list("excludeFields")?.unwrap_or_default(),
2241        };
2242        if crate::glob::names_a_path(&path) {
2243            let path = crate::glob::literal_path(&path);
2244            paths::validate_path(&path)?;
2245            return self.json_file(path, &fields);
2246        }
2247        // As in Nx, a glob selects the files a fileset from the same root
2248        // would: the project's own, or the workspace's.
2249        let owner = if declared.starts_with("{projectRoot}") {
2250            Some(project)
2251        } else if declared.starts_with("{workspaceRoot}/") {
2252            None
2253        } else {
2254            return Ok(());
2255        };
2256        let matcher = self.snapshot.pattern(&path, false)?;
2257        let snapshot = self.snapshot;
2258        let matched: Vec<String> = self
2259            .candidates
2260            .iter()
2261            .filter(|file| matcher.is_match(file))
2262            .filter(|file| owner.is_none() || snapshot.owner(file) == owner)
2263            .cloned()
2264            .collect();
2265        for file in matched {
2266            self.json_file(file, &fields)?;
2267        }
2268        self.json_globs.push(JsonGlob {
2269            matcher,
2270            prefix: crate::ignored::partition(&path).0,
2271            owner: owner.map(str::to_owned),
2272            fields,
2273        });
2274        Ok(())
2275    }
2276
2277    /// One file a `json` input selects, keyed by its fields. Several inputs
2278    /// may select different fields of one file: each counts, as in Nx since
2279    /// 24.0.0-rc.0, where one used to replace the other.
2280    fn json_file(&mut self, path: String, fields: &JsonFields) -> Result<()> {
2281        let text = match std::fs::read_to_string(self.workspace.root.join(&path)) {
2282            Ok(text) => Some(text),
2283            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
2284            Err(error) => return Err(error.into()),
2285        };
2286        let mut selections = self.json_fields.get(&path).cloned().unwrap_or_default();
2287        if !selections.contains(fields) {
2288            selections.push(fields.clone());
2289            // In one order, whichever input came first.
2290            selections.sort();
2291        }
2292        let mut values = Vec::new();
2293        for selection in &selections {
2294            values.push(match &text {
2295                Some(text) => match json_projection(&path, text, selection) {
2296                    Some(value) => value,
2297                    // As in Nx, a file it cannot read is keyed by its content,
2298                    // without the field filters. Nx reads no YAML, so it keys
2299                    // a YAML file whole where qk keys its fields.
2300                    None => {
2301                        self.selected.insert(path);
2302                        return Ok(());
2303                    }
2304                },
2305                None => Value::Null,
2306            });
2307        }
2308        // One selection keys its fields as before; several, each in turn.
2309        let value = if values.len() == 1 {
2310            values.remove(0)
2311        } else {
2312            Value::Array(values)
2313        };
2314        self.values.insert(format!("json:{path}"), value);
2315        self.json_fields.insert(path, selections);
2316        Ok(())
2317    }
2318
2319    fn named(&mut self, project: &str, name: &str) -> Result<()> {
2320        let identity = (project.to_owned(), name.to_owned());
2321        if self.named_stack.contains(&identity) {
2322            bail!("named input cycle at {project}:{name}");
2323        }
2324        self.named_stack.push(identity);
2325        let inputs = self.workspace.projects[project]
2326            .named_inputs
2327            .get(name)
2328            .cloned()
2329            .or_else(|| (name == "default").then(|| vec![json!("{projectRoot}/**/*")]))
2330            .with_context(|| format!("unknown named input {name:?}"))?;
2331        for input in &inputs {
2332            self.input(project, input)?;
2333        }
2334        self.named_stack.pop();
2335        Ok(())
2336    }
2337}
2338
2339/// As Nx's `validate_file_set`: a fileset starts from `{projectRoot}` or
2340/// `{workspaceRoot}`, after its `!`.
2341fn validate_fileset(fileset: &str) -> Result<()> {
2342    let body = fileset.strip_prefix('!').unwrap_or(fileset);
2343    if !body.starts_with("{projectRoot}") && !body.starts_with("{workspaceRoot}") {
2344        bail!(
2345            "{fileset:?} is an invalid fileset: filesets have to start with either {{workspaceRoot}} or {{projectRoot}}, and a named input must be defined"
2346        );
2347    }
2348    Ok(())
2349}
2350
2351/// A task's declared inputs, or Nx's default when it declares none.
2352fn declared_inputs(task: &Task) -> Vec<Value> {
2353    task.definition
2354        .inputs
2355        .clone()
2356        .unwrap_or_else(|| vec![json!("default"), json!("^default")])
2357}
2358
2359/// The continuous tasks serving a task, whose inputs count as its own, as Nx
2360/// hashes them: its continuous dependencies, theirs in turn, and so on, each
2361/// by its project and declared inputs. A dependency declared with
2362/// `inputs: false` is not followed, though a server it leads to still counts
2363/// when another way reaches it.
2364fn servers(graph: &TaskGraph, id: &str) -> Vec<(String, Vec<Value>)> {
2365    let mut servers = Vec::new();
2366    let mut visited = BTreeSet::from([id]);
2367    let mut pending = std::collections::VecDeque::from([id]);
2368    while let Some(current) = pending.pop_front() {
2369        let task = &graph.tasks[current];
2370        for dependency in &task.dependencies {
2371            let Some(server) = graph.tasks.get(dependency) else {
2372                continue;
2373            };
2374            if server.definition.continuous != Some(true)
2375                || !task.edge(dependency).inputs
2376                || !visited.insert(dependency)
2377            {
2378                continue;
2379            }
2380            servers.push((server.project.clone(), declared_inputs(server)));
2381            pending.push_back(dependency);
2382        }
2383    }
2384    servers
2385}
2386
2387pub fn resolve(
2388    snapshot: &Snapshot,
2389    workspace: &Workspace,
2390    task: &Task,
2391    prepared: Option<&PreparedTask>,
2392    cancelled: &AtomicBool,
2393) -> Result<Resolved> {
2394    resolve_candidates(
2395        snapshot,
2396        workspace,
2397        task,
2398        prepared,
2399        cancelled,
2400        &snapshot.files,
2401        &snapshot.source_ignore,
2402    )
2403}
2404
2405fn resolve_candidates(
2406    snapshot: &Snapshot,
2407    workspace: &Workspace,
2408    task: &Task,
2409    prepared: Option<&PreparedTask>,
2410    cancelled: &AtomicBool,
2411    candidates: &BTreeSet<String>,
2412    source_ignore: &SourceIgnore,
2413) -> Result<Resolved> {
2414    let mut resolver = Resolver::new(snapshot, workspace, prepared, cancelled, candidates);
2415    resolver.task_inputs(task)?;
2416    // Dependency outputs may also be declared sources, for filesets and `json`
2417    // globs alike. Downstream and unrelated
2418    // outputs remain artifacts, so producing them cannot invalidate an upstream task.
2419    let mut upstream = BTreeSet::new();
2420    let mut pending: Vec<_> = task.dependencies.iter().cloned().collect();
2421    while let Some(id) = pending.pop() {
2422        if upstream.insert(id.clone())
2423            && let Some(dependencies) = snapshot.task_dependencies.get(&id)
2424        {
2425            pending.extend(dependencies.iter().cloned());
2426        }
2427    }
2428    let own_outputs = Outputs::new(workspace, task)
2429        .ok()
2430        .filter(Outputs::is_explicit);
2431    let mut producers = BTreeSet::new();
2432    for (producer, declared) in &snapshot.generated_tasks {
2433        if producer.id == task.id || !upstream.contains(&producer.id) {
2434            continue;
2435        }
2436        let overlaps = |a: &str, b: &str| {
2437            a.is_empty()
2438                || a == b
2439                || a.strip_prefix(b).is_some_and(|rest| rest.starts_with('/'))
2440                || b.strip_prefix(a).is_some_and(|rest| rest.starts_with('/'))
2441        };
2442        let relevant = resolver
2443            .scopes
2444            .values()
2445            .flat_map(|scope| &scope.patterns)
2446            .filter(|pattern| !pattern.excluded)
2447            .map(|pattern| &pattern.prefix)
2448            .chain(resolver.json_globs.iter().map(|glob| &glob.prefix))
2449            .any(|prefix| {
2450                declared.anchors().any(|anchor| {
2451                    overlaps(prefix, anchor)
2452                        && (!source_ignore.matches_directory(anchor)
2453                            || !workspace.root.join(anchor).is_dir())
2454                })
2455            });
2456        if !relevant {
2457            continue;
2458        }
2459        producers.insert(producer.id.clone());
2460        let outputs = snapshot.dependency_outputs(workspace, producer)?;
2461        let mut json = Vec::new();
2462        for path in &outputs.files {
2463            if source_ignore.matches(path)
2464                || own_outputs.as_ref().is_some_and(|own| own.matches(path))
2465            {
2466                continue;
2467            }
2468            json.extend(
2469                resolver
2470                    .json_globs
2471                    .iter()
2472                    .filter(|glob| {
2473                        glob.matcher.is_match(path)
2474                            && (glob.owner.is_none()
2475                                || snapshot.owner(path) == glob.owner.as_deref())
2476                    })
2477                    .map(|glob| (path.clone(), glob.fields.clone())),
2478            );
2479            for selection in resolver.scopes.values_mut() {
2480                for pattern in &selection.patterns {
2481                    if pattern.matcher.is_match(path)
2482                        && (pattern.owner.is_none()
2483                            || snapshot.owner(path) == pattern.owner.as_deref())
2484                    {
2485                        if pattern.excluded {
2486                            selection.excluded.insert(path.clone());
2487                        } else {
2488                            selection.included.insert(path.clone());
2489                        }
2490                    }
2491                }
2492            }
2493        }
2494        for (path, fields) in json {
2495            resolver.json_file(path, &fields)?;
2496        }
2497    }
2498    // A changed file affected selection adds counts whatever produces it, as
2499    // in Nx, where a declared output is a file like any other.
2500    for selection in resolver.scopes.values() {
2501        resolver.selected.extend(
2502            selection
2503                .included
2504                .difference(&selection.excluded)
2505                .filter(|path| {
2506                    snapshot.extra_candidates.contains(*path)
2507                        || own_outputs.as_ref().is_none_or(|own| !own.matches(path))
2508                })
2509                .cloned(),
2510        );
2511    }
2512    // `includeIgnored` groups read the disk, gitignored files included, and
2513    // a changed path they name counts whether or not it is there. As in Nx,
2514    // one reading another task's declared outputs makes that task a producer.
2515    let mut ignored = BTreeSet::new();
2516    for ((project, _), globs) in &resolver.ignored {
2517        let group = Group::new(
2518            project,
2519            globs,
2520            workspace
2521                .projects
2522                .values()
2523                .map(|project| project.root.as_str()),
2524        )?;
2525        let found = group.expand(&workspace.root)?;
2526        ignored.extend(
2527            found
2528                .into_iter()
2529                .chain(
2530                    snapshot
2531                        .extra_candidates
2532                        .iter()
2533                        .filter(|path| group.matches(path))
2534                        .cloned(),
2535                )
2536                // A task's own outputs are no input of it, as for any fileset,
2537                // and no task's scratch is any task's.
2538                .filter(|path| own_outputs.as_ref().is_none_or(|own| !own.matches(path)))
2539                .filter(|path| !snapshot.scratch.iter().any(|scratch| scratch.matches(path))),
2540        );
2541        for (producer, declared) in &snapshot.generated_tasks {
2542            if producer.id != task.id
2543                && upstream.contains(&producer.id)
2544                && declared.declared()
2545                && reads_outputs(&group, declared)
2546            {
2547                producers.insert(producer.id.clone());
2548            }
2549        }
2550    }
2551    resolver.selected.extend(ignored.iter().cloned());
2552    let mut declared = Declared {
2553        files: resolver.selected,
2554        ignored,
2555        values: resolver.values,
2556        json_fields: resolver.json_fields,
2557        external: resolver.external,
2558        external_declared: resolver.external_declared,
2559        projects: resolver.projects,
2560        producers,
2561        selection: Selection {
2562            scopes: resolver
2563                .scopes
2564                .into_values()
2565                .map(|selection| selection.patterns)
2566                .collect(),
2567        },
2568    };
2569    // `dependentTasksOutputFiles` reads its direct dependencies' declared
2570    // outputs, or with `transitive` those of every task it depends on.
2571    let reads: Vec<bool> = declared
2572        .values
2573        .iter()
2574        .filter(|(name, _)| name.starts_with("dependentTasksOutputFiles:"))
2575        .map(|(_, transitive)| transitive == &Value::Bool(true))
2576        .collect();
2577    if !reads.is_empty() {
2578        let transitive = reads.contains(&true);
2579        for (producer, outputs) in &snapshot.generated_tasks {
2580            let read = if transitive {
2581                upstream.contains(&producer.id)
2582            } else {
2583                task.dependencies.contains(&producer.id)
2584            };
2585            if read && outputs.declared() {
2586                declared.producers.insert(producer.id.clone());
2587            }
2588        }
2589    }
2590    let mut inferred = infer(snapshot, workspace, task)?;
2591    // As in Nx, a task naming its external dependencies hashes those in place
2592    // of every installed package, so the root importer's installs count only
2593    // for the root project's own tasks.
2594    if declared.external_declared
2595        && let Some(importers) = &mut inferred.lockfile
2596    {
2597        let root = workspace.projects[&task.project].root == ".";
2598        if !root {
2599            importers.remove(".");
2600        }
2601    }
2602    Ok(join(declared, inferred))
2603}
2604
2605/// Whether an `includeIgnored` group may read files `outputs` declares, as
2606/// Nx's `GlobShape::may_read` judges it from the globs alone: a positive's
2607/// directory and an output's meet, the one holding the other, unless the
2608/// output lies in a project the positive does not reach, and their
2609/// extensions, where both have one, agree.
2610fn reads_outputs(group: &Group, outputs: &Outputs) -> bool {
2611    let holds = |outer: &str, inner: &str| {
2612        outer.is_empty()
2613            || inner == outer
2614            || inner
2615                .strip_prefix(outer)
2616                .is_some_and(|rest| rest.starts_with('/'))
2617    };
2618    group.reads().any(|(root, extension)| {
2619        outputs.globs().iter().any(|output| {
2620            let (prefix, _) = crate::ignored::partition(output);
2621            (holds(root, &prefix) || holds(&prefix, root))
2622                && !group
2623                    .skipped_below(root)
2624                    .iter()
2625                    .any(|project| holds(project, &prefix))
2626                && match (extension, crate::ignored::extension(output)) {
2627                    (Some(read), Some(written)) => read == written,
2628                    _ => true,
2629                }
2630        })
2631    })
2632}
2633
2634/// What qk adds to `task`'s key on its own, whatever its inputs declare.
2635fn infer(snapshot: &Snapshot, workspace: &Workspace, task: &Task) -> Result<Inferred> {
2636    let readable = snapshot
2637        .installed(&workspace.root, &task.id)?
2638        .is_some_and(|installed| installed.lockfile.is_some());
2639    let exists = |path: &str| {
2640        workspace.root.join(path).is_file() || snapshot.extra_candidates.contains(path)
2641    };
2642    let mut inferred = Inferred {
2643        lockfile_readable: readable,
2644        ..Inferred::default()
2645    };
2646    // Workspace resolution and configuration. Dotenv files are not keyed, as
2647    // in Nx: they hold per-machine values and credentials, and a task's `env`
2648    // inputs key the variables it declares. The root tsconfig, as Nx hashes it
2649    // into every task. The root package.json is not, as in Nx: what the root
2650    // importer installs counts for every task through the lockfile, and the
2651    // rest of it is the root project's manifest.
2652    inferred.tsconfig = crate::inputs::ROOT_TSCONFIG_FILES
2653        .into_iter()
2654        .find(|name| exists(name))
2655        .map(str::to_owned);
2656    // nx.json counts through what it changes: through the task's resolved
2657    // configuration, and by the settings that reach tasks otherwise. A tool
2658    // reading it itself declares it as an input, which keys the file whole.
2659    for path in ["nx.json", qk_config::LOCAL_WORKSPACE] {
2660        if exists(path) {
2661            inferred.settings.insert(path.into());
2662        }
2663    }
2664    if let Some(extended) = &workspace.extended {
2665        inferred.settings.insert(extended.clone());
2666    }
2667    for path in [
2668        ".gitignore",
2669        ".nxignore",
2670        "package-lock.json",
2671        "yarn.lock",
2672        "bun.lock",
2673    ] {
2674        if exists(path) {
2675            inferred.files.insert(path.into());
2676        }
2677    }
2678    // A pnpm lockfile qk can read is keyed by what the task's projects
2679    // install, and the workspace file without the resolution keys whose effect
2680    // lands in it.
2681    if exists("pnpm-workspace.yaml") {
2682        if readable {
2683            inferred.workspace_file = true;
2684        } else {
2685            inferred.files.insert("pnpm-workspace.yaml".into());
2686        }
2687    }
2688    if exists("pnpm-lock.yaml") && !readable {
2689        inferred.files.insert("pnpm-lock.yaml".into());
2690    }
2691    // The task's own package.json counts whole, its package scripts and
2692    // dependency declarations with it. A dependency's package.json counts by what it
2693    // decides for dependents, such as where their imports of it resolve; its
2694    // installs count through the lockfile.
2695    let mut packages = BTreeSet::from([task.project.clone()]);
2696    let mut pending = packages.clone();
2697    while let Some(project) = pending.pop_first() {
2698        for edge in &snapshot.projects.dependencies[&project] {
2699            if packages.insert(edge.target.clone()) {
2700                pending.insert(edge.target.clone());
2701            }
2702        }
2703    }
2704    for project in &packages {
2705        let own = *project == task.project;
2706        for name in ["project.json", qk_config::LOCAL_OVERRIDES, "package.json"] {
2707            if !own && name != "package.json" {
2708                continue;
2709            }
2710            let path = Path::new(&workspace.projects[project].root).join(name);
2711            let path = path.strip_prefix(".").unwrap_or(&path).to_owned();
2712            if !workspace.root.join(&path).is_file() {
2713                continue;
2714            }
2715            let path = path
2716                .to_str()
2717                .context("project path must be UTF-8")?
2718                .replace('\\', "/");
2719            // Its project.json and project.local.json are not added: what
2720            // they decide for the task counts through its resolved
2721            // configuration, and an input selecting them keys them as it
2722            // says.
2723            if own && name != "package.json" {
2724                inferred.project.insert(path);
2725                continue;
2726            }
2727            if own {
2728                inferred.files.insert(path);
2729                continue;
2730            }
2731            let text = std::fs::read_to_string(workspace.root.join(&path))
2732                .with_context(|| format!("cannot read {path}"))?;
2733            match manifest_for_dependents(&text, readable) {
2734                Some(value) => {
2735                    inferred.manifests.insert(path, value);
2736                }
2737                None => {
2738                    inferred.files.insert(path);
2739                }
2740            }
2741        }
2742    }
2743    if readable {
2744        // The root importer's packages resolve from every package in the
2745        // workspace, so they count for every task.
2746        inferred.lockfile = Some(
2747            std::iter::once(".".to_owned())
2748                .chain(
2749                    packages
2750                        .iter()
2751                        .map(|project| workspace.projects[project].root.clone()),
2752                )
2753                .collect(),
2754        );
2755    }
2756    Ok(inferred)
2757}
2758
2759/// `declared` and `inferred` together. A file both select is left to the
2760/// declared inputs, which count all of it.
2761fn join(declared: Declared, mut inferred: Inferred) -> Resolved {
2762    let mut covered = BTreeSet::new();
2763    inferred.files.retain(|path| {
2764        let keep = !declared.files.contains(path);
2765        if !keep {
2766            covered.insert(path.clone());
2767        }
2768        keep
2769    });
2770    inferred.manifests.retain(|path, _| {
2771        let keep = !declared.files.contains(path);
2772        if !keep {
2773            covered.insert(path.clone());
2774        }
2775        keep
2776    });
2777    if inferred.lockfile.is_some() && declared.files.contains("pnpm-lock.yaml") {
2778        inferred.lockfile = None;
2779        covered.insert("pnpm-lock.yaml".into());
2780    }
2781    if inferred.workspace_file && declared.files.contains("pnpm-workspace.yaml") {
2782        inferred.workspace_file = false;
2783        covered.insert("pnpm-workspace.yaml".into());
2784    }
2785    if let Some(tsconfig) = inferred
2786        .tsconfig
2787        .take_if(|path| declared.files.contains(path))
2788    {
2789        covered.insert(tsconfig);
2790    }
2791    inferred.covered = covered;
2792    Resolved { declared, inferred }
2793}
2794
2795/// What a task's key is computed from, as JSON: kept by the history so a
2796/// changed key can be explained.
2797pub fn inputs(
2798    snapshot: &Snapshot,
2799    workspace: &Workspace,
2800    task: &Task,
2801    prepared: &PreparedTask,
2802    dependencies: &BTreeMap<String, String>,
2803    cancelled: &AtomicBool,
2804) -> Result<Value> {
2805    let prefixes = snapshot.membership_prefixes(workspace, task)?;
2806    let candidates = snapshot.current_files_for(&workspace.root, Some(&prefixes), &task.id)?;
2807    let Resolved { declared, inferred } = resolve_candidates(
2808        snapshot,
2809        workspace,
2810        task,
2811        Some(prepared),
2812        cancelled,
2813        &candidates.files,
2814        &candidates.source_ignore,
2815    )?;
2816    let file_values = |paths: &BTreeSet<String>| {
2817        paths
2818            .iter()
2819            .map(|path| {
2820                let value = snapshot
2821                    .file_value(&workspace.root, path)
2822                    .with_context(|| format!("cannot read input {path}"))?;
2823                Ok((path.clone(), value))
2824            })
2825            .collect::<Result<BTreeMap<_, _>>>()
2826    };
2827    let mut files = file_values(&(&declared.files - &declared.ignored))?;
2828    for path in &declared.ignored {
2829        if let Some(value) = snapshot
2830            .ignored_value(&workspace.root, path)
2831            .with_context(|| format!("cannot read input {path}"))?
2832        {
2833            files.insert(path.clone(), value);
2834        }
2835    }
2836    let mut values = declared.values;
2837    // Left out without a declared environment, so other keys stay as they
2838    // were.
2839    if let Some(environment) = &prepared.environment {
2840        values.insert("environment".into(), environment.keyed());
2841    }
2842    let mut configuration = json!({
2843        "files": file_values(&inferred.files)?,
2844        "settings": workspace.config.keyed_settings(),
2845        "project": task_configuration(workspace, task),
2846    });
2847    let installed = snapshot.installed(&workspace.root, &task.id)?;
2848    if let (Some(importers), Some(installed)) = (&inferred.lockfile, &installed)
2849        && let Some(lockfile) = &installed.lockfile
2850    {
2851        let importers: BTreeMap<_, _> = importers
2852            .iter()
2853            .filter(|importer| lockfile.has_importer(importer))
2854            .map(|importer| {
2855                let digest = installed.digest(&format!("importer:{importer}"), || {
2856                    lockfile.installed(importer).unwrap_or_default()
2857                });
2858                (importer.clone(), digest)
2859            })
2860            .collect();
2861        configuration["lockfile"] = json!({
2862            "global": installed.digest("global", || BTreeSet::from([lockfile.global().to_string()])),
2863            "importers": importers,
2864        });
2865        // A lockfile keyed whole already covers the packages it installs.
2866        if !declared.external.is_empty() {
2867            let external: BTreeMap<_, _> = declared
2868                .external
2869                .iter()
2870                .map(|name| {
2871                    let digest =
2872                        installed.digest(&format!("package:{name}"), || lockfile.package(name));
2873                    // As in Nx, a package nothing installs is an error.
2874                    if digest == blake3::hash(b"").to_hex().as_str() {
2875                        bail!(
2876                            "the externalDependency {name:?} of {} could not be found",
2877                            task.id
2878                        );
2879                    }
2880                    Ok((name.clone(), digest))
2881                })
2882                .collect::<Result<_>>()?;
2883            values.insert("externalDependencies".into(), json!(external));
2884        }
2885    }
2886    if inferred.workspace_file {
2887        configuration["workspaceFile"] = match workspace_without_resolution(&workspace.root) {
2888            Some(value) => value,
2889            None => snapshot.file_value(&workspace.root, "pnpm-workspace.yaml")?,
2890        };
2891    }
2892    if !inferred.manifests.is_empty() {
2893        configuration["manifests"] = json!(inferred.manifests);
2894    }
2895    if let Some(path) = &inferred.tsconfig {
2896        let parsed = std::fs::read_to_string(workspace.root.join(path))
2897            .ok()
2898            .and_then(|text| TsConfig::parse(&text));
2899        configuration["tsconfig"] = match parsed {
2900            Some(tsconfig) if crate::inputs::selectively_hash_tsconfig(workspace) => json!({
2901                "rest": tsconfig.rest,
2902                "paths": tsconfig.paths_of(&declared.projects, |target| snapshot.owner(target)),
2903            }),
2904            Some(tsconfig) => json!({ "rest": tsconfig.rest }),
2905            None => snapshot.file_value(&workspace.root, path)?,
2906        };
2907    }
2908    let definition = keyed_definition(task);
2909    let hash = json!({
2910        "schema":"qk-local-v4", "qk":env!("CARGO_PKG_VERSION"),
2911        "platform":[std::env::consts::OS, std::env::consts::ARCH], "workspace":snapshot.workspace_prefix,
2912        "id":task.id, "args":task.args, "definition":definition, "packageManager":workspace.package_manager,
2913        "files":files, "values":values, "inferred":configuration, "dependencies":dependencies,
2914    });
2915    Ok(hash)
2916}
2917
2918/// A task's definition as its key holds it. Warm state configuration never
2919/// changes a result, and as in Nx a target's metadata, such as the run
2920/// command shown for a script, is description only.
2921pub fn keyed_definition(task: &Task) -> qk_config::Target {
2922    let mut definition = task.definition.clone();
2923    definition.extra.remove("qk:warm");
2924    definition.extra.remove("qk:threads");
2925    definition.extra.remove("metadata");
2926    // What a recording keys is the recording's own concern.
2927    definition.extra.remove("qk:ultracache");
2928    definition
2929}
2930
2931/// What a task's key holds of its project's configuration beside its
2932/// definition and resolved inputs: the project's keyed settings, such as its
2933/// root, the paths its outputs resolve to, which `{project.*}` tokens can
2934/// read from anywhere in the configuration, and all of the configuration
2935/// when a forwarded argument holds such a token, as the task reads it then.
2936pub fn task_configuration(workspace: &Workspace, task: &Task) -> Value {
2937    let project = &workspace.projects[&task.project];
2938    let mut value = json!({ "settings": project.keyed_settings() });
2939    if let Ok((outputs, _)) = paths::resolved_outputs(workspace, task) {
2940        value["outputs"] = json!(outputs);
2941    }
2942    if task.args.iter().any(|arg| arg.contains("{project")) {
2943        value["configuration"] = serde_json::to_value(project).unwrap_or_default();
2944    }
2945    value
2946}
2947
2948/// The key for a task's inputs. Objects are keyed with their fields sorted,
2949/// so the order they were written in, which configuration keeps, does not
2950/// change the key.
2951pub fn key(inputs: &Value) -> Result<String> {
2952    Ok(blake3::hash(&serde_json::to_vec(&sorted(inputs))?)
2953        .to_hex()
2954        .to_string())
2955}
2956
2957/// `value` with every object's fields in key order.
2958fn sorted(value: &Value) -> Value {
2959    match value {
2960        Value::Object(object) => {
2961            let mut fields: Vec<_> = object.iter().collect();
2962            fields.sort_unstable_by_key(|(name, _)| *name);
2963            Value::Object(
2964                fields
2965                    .into_iter()
2966                    .map(|(name, value)| (name.clone(), sorted(value)))
2967                    .collect(),
2968            )
2969        }
2970        Value::Array(items) => Value::Array(items.iter().map(sorted).collect()),
2971        other => other.clone(),
2972    }
2973}
2974
2975pub fn fingerprint(
2976    snapshot: &Snapshot,
2977    workspace: &Workspace,
2978    task: &Task,
2979    prepared: &PreparedTask,
2980    dependencies: &BTreeMap<String, String>,
2981    cancelled: &AtomicBool,
2982) -> Result<String> {
2983    key(&inputs(
2984        snapshot,
2985        workspace,
2986        task,
2987        prepared,
2988        dependencies,
2989        cancelled,
2990    )?)
2991}
2992
2993/// The key of a task keyed by its recordings, before its path set: `inputs`,
2994/// the task's key, without its declared file inputs, which a path set
2995/// replaces, but with its `"always": true` inputs, which count whatever it
2996/// read, and with what `ignoreReads` leaves out of its path sets.
2997#[allow(clippy::too_many_arguments)]
2998pub(crate) fn weak_key(
2999    snapshot: &Snapshot,
3000    workspace: &Workspace,
3001    graph: &TaskGraph,
3002    task: &Task,
3003    prepared: &PreparedTask,
3004    inputs: &Value,
3005    ignore_reads: &[String],
3006    ignored_within: &[(&str, bool)],
3007    cancelled: &AtomicBool,
3008) -> Result<String> {
3009    let mut weak = inputs.clone();
3010    let object = weak
3011        .as_object_mut()
3012        .context("a key's inputs are an object")?;
3013    object.remove("files");
3014    object.remove("dependencies");
3015    if let Some(Value::Object(values)) = object.get_mut("values") {
3016        values.retain(|name, _| {
3017            !name.starts_with("json:") && !name.starts_with("dependentTasksOutputFiles:")
3018        });
3019    }
3020    let mut always = task.clone();
3021    always.definition.inputs = Some(
3022        declared_inputs(task)
3023            .into_iter()
3024            .filter(|input| input.get("always") == Some(&Value::Bool(true)))
3025            .collect(),
3026    );
3027    let dependencies = dependency_keys(snapshot, workspace, graph, &always, cancelled)?;
3028    let always = self::inputs(
3029        snapshot,
3030        workspace,
3031        &always,
3032        prepared,
3033        &dependencies,
3034        cancelled,
3035    )?;
3036    object.insert(
3037        "always".into(),
3038        json!({"files": always["files"], "values": always["values"], "dependencies": always["dependencies"]}),
3039    );
3040    object.insert("schema".into(), json!("qk-weak-v1"));
3041    object.insert("ignoreReads".into(), json!(ignore_reads));
3042    // What its `^` entries match moves with the project graph, the projects
3043    // depended on and those nested in them that are not, so a path set
3044    // recorded under one never keys a task under another. Left out without
3045    // them, so other weak keys stay as they were.
3046    if !ignored_within.is_empty() {
3047        object.insert("ignoredWithin".into(), json!(ignored_within));
3048    }
3049    key(&weak)
3050}
3051
3052/// The dependency outputs a task's `dependentTasksOutputFiles` inputs read,
3053/// as Nx hashes them: the files each glob selects of the declared outputs of
3054/// its direct dependencies, or with `transitive` of every task it depends on.
3055/// Nothing else about a dependency keys a task.
3056pub(crate) fn dependency_keys(
3057    snapshot: &Snapshot,
3058    workspace: &Workspace,
3059    graph: &TaskGraph,
3060    task: &Task,
3061    cancelled: &AtomicBool,
3062) -> Result<BTreeMap<String, String>> {
3063    dependency_keys_impl(snapshot, workspace, graph, task, cancelled, false)
3064}
3065
3066/// Read dependency artifacts again before accepting an execution as unchanged.
3067pub(crate) fn recheck_dependency_keys(
3068    snapshot: &Snapshot,
3069    workspace: &Workspace,
3070    graph: &TaskGraph,
3071    task: &Task,
3072    cancelled: &AtomicBool,
3073) -> Result<BTreeMap<String, String>> {
3074    dependency_keys_impl(snapshot, workspace, graph, task, cancelled, true)
3075}
3076
3077fn dependency_keys_impl(
3078    snapshot: &Snapshot,
3079    workspace: &Workspace,
3080    graph: &TaskGraph,
3081    task: &Task,
3082    cancelled: &AtomicBool,
3083    fresh: bool,
3084) -> Result<BTreeMap<String, String>> {
3085    let resolved = resolve(snapshot, workspace, task, None, cancelled)?;
3086    let selections: Vec<_> = resolved.dependency_output_inputs().collect();
3087    let mut keys = BTreeMap::new();
3088    let mut fresh_outputs = HashMap::new();
3089    for (pattern, transitive) in selections {
3090        let matcher = snapshot.pattern(pattern, false)?;
3091        let mut selected = task.dependencies.clone();
3092        if transitive {
3093            let mut pending = selected.clone();
3094            while let Some(id) = pending.pop_first() {
3095                for dependency in &graph.tasks[&id].dependencies {
3096                    if selected.insert(dependency.clone()) {
3097                        pending.insert(dependency.clone());
3098                    }
3099                }
3100            }
3101        }
3102        for id in selected {
3103            // As in Nx, a dependency without declared outputs offers none.
3104            if !Outputs::new(workspace, &graph.tasks[&id])?.declared() {
3105                continue;
3106            }
3107            let outputs = if fresh {
3108                if !fresh_outputs.contains_key(&id) {
3109                    fresh_outputs.insert(
3110                        id.clone(),
3111                        Arc::new(snapshot.fresh_dependency_outputs(workspace, &graph.tasks[&id])?),
3112                    );
3113                }
3114                fresh_outputs[&id].clone()
3115            } else {
3116                snapshot.dependency_outputs(workspace, &graph.tasks[&id])?
3117            };
3118            let mut files = BTreeMap::new();
3119            for path in outputs.files.iter().filter(|path| matcher.is_match(path)) {
3120                let known = outputs.values.lock().unwrap().get(path).cloned();
3121                let value = match known {
3122                    Some(value) => value,
3123                    None => {
3124                        let value = snapshot.file_value(&workspace.root, path)?;
3125                        // Links depend on paths outside the declared output roots.
3126                        if value.get("link").is_none() {
3127                            outputs
3128                                .values
3129                                .lock()
3130                                .unwrap()
3131                                .insert(path.clone(), value.clone());
3132                        }
3133                        value
3134                    }
3135                };
3136                files.insert(path.clone(), value);
3137            }
3138            keys.insert(format!("{id}:{pattern}"), key(&json!(files))?);
3139        }
3140    }
3141    Ok(keys)
3142}
3143
3144/// What one task's `dependentTasksOutputFiles` glob selects of the outputs it
3145/// reads.
3146#[derive(Clone, Debug, PartialEq, Eq)]
3147pub struct DependencyGlob {
3148    pub task: String,
3149    pub pattern: String,
3150    pub selects: Selects,
3151}
3152
3153#[derive(Clone, Debug, PartialEq, Eq)]
3154pub enum Selects {
3155    /// None of the tasks it reads declares outputs, so nothing ever.
3156    NoDeclaredOutputs,
3157    /// Some of their outputs are not built, so it cannot be told.
3158    NotBuilt,
3159    /// None of the files their outputs hold now, this many.
3160    NoneOf(usize),
3161    /// Some of the files their outputs hold now.
3162    Some,
3163}
3164
3165/// What each `dependentTasksOutputFiles` glob of `graph`'s tasks selects of
3166/// its dependencies' outputs as they are on disk, without running anything.
3167pub fn dependency_globs(workspace: &Workspace, graph: &TaskGraph) -> Result<Vec<DependencyGlob>> {
3168    let snapshot = Snapshot::new(workspace, graph, &paths::cache_location(workspace))?;
3169    let cancelled = AtomicBool::new(false);
3170    let mut globs = Vec::new();
3171    for task in graph.tasks.values() {
3172        // A task whose inputs cannot be resolved fails as it runs instead.
3173        let Ok(resolved) = resolve(&snapshot, workspace, task, None, &cancelled) else {
3174            continue;
3175        };
3176        for (pattern, transitive) in resolved.dependency_output_inputs() {
3177            let mut selected = task.dependencies.clone();
3178            if transitive {
3179                let mut pending = selected.clone();
3180                while let Some(id) = pending.pop_first() {
3181                    for dependency in &graph.tasks[&id].dependencies {
3182                        if selected.insert(dependency.clone()) {
3183                            pending.insert(dependency.clone());
3184                        }
3185                    }
3186                }
3187            }
3188            let matcher = snapshot.pattern(pattern, false)?;
3189            // A dependency not built yet may still produce what it matches.
3190            let (mut declared, mut files, mut matched, mut unbuilt) = (false, 0, false, false);
3191            for id in &selected {
3192                let dependency = &graph.tasks[id];
3193                if !Outputs::new(workspace, dependency)?.declared() {
3194                    continue;
3195                }
3196                declared = true;
3197                let outputs = snapshot.dependency_outputs(workspace, dependency)?;
3198                unbuilt |= outputs.files.is_empty();
3199                files += outputs.files.len();
3200                matched |= outputs.files.iter().any(|path| matcher.is_match(path));
3201            }
3202            globs.push(DependencyGlob {
3203                task: task.id.clone(),
3204                pattern: pattern.to_owned(),
3205                selects: match (declared, matched, unbuilt) {
3206                    (false, ..) => Selects::NoDeclaredOutputs,
3207                    (_, true, _) => Selects::Some,
3208                    (_, _, true) => Selects::NotBuilt,
3209                    _ => Selects::NoneOf(files),
3210                },
3211            });
3212        }
3213    }
3214    Ok(globs)
3215}
3216
3217#[cfg(test)]
3218mod tests {
3219
3220    /// Every file keyed by its whole content, declared or inferred.
3221    fn whole(resolved: &Resolved) -> BTreeSet<String> {
3222        resolved.whole_files().map(str::to_owned).collect()
3223    }
3224    use super::*;
3225    use qk_taskgraph::Request;
3226
3227    fn fixture(outputs: Option<Value>) -> (tempfile::TempDir, Workspace, TaskGraph) {
3228        let root = tempfile::tempdir().unwrap();
3229        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
3230        let mut post = json!({"command": "true"});
3231        if let Some(outputs) = outputs {
3232            post["outputs"] = outputs;
3233        }
3234        std::fs::write(root.path().join("project.json"), json!({"name":"app", "targets": {
3235            "gen": {"command":"true", "outputs":["{projectRoot}/generated"]},
3236            "post": post,
3237            "build": {"command":"true", "dependsOn":["gen", "post"], "inputs":[{"dependentTasksOutputFiles":"**/*"}]}
3238        }}).to_string()).unwrap();
3239        std::fs::create_dir(root.path().join("generated")).unwrap();
3240        std::fs::write(root.path().join("generated/value"), "one").unwrap();
3241        let workspace = Workspace::load(root.path()).unwrap();
3242        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3243        (root, workspace, graph)
3244    }
3245
3246    /// A `json` glob selects a dependency's declared outputs, keyed by their
3247    /// fields, and makes that dependency a producer, as a fileset does.
3248
3249    #[test]
3250    fn keys_ignore_the_order_object_fields_were_written_in() {
3251        let written = json!({"options": {"cwd": "app", "command": "x"}, "args": ["a", "b"]});
3252        let reordered = json!({"args": ["a", "b"], "options": {"command": "x", "cwd": "app"}});
3253        assert_eq!(key(&written).unwrap(), key(&reordered).unwrap());
3254        let swapped = json!({"options": {"cwd": "app", "command": "x"}, "args": ["b", "a"]});
3255        assert_ne!(key(&written).unwrap(), key(&swapped).unwrap());
3256    }
3257    #[test]
3258    fn json_globs_select_dependency_outputs() {
3259        let root = tempfile::tempdir().unwrap();
3260        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
3261        for (path, content) in [
3262            (
3263                "apps/app/project.json",
3264                json!({"name": "app", "implicitDependencies": ["lib"], "targets": {
3265                    "build": {"command": "true", "dependsOn": ["^build"], "inputs": [
3266                        {"json": "{workspaceRoot}/libs/lib/out/*.json", "fields": ["version"]}
3267                    ]}
3268                }}),
3269            ),
3270            (
3271                "libs/lib/project.json",
3272                json!({"name": "lib", "targets": {
3273                    "build": {"command": "true", "outputs": ["{projectRoot}/out"]}
3274                }}),
3275            ),
3276            (
3277                "libs/lib/out/meta.json",
3278                json!({"version": 2, "built": "now"}),
3279            ),
3280        ] {
3281            let path = root.path().join(path);
3282            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
3283            std::fs::write(path, content.to_string()).unwrap();
3284        }
3285        let workspace = Workspace::load(root.path()).unwrap();
3286        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3287        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3288        let resolved = resolve(
3289            &snapshot,
3290            &workspace,
3291            &graph.tasks["app:build"],
3292            None,
3293            &AtomicBool::new(false),
3294        )
3295        .unwrap();
3296        assert_eq!(
3297            resolved.declared.values.get("json:libs/lib/out/meta.json"),
3298            Some(&json!({"version": 2}))
3299        );
3300        assert_eq!(
3301            resolved.declared.producers,
3302            BTreeSet::from(["lib:build".to_owned()])
3303        );
3304    }
3305
3306    /// The declared key covers a recording when every file it read is keyed,
3307    /// every file it looked for would be selected and not gitignored, and
3308    /// every entry a directory it listed could hold would be selected.
3309    #[test]
3310    fn declared_inputs_cover_what_they_would_select_and_not_what_they_leave_out() {
3311        let root = tempfile::tempdir().unwrap();
3312        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
3313        std::fs::write(
3314            root.path().join("project.json"),
3315            json!({"name": "app", "targets": {
3316                "build": {"command": "true", "inputs": [
3317                    "{projectRoot}/src/**/*", "!{projectRoot}/src/skip/**/*"
3318                ]},
3319                "gen": {"command": "true", "outputs": ["{projectRoot}/src/gen"]}
3320            }})
3321            .to_string(),
3322        )
3323        .unwrap();
3324        std::fs::write(root.path().join(".gitignore"), "src/secret.ts\n").unwrap();
3325        for path in [
3326            "src/a.ts",
3327            "src/lib/b.ts",
3328            "src/skip/c.ts",
3329            "src/gen/d.ts",
3330            "README.md",
3331        ] {
3332            let path = root.path().join(path);
3333            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
3334            std::fs::write(path, "x").unwrap();
3335        }
3336        let workspace = Workspace::load(root.path()).unwrap();
3337        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3338        let task = &graph.tasks["app:build"];
3339        let prepared = qk_executor::prepare(&workspace, task, &BTreeMap::new()).unwrap();
3340        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3341        let coverage = coverage(
3342            &snapshot,
3343            &workspace,
3344            &graph,
3345            task,
3346            &prepared,
3347            &AtomicBool::new(false),
3348        )
3349        .unwrap();
3350        let set = |part: &str, path: &str| {
3351            let mut set = crate::recorded::PathSet::default();
3352            match part {
3353                "read" => &mut set.reads,
3354                "present" => &mut set.present,
3355                "absent" => &mut set.absent,
3356                _ => &mut set.listings,
3357            }
3358            .insert(path.to_owned());
3359            set
3360        };
3361        for (part, path, covered) in [
3362            ("read", "src/a.ts", true),
3363            ("read", "README.md", false),
3364            ("read", "src/skip/c.ts", false),
3365            ("present", "src/lib", true),
3366            ("absent", "src/new.ts", true),
3367            // Excluded, or gitignored: creating it would not change the key.
3368            ("absent", "src/skip/new.ts", false),
3369            ("absent", "src/secret.ts", false),
3370            ("absent", ".env.local", false),
3371            // Another target's output, which no declared key holds.
3372            ("absent", "src/gen/e.ts", false),
3373            ("listing", "src/gen", false),
3374            ("listing", "src/lib", true),
3375            // An exclusion reaches into it, or nothing selects all of it.
3376            ("listing", "src", false),
3377            ("listing", ".", false),
3378        ] {
3379            let generated = |path: &str| path == "src/gen" || path.starts_with("src/gen/");
3380            assert_eq!(
3381                coverage.covers(&snapshot, root.path(), &set(part, path), &generated),
3382                covered,
3383                "{part} {path}"
3384            );
3385        }
3386    }
3387
3388    #[test]
3389    fn execution_fingerprints_refresh_sources_and_preserve_artifact_exclusions() {
3390        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3391        let definition = workspace
3392            .projects
3393            .get_mut("app")
3394            .unwrap()
3395            .targets
3396            .get_mut("post")
3397            .unwrap();
3398        definition
3399            .extra
3400            .insert("qk:warm".into(), json!({"paths": ["scratch"]}));
3401        std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
3402        std::fs::create_dir(root.path().join("src")).unwrap();
3403        std::fs::write(root.path().join("src/original"), "one").unwrap();
3404        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3405        let task = &graph.tasks["app:post"];
3406        let prepared = qk_executor::prepare(&workspace, task, &BTreeMap::new()).unwrap();
3407        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3408        let inputs = || {
3409            super::inputs(
3410                &snapshot,
3411                &workspace,
3412                task,
3413                &prepared,
3414                &BTreeMap::new(),
3415                &AtomicBool::new(false),
3416            )
3417            .unwrap()
3418        };
3419        let before = inputs();
3420        // Artifacts created after startup must not change the execution key.
3421        for directory in ["generated", "dist", "scratch", "cache", "ignored"] {
3422            std::fs::create_dir_all(root.path().join(directory)).unwrap();
3423            std::fs::write(root.path().join(directory).join("new"), "artifact").unwrap();
3424        }
3425        assert_eq!(before, inputs());
3426        // This covers both post-execution verification and a later task's first
3427        // fingerprint against a snapshot created before this source existed.
3428        std::fs::write(root.path().join("src/added"), "two").unwrap();
3429        let after = inputs();
3430        assert!(after["files"].get("src/added").is_some());
3431        assert_ne!(key(&before).unwrap(), key(&after).unwrap());
3432        std::fs::remove_file(root.path().join("src/added")).unwrap();
3433        assert_eq!(before, inputs());
3434        std::fs::remove_file(root.path().join("src/original")).unwrap();
3435        assert!(inputs()["files"].get("src/original").is_none());
3436    }
3437
3438    #[test]
3439    fn membership_reuses_settled_candidates_and_detects_directory_changes() {
3440        let mut fixtures = Vec::new();
3441        for git in [false, true] {
3442            let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3443            for directory in ["src/empty", "dist", "cache", "ignored"] {
3444                std::fs::create_dir_all(root.path().join(directory)).unwrap();
3445            }
3446            std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
3447            std::fs::write(root.path().join("src/original"), "one").unwrap();
3448            if git {
3449                assert!(
3450                    paths::git(root.path(), &["init", "-q"])
3451                        .unwrap()
3452                        .status
3453                        .success()
3454                );
3455                assert!(
3456                    paths::git(root.path(), &["add", "."])
3457                        .unwrap()
3458                        .status
3459                        .success()
3460                );
3461            }
3462            let snapshot =
3463                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3464            snapshot.current_files(root.path()).unwrap();
3465            fixtures.push((root, snapshot));
3466        }
3467        // Recent directory metadata deliberately uses the conservative listing
3468        // path. Waiting lets this test exercise the actual reuse path too.
3469        std::thread::sleep(Duration::from_millis(2100));
3470        for (root, snapshot) in fixtures {
3471            let files = || snapshot.current_files(root.path()).unwrap();
3472            let before = files();
3473            assert!(Arc::ptr_eq(&before, &files()));
3474            for directory in ["generated", "dist", "cache"] {
3475                std::fs::write(root.path().join(directory).join("new"), "artifact").unwrap();
3476            }
3477            assert!(Arc::ptr_eq(&before, &files()));
3478            std::fs::write(root.path().join("src/empty/added"), "two").unwrap();
3479            assert!(files().contains("src/empty/added"));
3480            std::fs::create_dir_all(root.path().join("src/new/nested")).unwrap();
3481            std::fs::write(root.path().join("src/new/nested/added"), "three").unwrap();
3482            assert!(files().contains("src/new/nested/added"));
3483            std::fs::rename(
3484                root.path().join("src/original"),
3485                root.path().join("src/renamed"),
3486            )
3487            .unwrap();
3488            let renamed = files();
3489            assert!(!renamed.contains("src/original"));
3490            assert!(renamed.contains("src/renamed"));
3491            std::fs::remove_file(root.path().join("src/renamed")).unwrap();
3492            assert!(!files().contains("src/renamed"));
3493            // Policy files must be checked even when directory entries do not
3494            // change (editing an existing ignore file in place).
3495            std::fs::write(root.path().join(".gitignore"), "ignored/\nsrc/empty/\n").unwrap();
3496            assert!(!files().contains("src/empty/added"));
3497            std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
3498            assert!(files().contains("src/empty/added"));
3499        }
3500    }
3501
3502    #[test]
3503    fn identical_ignore_rewrites_reuse_candidates_and_changed_rules_refresh() {
3504        for name in [".gitignore", ".nxignore"] {
3505            let (root, workspace, graph) = fixture(None);
3506            let policy = root.path().join(name);
3507            std::fs::write(root.path().join("alpha"), "a").unwrap();
3508            std::fs::write(root.path().join("bravo"), "b").unwrap();
3509            std::fs::write(&policy, "alpha\n").unwrap();
3510            let snapshot =
3511                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3512            let original = snapshot.current_files(root.path()).unwrap();
3513            assert!(!original.contains("alpha"));
3514            assert!(original.contains("bravo"));
3515            for _ in 0..3 {
3516                std::fs::write(&policy, "alpha\n").unwrap();
3517                assert!(Arc::ptr_eq(
3518                    &original,
3519                    &snapshot.current_files(root.path()).unwrap()
3520                ));
3521            }
3522            // Same-length content can change while coarse timestamps appear
3523            // identical. Recent policies must still compare their contents.
3524            std::fs::write(&policy, "bravo\n").unwrap();
3525            {
3526                let mut cached = snapshot.membership.lock().unwrap();
3527                Arc::make_mut(cached.as_mut().unwrap())
3528                    .stamps
3529                    .insert(policy.clone(), membership_stamp(&policy).unwrap());
3530            }
3531            let changed = snapshot.current_files(root.path()).unwrap();
3532            assert!(!Arc::ptr_eq(&original, &changed));
3533            assert!(changed.contains("alpha"));
3534            assert!(!changed.contains("bravo"));
3535            std::fs::remove_file(&policy).unwrap();
3536            assert!(
3537                snapshot
3538                    .current_files(root.path())
3539                    .unwrap()
3540                    .contains("bravo")
3541            );
3542        }
3543    }
3544
3545    #[test]
3546    fn ignore_contents_changed_after_inventory_cannot_bless_a_listing() {
3547        let (root, workspace, graph) = fixture(None);
3548        let policy = root.path().join(".nxignore");
3549        std::fs::write(&policy, "alpha\n").unwrap();
3550        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3551        snapshot.current_files(root.path()).unwrap();
3552        let membership = snapshot.membership.lock().unwrap().clone().unwrap();
3553        std::fs::write(&policy, "bravo\n").unwrap();
3554        assert!(!membership.state(None).unwrap().0);
3555    }
3556
3557    #[test]
3558    fn a_directory_missed_by_the_inventory_cannot_enable_reuse() {
3559        let (root, workspace, graph) = fixture(None);
3560        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3561        snapshot.current_files(root.path()).unwrap();
3562        std::fs::create_dir(root.path().join("new-empty")).unwrap();
3563        let mut cached = snapshot.membership.lock().unwrap();
3564        let membership = Arc::make_mut(cached.as_mut().unwrap());
3565        // Model creation between the directory walk and child-name capture:
3566        // the new directory is in its parent's names but not in the inventory.
3567        membership
3568            .directory_entries
3569            .get_mut(root.path())
3570            .unwrap()
3571            .insert((OsString::from("new-empty"), 1));
3572        assert!(membership.entries(root.path()).unwrap().is_none());
3573        assert!(!membership.state(None).unwrap().0);
3574    }
3575
3576    #[test]
3577    fn a_policy_missed_by_discovery_cannot_enable_reuse() {
3578        let (root, workspace, graph) = fixture(None);
3579        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3580        snapshot.current_files(root.path()).unwrap();
3581        std::fs::write(root.path().join(".nxignore"), "hidden\n").unwrap();
3582        let mut cached = snapshot.membership.lock().unwrap();
3583        let membership = Arc::make_mut(cached.as_mut().unwrap());
3584        // Model a new policy appearing after discovery but before capturing
3585        // its parent's entries; its content would otherwise have no stamp.
3586        membership
3587            .directory_entries
3588            .get_mut(root.path())
3589            .unwrap()
3590            .insert((OsString::from(".nxignore"), 0));
3591        assert!(membership.entries(root.path()).unwrap().is_none());
3592        assert!(!membership.state(None).unwrap().0);
3593    }
3594
3595    #[test]
3596    fn output_publication_reuses_candidates_but_source_names_still_refresh() {
3597        for partial in [false, true] {
3598            let outputs = if partial {
3599                json!(["{projectRoot}/dist", "!{projectRoot}/dist/keep"])
3600            } else {
3601                json!(["{projectRoot}/dist"])
3602            };
3603            let (root, workspace, graph) = fixture(Some(outputs));
3604            std::fs::create_dir_all(root.path().join("src")).unwrap();
3605            std::fs::write(root.path().join("src/original"), "one").unwrap();
3606            if partial {
3607                std::fs::create_dir_all(root.path().join("dist/keep")).unwrap();
3608            }
3609            let snapshot =
3610                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3611            snapshot.current_files(root.path()).unwrap();
3612            // Policies retain their conservative timestamp window. Directory
3613            // names are freshly verified throughout the window instead.
3614            std::thread::sleep(Duration::from_millis(2100));
3615            let before = snapshot.current_files(root.path()).unwrap();
3616            std::fs::create_dir_all(root.path().join("dist")).unwrap();
3617            std::fs::write(root.path().join("dist/restored"), "artifact").unwrap();
3618            let restored = snapshot.current_files(root.path()).unwrap();
3619            assert!(Arc::ptr_eq(&before, &restored));
3620            std::fs::remove_file(root.path().join("dist/restored")).unwrap();
3621            assert!(Arc::ptr_eq(
3622                &before,
3623                &snapshot.current_files(root.path()).unwrap()
3624            ));
3625            let source = if partial { "dist/keep/new" } else { "src/new" };
3626            std::fs::write(root.path().join(source), "source").unwrap();
3627            let after = snapshot.current_files(root.path()).unwrap();
3628            assert!(after.contains(source));
3629            assert!(!Arc::ptr_eq(&before, &after));
3630            std::fs::remove_file(root.path().join(source)).unwrap();
3631            assert!(
3632                !snapshot
3633                    .current_files(root.path())
3634                    .unwrap()
3635                    .contains(source)
3636            );
3637        }
3638    }
3639
3640    #[test]
3641    fn concurrent_fingerprints_refresh_without_replacing_newer_membership() {
3642        let (root, workspace, graph) = fixture(None);
3643        std::fs::create_dir_all(root.path().join("src")).unwrap();
3644        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3645        let original = snapshot.current_files(root.path()).unwrap();
3646        let barrier = std::sync::Barrier::new(9);
3647        std::thread::scope(|scope| {
3648            let workers: Vec<_> = (0..8)
3649                .map(|_| {
3650                    scope.spawn(|| {
3651                        let mut rounds = Vec::new();
3652                        for _ in 0..6 {
3653                            barrier.wait();
3654                            rounds.push(snapshot.current_files(root.path()));
3655                            barrier.wait();
3656                        }
3657                        rounds
3658                    })
3659                })
3660                .collect();
3661            for round in 0..6 {
3662                std::fs::write(root.path().join(format!("src/new{round}")), "source").unwrap();
3663                barrier.wait();
3664                barrier.wait();
3665            }
3666            // Assertions run after synchronization, so a failed membership
3667            // check cannot strand other workers at a barrier.
3668            for worker in workers {
3669                for (round, files) in worker.join().unwrap().into_iter().enumerate() {
3670                    let files = files.unwrap();
3671                    for added in 0..=round {
3672                        assert!(files.contains(&format!("src/new{added}")));
3673                    }
3674                }
3675            }
3676        });
3677        assert!(!original.contains("src/new0"));
3678        assert!(
3679            snapshot
3680                .current_files(root.path())
3681                .unwrap()
3682                .contains("src/new5")
3683        );
3684    }
3685
3686    #[test]
3687    fn retained_candidates_keep_their_dependency_output_ignore_policy() {
3688        let (root, mut workspace, _) = fixture(None);
3689        workspace
3690            .projects
3691            .get_mut("app")
3692            .unwrap()
3693            .targets
3694            .get_mut("build")
3695            .unwrap()
3696            .inputs = Some(vec![json!("{workspaceRoot}/**/*.txt")]);
3697        std::fs::create_dir(root.path().join("src")).unwrap();
3698        for name in ["alpha", "beta", "gamma"] {
3699            for directory in ["src", "generated"] {
3700                std::fs::write(root.path().join(format!("{directory}/{name}.txt")), name).unwrap();
3701            }
3702        }
3703        let policy = |keep: &str| {
3704            let ignored: String = ["alpha", "beta", "gamma"]
3705                .into_iter()
3706                .filter(|name| *name != keep)
3707                .flat_map(|name| {
3708                    [
3709                        format!("src/{name}.txt\n"),
3710                        format!("generated/{name}.txt\n"),
3711                    ]
3712                })
3713                .collect();
3714            std::fs::write(root.path().join(".nxignore"), ignored).unwrap();
3715        };
3716        policy("alpha");
3717        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3718        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3719        let first = snapshot
3720            .current_files_for(root.path(), None, "test")
3721            .unwrap();
3722        policy("beta");
3723        let second = snapshot
3724            .current_files_for(root.path(), None, "test")
3725            .unwrap();
3726        policy("gamma");
3727        let third = snapshot
3728            .current_files_for(root.path(), None, "test")
3729            .unwrap();
3730        // Deterministically pause two fingerprints after candidate acquisition,
3731        // then let another fingerprint refresh policy twice before they resolve.
3732        let cancelled = AtomicBool::new(false);
3733        let expected = |name: &str| {
3734            BTreeSet::from([
3735                ".nxignore".into(),
3736                format!("src/{name}.txt"),
3737                format!("generated/{name}.txt"),
3738            ])
3739        };
3740        for (candidates, name) in [(first, "alpha"), (second, "beta"), (third, "gamma")] {
3741            let resolved = resolve_candidates(
3742                &snapshot,
3743                &workspace,
3744                &graph.tasks["app:build"],
3745                None,
3746                &cancelled,
3747                &candidates.files,
3748                &candidates.source_ignore,
3749            )
3750            .unwrap();
3751            assert_eq!(whole(&resolved), expected(name));
3752        }
3753        // Inspection still uses its original candidate list and original policy.
3754        let inspected = resolve(
3755            &snapshot,
3756            &workspace,
3757            &graph.tasks["app:build"],
3758            None,
3759            &cancelled,
3760        )
3761        .unwrap();
3762        assert_eq!(whole(&inspected), expected("alpha"));
3763    }
3764
3765    #[test]
3766    fn scoped_membership_defers_unrelated_changes_until_a_matching_task_asks() {
3767        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3768        let targets = &mut workspace.projects.get_mut("app").unwrap().targets;
3769        targets.get_mut("post").unwrap().inputs =
3770            Some(vec![json!("{workspaceRoot}/left/**/*.txt")]);
3771        targets.get_mut("gen").unwrap().inputs =
3772            Some(vec![json!("{workspaceRoot}/right/**/*.txt")]);
3773        targets.get_mut("build").unwrap().inputs = Some(vec![json!("{workspaceRoot}/**/*.txt")]);
3774        for directory in ["left/empty", "right/empty"] {
3775            std::fs::create_dir_all(root.path().join(directory)).unwrap();
3776        }
3777        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3778        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3779        snapshot.current_files(&workspace.root).unwrap();
3780        std::thread::sleep(Duration::from_millis(2100));
3781        let left = snapshot
3782            .membership_prefixes(&workspace, &graph.tasks["app:post"])
3783            .unwrap();
3784        let right = snapshot
3785            .membership_prefixes(&workspace, &graph.tasks["app:gen"])
3786            .unwrap();
3787        let all = snapshot
3788            .membership_prefixes(&workspace, &graph.tasks["app:build"])
3789            .unwrap();
3790        let before = snapshot
3791            .current_files_for(&workspace.root, Some(&left), "test")
3792            .unwrap();
3793        std::fs::write(root.path().join("right/empty/new.txt"), "right").unwrap();
3794        let unrelated = snapshot
3795            .current_files_for(&workspace.root, Some(&left), "test")
3796            .unwrap();
3797        assert!(Arc::ptr_eq(&before.files, &unrelated.files));
3798        assert!(!unrelated.files.contains("right/empty/new.txt"));
3799        assert!(
3800            snapshot
3801                .current_files_for(&workspace.root, Some(&right), "test")
3802                .unwrap()
3803                .files
3804                .contains("right/empty/new.txt")
3805        );
3806        std::fs::create_dir_all(root.path().join("left/empty/nested")).unwrap();
3807        std::fs::write(root.path().join("left/empty/nested/new.txt"), "left").unwrap();
3808        assert!(
3809            snapshot
3810                .current_files_for(&workspace.root, Some(&left), "test")
3811                .unwrap()
3812                .files
3813                .contains("left/empty/nested/new.txt")
3814        );
3815        std::fs::write(root.path().join("right/empty/another.txt"), "right").unwrap();
3816        assert!(
3817            snapshot
3818                .current_files_for(&workspace.root, Some(&all), "test")
3819                .unwrap()
3820                .files
3821                .contains("right/empty/another.txt")
3822        );
3823    }
3824
3825    #[test]
3826    fn membership_watches_the_directories_json_globs_select_from() {
3827        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3828        let targets = &mut workspace.projects.get_mut("app").unwrap().targets;
3829        targets.get_mut("build").unwrap().inputs = Some(vec![json!(
3830            {"json": "{workspaceRoot}/config/**/*.json", "fields": ["version"]}
3831        )]);
3832        std::fs::create_dir_all(root.path().join("config/empty")).unwrap();
3833        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3834        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3835        snapshot.current_files(&workspace.root).unwrap();
3836        std::thread::sleep(Duration::from_millis(2100));
3837        let prefixes = snapshot
3838            .membership_prefixes(&workspace, &graph.tasks["app:build"])
3839            .unwrap();
3840        snapshot
3841            .current_files_for(&workspace.root, Some(&prefixes), "test")
3842            .unwrap();
3843        std::fs::write(
3844            root.path().join("config/empty/new.json"),
3845            r#"{"version": 1}"#,
3846        )
3847        .unwrap();
3848        assert!(
3849            snapshot
3850                .current_files_for(&workspace.root, Some(&prefixes), "test")
3851                .unwrap()
3852                .files
3853                .contains("config/empty/new.json")
3854        );
3855    }
3856
3857    #[test]
3858    fn membership_watches_git_ignored_tracked_parents_and_index_policy() {
3859        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3860        std::fs::create_dir_all(root.path().join("tracked/nested")).unwrap();
3861        std::fs::write(root.path().join("tracked/.gitignore"), "nested/\n").unwrap();
3862        std::fs::write(root.path().join("tracked/nested/source"), "one").unwrap();
3863        assert!(
3864            paths::git(root.path(), &["init", "-q"])
3865                .unwrap()
3866                .status
3867                .success()
3868        );
3869        assert!(
3870            paths::git(root.path(), &["add", "-f", "tracked/nested/source"])
3871                .unwrap()
3872                .status
3873                .success()
3874        );
3875        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3876        let files = || snapshot.current_files(root.path()).unwrap();
3877        assert!(files().contains("tracked/nested/source"));
3878        std::fs::remove_file(root.path().join("tracked/nested/source")).unwrap();
3879        assert!(!files().contains("tracked/nested/source"));
3880        std::fs::write(root.path().join("tracked/nested/another"), "two").unwrap();
3881        assert!(!files().contains("tracked/nested/another"));
3882        assert!(
3883            paths::git(root.path(), &["add", "-f", "tracked/nested/another"])
3884                .unwrap()
3885                .status
3886                .success()
3887        );
3888        assert!(files().contains("tracked/nested/another"));
3889        std::fs::write(root.path().join("untracked"), "three").unwrap();
3890        assert!(files().contains("untracked"));
3891        std::fs::write(root.path().join(".git/info/exclude"), "untracked\n").unwrap();
3892        assert!(!files().contains("untracked"));
3893    }
3894
3895    #[test]
3896    fn a_new_git_config_include_invalidates_settled_listing_policy() {
3897        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3898        let policy = tempfile::tempdir().unwrap();
3899        let included = policy.path().join("included.config");
3900        let excludes = policy.path().join("excludes");
3901        std::fs::write(&excludes, "hidden\n").unwrap();
3902        std::fs::write(root.path().join("hidden"), "source").unwrap();
3903        assert!(
3904            paths::git(root.path(), &["init", "-q"])
3905                .unwrap()
3906                .status
3907                .success()
3908        );
3909        assert!(
3910            paths::git(
3911                root.path(),
3912                &["config", "include.path", included.to_str().unwrap()]
3913            )
3914            .unwrap()
3915            .status
3916            .success()
3917        );
3918        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3919        snapshot.current_files(&workspace.root).unwrap();
3920        std::thread::sleep(Duration::from_millis(2100));
3921        let before = snapshot.current_files(&workspace.root).unwrap();
3922        assert!(before.contains("hidden"));
3923        assert!(Arc::ptr_eq(
3924            &before,
3925            &snapshot.current_files(&workspace.root).unwrap()
3926        ));
3927        assert!(
3928            paths::git(
3929                root.path(),
3930                &[
3931                    "config",
3932                    "--file",
3933                    included.to_str().unwrap(),
3934                    "core.excludesfile",
3935                    excludes.to_str().unwrap(),
3936                ]
3937            )
3938            .unwrap()
3939            .status
3940            .success()
3941        );
3942        assert!(
3943            !snapshot
3944                .current_files(&workspace.root)
3945                .unwrap()
3946                .contains("hidden")
3947        );
3948    }
3949
3950    #[cfg(unix)]
3951    #[test]
3952    fn git_policy_paths_preserve_quoted_origins_and_multiline_values() {
3953        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3954        let policy = tempfile::tempdir().unwrap();
3955        // Git's text output C-quotes these origins and octal-escapes UTF-8.
3956        let included = policy.path().join("included\\é\t\n.config");
3957        let excludes = policy.path().join("excludes\\é\t\n");
3958        let replacement = policy.path().join("replacement\n");
3959        std::fs::write(&excludes, "hidden\n").unwrap();
3960        std::fs::write(&replacement, "visible\n").unwrap();
3961        for file in ["hidden", "visible"] {
3962            std::fs::write(root.path().join(file), "source").unwrap();
3963        }
3964        let git = |args: &[&str]| {
3965            let output = paths::git(root.path(), args).unwrap();
3966            assert!(output.status.success(), "{output:?}");
3967            output
3968        };
3969        git(&["init", "-q"]);
3970        git(&["config", "include.path", included.to_str().unwrap()]);
3971        git(&[
3972            "config",
3973            "--file",
3974            included.to_str().unwrap(),
3975            "core.excludesfile",
3976            excludes.to_str().unwrap(),
3977        ]);
3978        let text = git(&["config", "--show-origin", "--list"]);
3979        let text = String::from_utf8_lossy(&text.stdout);
3980        let quoted_origin = text
3981            .lines()
3982            .find_map(|line| {
3983                line.strip_prefix("file:\"")
3984                    .and_then(|_| line.split_once('\t'))
3985            })
3986            .unwrap()
3987            .0
3988            .strip_prefix("file:")
3989            .unwrap();
3990        let policies = git_membership_policies(root.path());
3991        assert!(!policies.contains(&root.path().join(quoted_origin)));
3992        assert!(policies.contains(&included));
3993        assert!(policies.contains(&excludes));
3994        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3995        let initial = snapshot.current_files(&workspace.root).unwrap();
3996        assert!(!initial.contains("hidden"));
3997        assert!(initial.contains("visible"));
3998        std::thread::sleep(Duration::from_millis(2100));
3999        let settled = snapshot.current_files(&workspace.root).unwrap();
4000        assert!(Arc::ptr_eq(
4001            &settled,
4002            &snapshot.current_files(&workspace.root).unwrap()
4003        ));
4004        git(&[
4005            "config",
4006            "--file",
4007            included.to_str().unwrap(),
4008            "core.excludesfile",
4009            replacement.to_str().unwrap(),
4010        ]);
4011        let changed = snapshot.current_files(&workspace.root).unwrap();
4012        assert!(changed.contains("hidden"));
4013        assert!(!changed.contains("visible"));
4014        assert!(git_membership_policies(root.path()).contains(&replacement));
4015    }
4016
4017    #[cfg(unix)]
4018    #[test]
4019    fn symlinked_ignore_policy_never_reuses_stale_membership() {
4020        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
4021        let policy = tempfile::NamedTempFile::new().unwrap();
4022        std::fs::write(policy.path(), "hidden\n").unwrap();
4023        std::os::unix::fs::symlink(policy.path(), root.path().join(".gitignore")).unwrap();
4024        std::fs::write(root.path().join("hidden"), "source").unwrap();
4025        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
4026        assert!(
4027            !snapshot
4028                .current_files(root.path())
4029                .unwrap()
4030                .contains("hidden")
4031        );
4032        assert!(
4033            !snapshot
4034                .membership
4035                .lock()
4036                .unwrap()
4037                .as_ref()
4038                .unwrap()
4039                .settled
4040        );
4041        std::thread::sleep(Duration::from_millis(2100));
4042        let before = snapshot.current_files(root.path()).unwrap();
4043        assert!(Arc::ptr_eq(
4044            &before,
4045            &snapshot.current_files(root.path()).unwrap()
4046        ));
4047        std::fs::write(policy.path(), "").unwrap();
4048        assert!(
4049            snapshot
4050                .current_files(root.path())
4051                .unwrap()
4052                .contains("hidden")
4053        );
4054    }
4055
4056    #[cfg(unix)]
4057    #[test]
4058    fn recent_change_time_prevents_membership_reuse_despite_old_mtime() {
4059        use std::os::unix::fs::MetadataExt;
4060        let root = tempfile::tempdir().unwrap();
4061        let old = SystemTime::UNIX_EPOCH + Duration::from_secs(1);
4062        File::open(root.path())
4063            .unwrap()
4064            .set_times(std::fs::FileTimes::new().set_modified(old))
4065            .unwrap();
4066        let metadata = std::fs::metadata(root.path()).unwrap();
4067        assert!(metadata.ctime() > 1);
4068        let stamp = Stamp::new(&metadata);
4069        assert!(stamp.settled());
4070        assert!(!stamp.membership_settled());
4071    }
4072
4073    #[test]
4074    fn inspection_keeps_deleted_candidates() {
4075        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
4076        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache"))
4077            .unwrap()
4078            .with_candidates(&["src/deleted".into()]);
4079        let resolved = resolve(
4080            &snapshot,
4081            &workspace,
4082            &graph.tasks["app:post"],
4083            None,
4084            &AtomicBool::new(false),
4085        )
4086        .unwrap();
4087        assert!(resolved.declared.files.contains("src/deleted"));
4088    }
4089
4090    #[test]
4091    fn undeclared_writes_invalidate_dependency_values() {
4092        for outputs in [None, Some(json!(["{projectRoot}/generated"]))] {
4093            let (root, workspace, graph) = fixture(outputs);
4094            let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
4095            let keys = || {
4096                dependency_keys(
4097                    &snapshot,
4098                    &workspace,
4099                    &graph,
4100                    &graph.tasks["app:build"],
4101                    &AtomicBool::new(false),
4102                )
4103                .unwrap()
4104            };
4105            let before = keys();
4106            std::fs::write(root.path().join("generated/value"), "different").unwrap();
4107            snapshot.outputs_written(&workspace, &graph.tasks["app:post"]);
4108            assert_ne!(before, keys());
4109        }
4110    }
4111
4112    #[cfg(unix)]
4113    #[test]
4114    fn dependency_symlinks_recheck_targets_outside_output_roots() {
4115        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/generated"])));
4116        workspace
4117            .projects
4118            .get_mut("app")
4119            .unwrap()
4120            .targets
4121            .get_mut("gen")
4122            .unwrap()
4123            .outputs = Some(vec!["{projectRoot}/links".into()]);
4124        std::fs::create_dir(root.path().join("links")).unwrap();
4125        std::os::unix::fs::symlink("../generated/value", root.path().join("links/value")).unwrap();
4126        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
4127        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
4128        let keys = || {
4129            dependency_keys(
4130                &snapshot,
4131                &workspace,
4132                &graph,
4133                &graph.tasks["app:build"],
4134                &AtomicBool::new(false),
4135            )
4136            .unwrap()
4137        };
4138        let before = keys();
4139        std::fs::write(root.path().join("generated/value"), "different").unwrap();
4140        snapshot.outputs_written(&workspace, &graph.tasks["app:post"]);
4141        assert_ne!(before["app:gen:**/*"], keys()["app:gen:**/*"]);
4142    }
4143    /// The digest of a git-ignored file an `includeIgnored` fileset reads is
4144    /// saved with the others, so a warm run does not read it again.
4145    #[test]
4146    fn digests_of_ignored_files_read_by_include_ignored_are_saved() {
4147        let root = tempfile::tempdir().unwrap();
4148        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
4149        std::fs::write(root.path().join(".gitignore"), "generated/\n").unwrap();
4150        std::fs::write(
4151            root.path().join("project.json"),
4152            json!({"name": "app", "targets": {"build": {"command": "true", "inputs": [
4153                {"fileset": "{projectRoot}/generated/**/*", "includeIgnored": true}
4154            ]}}})
4155            .to_string(),
4156        )
4157        .unwrap();
4158        std::fs::create_dir(root.path().join("generated")).unwrap();
4159        std::fs::write(root.path().join("generated/schema.json"), "{}").unwrap();
4160        // Digests are only saved for files old enough to have settled.
4161        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
4162        std::fs::File::options()
4163            .write(true)
4164            .open(root.path().join("generated/schema.json"))
4165            .unwrap()
4166            .set_times(std::fs::FileTimes::new().set_modified(old))
4167            .unwrap();
4168        let git = |args: &[&str]| assert!(paths::git(root.path(), args).unwrap().status.success());
4169        git(&["init", "--quiet"]);
4170        let workspace = Workspace::load(root.path()).unwrap();
4171        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
4172        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
4173        assert!(!snapshot.files.contains("generated/schema.json"));
4174        let prepared =
4175            qk_executor::prepare(&workspace, &graph.tasks["app:build"], &BTreeMap::new()).unwrap();
4176        inputs(
4177            &snapshot,
4178            &workspace,
4179            &graph.tasks["app:build"],
4180            &prepared,
4181            &BTreeMap::new(),
4182            &AtomicBool::new(false),
4183        )
4184        .unwrap();
4185        snapshot.save_digests(root.path());
4186        assert!(load_digests(root.path()).contains_key("generated/schema.json"));
4187    }
4188}