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    let mut configuration = json!({
2838        "files": file_values(&inferred.files)?,
2839        "settings": workspace.config.keyed_settings(),
2840        "project": task_configuration(workspace, task),
2841    });
2842    let installed = snapshot.installed(&workspace.root, &task.id)?;
2843    if let (Some(importers), Some(installed)) = (&inferred.lockfile, &installed)
2844        && let Some(lockfile) = &installed.lockfile
2845    {
2846        let importers: BTreeMap<_, _> = importers
2847            .iter()
2848            .filter(|importer| lockfile.has_importer(importer))
2849            .map(|importer| {
2850                let digest = installed.digest(&format!("importer:{importer}"), || {
2851                    lockfile.installed(importer).unwrap_or_default()
2852                });
2853                (importer.clone(), digest)
2854            })
2855            .collect();
2856        configuration["lockfile"] = json!({
2857            "global": installed.digest("global", || BTreeSet::from([lockfile.global().to_string()])),
2858            "importers": importers,
2859        });
2860        // A lockfile keyed whole already covers the packages it installs.
2861        if !declared.external.is_empty() {
2862            let external: BTreeMap<_, _> = declared
2863                .external
2864                .iter()
2865                .map(|name| {
2866                    let digest =
2867                        installed.digest(&format!("package:{name}"), || lockfile.package(name));
2868                    // As in Nx, a package nothing installs is an error.
2869                    if digest == blake3::hash(b"").to_hex().as_str() {
2870                        bail!(
2871                            "the externalDependency {name:?} of {} could not be found",
2872                            task.id
2873                        );
2874                    }
2875                    Ok((name.clone(), digest))
2876                })
2877                .collect::<Result<_>>()?;
2878            values.insert("externalDependencies".into(), json!(external));
2879        }
2880    }
2881    if inferred.workspace_file {
2882        configuration["workspaceFile"] = match workspace_without_resolution(&workspace.root) {
2883            Some(value) => value,
2884            None => snapshot.file_value(&workspace.root, "pnpm-workspace.yaml")?,
2885        };
2886    }
2887    if !inferred.manifests.is_empty() {
2888        configuration["manifests"] = json!(inferred.manifests);
2889    }
2890    if let Some(path) = &inferred.tsconfig {
2891        let parsed = std::fs::read_to_string(workspace.root.join(path))
2892            .ok()
2893            .and_then(|text| TsConfig::parse(&text));
2894        configuration["tsconfig"] = match parsed {
2895            Some(tsconfig) if crate::inputs::selectively_hash_tsconfig(workspace) => json!({
2896                "rest": tsconfig.rest,
2897                "paths": tsconfig.paths_of(&declared.projects, |target| snapshot.owner(target)),
2898            }),
2899            Some(tsconfig) => json!({ "rest": tsconfig.rest }),
2900            None => snapshot.file_value(&workspace.root, path)?,
2901        };
2902    }
2903    let definition = keyed_definition(task);
2904    let hash = json!({
2905        "schema":"qk-local-v4", "qk":env!("CARGO_PKG_VERSION"),
2906        "platform":[std::env::consts::OS, std::env::consts::ARCH], "workspace":snapshot.workspace_prefix,
2907        "id":task.id, "args":task.args, "definition":definition, "packageManager":workspace.package_manager,
2908        "files":files, "values":values, "inferred":configuration, "dependencies":dependencies,
2909    });
2910    Ok(hash)
2911}
2912
2913/// A task's definition as its key holds it. Warm state configuration never
2914/// changes a result, and as in Nx a target's metadata, such as the run
2915/// command shown for a script, is description only.
2916pub fn keyed_definition(task: &Task) -> qk_config::Target {
2917    let mut definition = task.definition.clone();
2918    definition.extra.remove("qk:warm");
2919    definition.extra.remove("qk:threads");
2920    definition.extra.remove("metadata");
2921    // What a recording keys is the recording's own concern.
2922    definition.extra.remove("qk:ultracache");
2923    definition
2924}
2925
2926/// What a task's key holds of its project's configuration beside its
2927/// definition and resolved inputs: the project's keyed settings, such as its
2928/// root, the paths its outputs resolve to, which `{project.*}` tokens can
2929/// read from anywhere in the configuration, and all of the configuration
2930/// when a forwarded argument holds such a token, as the task reads it then.
2931pub fn task_configuration(workspace: &Workspace, task: &Task) -> Value {
2932    let project = &workspace.projects[&task.project];
2933    let mut value = json!({ "settings": project.keyed_settings() });
2934    if let Ok((outputs, _)) = paths::resolved_outputs(workspace, task) {
2935        value["outputs"] = json!(outputs);
2936    }
2937    if task.args.iter().any(|arg| arg.contains("{project")) {
2938        value["configuration"] = serde_json::to_value(project).unwrap_or_default();
2939    }
2940    value
2941}
2942
2943/// The key for a task's inputs. Objects are keyed with their fields sorted,
2944/// so the order they were written in, which configuration keeps, does not
2945/// change the key.
2946pub fn key(inputs: &Value) -> Result<String> {
2947    Ok(blake3::hash(&serde_json::to_vec(&sorted(inputs))?)
2948        .to_hex()
2949        .to_string())
2950}
2951
2952/// `value` with every object's fields in key order.
2953fn sorted(value: &Value) -> Value {
2954    match value {
2955        Value::Object(object) => {
2956            let mut fields: Vec<_> = object.iter().collect();
2957            fields.sort_unstable_by_key(|(name, _)| *name);
2958            Value::Object(
2959                fields
2960                    .into_iter()
2961                    .map(|(name, value)| (name.clone(), sorted(value)))
2962                    .collect(),
2963            )
2964        }
2965        Value::Array(items) => Value::Array(items.iter().map(sorted).collect()),
2966        other => other.clone(),
2967    }
2968}
2969
2970pub fn fingerprint(
2971    snapshot: &Snapshot,
2972    workspace: &Workspace,
2973    task: &Task,
2974    prepared: &PreparedTask,
2975    dependencies: &BTreeMap<String, String>,
2976    cancelled: &AtomicBool,
2977) -> Result<String> {
2978    key(&inputs(
2979        snapshot,
2980        workspace,
2981        task,
2982        prepared,
2983        dependencies,
2984        cancelled,
2985    )?)
2986}
2987
2988/// The key of a task keyed by its recordings, before its path set: `inputs`,
2989/// the task's key, without its declared file inputs, which a path set
2990/// replaces, but with its `"always": true` inputs, which count whatever it
2991/// read, and with what `ignoreReads` leaves out of its path sets.
2992#[allow(clippy::too_many_arguments)]
2993pub(crate) fn weak_key(
2994    snapshot: &Snapshot,
2995    workspace: &Workspace,
2996    graph: &TaskGraph,
2997    task: &Task,
2998    prepared: &PreparedTask,
2999    inputs: &Value,
3000    ignore_reads: &[String],
3001    cancelled: &AtomicBool,
3002) -> Result<String> {
3003    let mut weak = inputs.clone();
3004    let object = weak
3005        .as_object_mut()
3006        .context("a key's inputs are an object")?;
3007    object.remove("files");
3008    object.remove("dependencies");
3009    if let Some(Value::Object(values)) = object.get_mut("values") {
3010        values.retain(|name, _| {
3011            !name.starts_with("json:") && !name.starts_with("dependentTasksOutputFiles:")
3012        });
3013    }
3014    let mut always = task.clone();
3015    always.definition.inputs = Some(
3016        declared_inputs(task)
3017            .into_iter()
3018            .filter(|input| input.get("always") == Some(&Value::Bool(true)))
3019            .collect(),
3020    );
3021    let dependencies = dependency_keys(snapshot, workspace, graph, &always, cancelled)?;
3022    let always = self::inputs(
3023        snapshot,
3024        workspace,
3025        &always,
3026        prepared,
3027        &dependencies,
3028        cancelled,
3029    )?;
3030    object.insert(
3031        "always".into(),
3032        json!({"files": always["files"], "values": always["values"], "dependencies": always["dependencies"]}),
3033    );
3034    object.insert("schema".into(), json!("qk-weak-v1"));
3035    object.insert("ignoreReads".into(), json!(ignore_reads));
3036    key(&weak)
3037}
3038
3039/// The dependency outputs a task's `dependentTasksOutputFiles` inputs read,
3040/// as Nx hashes them: the files each glob selects of the declared outputs of
3041/// its direct dependencies, or with `transitive` of every task it depends on.
3042/// Nothing else about a dependency keys a task.
3043pub(crate) fn dependency_keys(
3044    snapshot: &Snapshot,
3045    workspace: &Workspace,
3046    graph: &TaskGraph,
3047    task: &Task,
3048    cancelled: &AtomicBool,
3049) -> Result<BTreeMap<String, String>> {
3050    dependency_keys_impl(snapshot, workspace, graph, task, cancelled, false)
3051}
3052
3053/// Read dependency artifacts again before accepting an execution as unchanged.
3054pub(crate) fn recheck_dependency_keys(
3055    snapshot: &Snapshot,
3056    workspace: &Workspace,
3057    graph: &TaskGraph,
3058    task: &Task,
3059    cancelled: &AtomicBool,
3060) -> Result<BTreeMap<String, String>> {
3061    dependency_keys_impl(snapshot, workspace, graph, task, cancelled, true)
3062}
3063
3064fn dependency_keys_impl(
3065    snapshot: &Snapshot,
3066    workspace: &Workspace,
3067    graph: &TaskGraph,
3068    task: &Task,
3069    cancelled: &AtomicBool,
3070    fresh: bool,
3071) -> Result<BTreeMap<String, String>> {
3072    let resolved = resolve(snapshot, workspace, task, None, cancelled)?;
3073    let selections: Vec<_> = resolved.dependency_output_inputs().collect();
3074    let mut keys = BTreeMap::new();
3075    let mut fresh_outputs = HashMap::new();
3076    for (pattern, transitive) in selections {
3077        let matcher = snapshot.pattern(pattern, false)?;
3078        let mut selected = task.dependencies.clone();
3079        if transitive {
3080            let mut pending = selected.clone();
3081            while let Some(id) = pending.pop_first() {
3082                for dependency in &graph.tasks[&id].dependencies {
3083                    if selected.insert(dependency.clone()) {
3084                        pending.insert(dependency.clone());
3085                    }
3086                }
3087            }
3088        }
3089        for id in selected {
3090            // As in Nx, a dependency without declared outputs offers none.
3091            if !Outputs::new(workspace, &graph.tasks[&id])?.declared() {
3092                continue;
3093            }
3094            let outputs = if fresh {
3095                if !fresh_outputs.contains_key(&id) {
3096                    fresh_outputs.insert(
3097                        id.clone(),
3098                        Arc::new(snapshot.fresh_dependency_outputs(workspace, &graph.tasks[&id])?),
3099                    );
3100                }
3101                fresh_outputs[&id].clone()
3102            } else {
3103                snapshot.dependency_outputs(workspace, &graph.tasks[&id])?
3104            };
3105            let mut files = BTreeMap::new();
3106            for path in outputs.files.iter().filter(|path| matcher.is_match(path)) {
3107                let known = outputs.values.lock().unwrap().get(path).cloned();
3108                let value = match known {
3109                    Some(value) => value,
3110                    None => {
3111                        let value = snapshot.file_value(&workspace.root, path)?;
3112                        // Links depend on paths outside the declared output roots.
3113                        if value.get("link").is_none() {
3114                            outputs
3115                                .values
3116                                .lock()
3117                                .unwrap()
3118                                .insert(path.clone(), value.clone());
3119                        }
3120                        value
3121                    }
3122                };
3123                files.insert(path.clone(), value);
3124            }
3125            keys.insert(format!("{id}:{pattern}"), key(&json!(files))?);
3126        }
3127    }
3128    Ok(keys)
3129}
3130
3131/// What one task's `dependentTasksOutputFiles` glob selects of the outputs it
3132/// reads.
3133#[derive(Clone, Debug, PartialEq, Eq)]
3134pub struct DependencyGlob {
3135    pub task: String,
3136    pub pattern: String,
3137    pub selects: Selects,
3138}
3139
3140#[derive(Clone, Debug, PartialEq, Eq)]
3141pub enum Selects {
3142    /// None of the tasks it reads declares outputs, so nothing ever.
3143    NoDeclaredOutputs,
3144    /// Some of their outputs are not built, so it cannot be told.
3145    NotBuilt,
3146    /// None of the files their outputs hold now, this many.
3147    NoneOf(usize),
3148    /// Some of the files their outputs hold now.
3149    Some,
3150}
3151
3152/// What each `dependentTasksOutputFiles` glob of `graph`'s tasks selects of
3153/// its dependencies' outputs as they are on disk, without running anything.
3154pub fn dependency_globs(workspace: &Workspace, graph: &TaskGraph) -> Result<Vec<DependencyGlob>> {
3155    let snapshot = Snapshot::new(workspace, graph, &paths::cache_location(workspace))?;
3156    let cancelled = AtomicBool::new(false);
3157    let mut globs = Vec::new();
3158    for task in graph.tasks.values() {
3159        // A task whose inputs cannot be resolved fails as it runs instead.
3160        let Ok(resolved) = resolve(&snapshot, workspace, task, None, &cancelled) else {
3161            continue;
3162        };
3163        for (pattern, transitive) in resolved.dependency_output_inputs() {
3164            let mut selected = task.dependencies.clone();
3165            if transitive {
3166                let mut pending = selected.clone();
3167                while let Some(id) = pending.pop_first() {
3168                    for dependency in &graph.tasks[&id].dependencies {
3169                        if selected.insert(dependency.clone()) {
3170                            pending.insert(dependency.clone());
3171                        }
3172                    }
3173                }
3174            }
3175            let matcher = snapshot.pattern(pattern, false)?;
3176            // A dependency not built yet may still produce what it matches.
3177            let (mut declared, mut files, mut matched, mut unbuilt) = (false, 0, false, false);
3178            for id in &selected {
3179                let dependency = &graph.tasks[id];
3180                if !Outputs::new(workspace, dependency)?.declared() {
3181                    continue;
3182                }
3183                declared = true;
3184                let outputs = snapshot.dependency_outputs(workspace, dependency)?;
3185                unbuilt |= outputs.files.is_empty();
3186                files += outputs.files.len();
3187                matched |= outputs.files.iter().any(|path| matcher.is_match(path));
3188            }
3189            globs.push(DependencyGlob {
3190                task: task.id.clone(),
3191                pattern: pattern.to_owned(),
3192                selects: match (declared, matched, unbuilt) {
3193                    (false, ..) => Selects::NoDeclaredOutputs,
3194                    (_, true, _) => Selects::Some,
3195                    (_, _, true) => Selects::NotBuilt,
3196                    _ => Selects::NoneOf(files),
3197                },
3198            });
3199        }
3200    }
3201    Ok(globs)
3202}
3203
3204#[cfg(test)]
3205mod tests {
3206
3207    /// Every file keyed by its whole content, declared or inferred.
3208    fn whole(resolved: &Resolved) -> BTreeSet<String> {
3209        resolved.whole_files().map(str::to_owned).collect()
3210    }
3211    use super::*;
3212    use qk_taskgraph::Request;
3213
3214    fn fixture(outputs: Option<Value>) -> (tempfile::TempDir, Workspace, TaskGraph) {
3215        let root = tempfile::tempdir().unwrap();
3216        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
3217        let mut post = json!({"command": "true"});
3218        if let Some(outputs) = outputs {
3219            post["outputs"] = outputs;
3220        }
3221        std::fs::write(root.path().join("project.json"), json!({"name":"app", "targets": {
3222            "gen": {"command":"true", "outputs":["{projectRoot}/generated"]},
3223            "post": post,
3224            "build": {"command":"true", "dependsOn":["gen", "post"], "inputs":[{"dependentTasksOutputFiles":"**/*"}]}
3225        }}).to_string()).unwrap();
3226        std::fs::create_dir(root.path().join("generated")).unwrap();
3227        std::fs::write(root.path().join("generated/value"), "one").unwrap();
3228        let workspace = Workspace::load(root.path()).unwrap();
3229        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3230        (root, workspace, graph)
3231    }
3232
3233    /// A `json` glob selects a dependency's declared outputs, keyed by their
3234    /// fields, and makes that dependency a producer, as a fileset does.
3235
3236    #[test]
3237    fn keys_ignore_the_order_object_fields_were_written_in() {
3238        let written = json!({"options": {"cwd": "app", "command": "x"}, "args": ["a", "b"]});
3239        let reordered = json!({"args": ["a", "b"], "options": {"command": "x", "cwd": "app"}});
3240        assert_eq!(key(&written).unwrap(), key(&reordered).unwrap());
3241        let swapped = json!({"options": {"cwd": "app", "command": "x"}, "args": ["b", "a"]});
3242        assert_ne!(key(&written).unwrap(), key(&swapped).unwrap());
3243    }
3244    #[test]
3245    fn json_globs_select_dependency_outputs() {
3246        let root = tempfile::tempdir().unwrap();
3247        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
3248        for (path, content) in [
3249            (
3250                "apps/app/project.json",
3251                json!({"name": "app", "implicitDependencies": ["lib"], "targets": {
3252                    "build": {"command": "true", "dependsOn": ["^build"], "inputs": [
3253                        {"json": "{workspaceRoot}/libs/lib/out/*.json", "fields": ["version"]}
3254                    ]}
3255                }}),
3256            ),
3257            (
3258                "libs/lib/project.json",
3259                json!({"name": "lib", "targets": {
3260                    "build": {"command": "true", "outputs": ["{projectRoot}/out"]}
3261                }}),
3262            ),
3263            (
3264                "libs/lib/out/meta.json",
3265                json!({"version": 2, "built": "now"}),
3266            ),
3267        ] {
3268            let path = root.path().join(path);
3269            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
3270            std::fs::write(path, content.to_string()).unwrap();
3271        }
3272        let workspace = Workspace::load(root.path()).unwrap();
3273        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3274        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3275        let resolved = resolve(
3276            &snapshot,
3277            &workspace,
3278            &graph.tasks["app:build"],
3279            None,
3280            &AtomicBool::new(false),
3281        )
3282        .unwrap();
3283        assert_eq!(
3284            resolved.declared.values.get("json:libs/lib/out/meta.json"),
3285            Some(&json!({"version": 2}))
3286        );
3287        assert_eq!(
3288            resolved.declared.producers,
3289            BTreeSet::from(["lib:build".to_owned()])
3290        );
3291    }
3292
3293    /// The declared key covers a recording when every file it read is keyed,
3294    /// every file it looked for would be selected and not gitignored, and
3295    /// every entry a directory it listed could hold would be selected.
3296    #[test]
3297    fn declared_inputs_cover_what_they_would_select_and_not_what_they_leave_out() {
3298        let root = tempfile::tempdir().unwrap();
3299        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
3300        std::fs::write(
3301            root.path().join("project.json"),
3302            json!({"name": "app", "targets": {
3303                "build": {"command": "true", "inputs": [
3304                    "{projectRoot}/src/**/*", "!{projectRoot}/src/skip/**/*"
3305                ]},
3306                "gen": {"command": "true", "outputs": ["{projectRoot}/src/gen"]}
3307            }})
3308            .to_string(),
3309        )
3310        .unwrap();
3311        std::fs::write(root.path().join(".gitignore"), "src/secret.ts\n").unwrap();
3312        for path in [
3313            "src/a.ts",
3314            "src/lib/b.ts",
3315            "src/skip/c.ts",
3316            "src/gen/d.ts",
3317            "README.md",
3318        ] {
3319            let path = root.path().join(path);
3320            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
3321            std::fs::write(path, "x").unwrap();
3322        }
3323        let workspace = Workspace::load(root.path()).unwrap();
3324        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3325        let task = &graph.tasks["app:build"];
3326        let prepared = qk_executor::prepare(&workspace, task, &BTreeMap::new()).unwrap();
3327        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3328        let coverage = coverage(
3329            &snapshot,
3330            &workspace,
3331            &graph,
3332            task,
3333            &prepared,
3334            &AtomicBool::new(false),
3335        )
3336        .unwrap();
3337        let set = |part: &str, path: &str| {
3338            let mut set = crate::recorded::PathSet::default();
3339            match part {
3340                "read" => &mut set.reads,
3341                "present" => &mut set.present,
3342                "absent" => &mut set.absent,
3343                _ => &mut set.listings,
3344            }
3345            .insert(path.to_owned());
3346            set
3347        };
3348        for (part, path, covered) in [
3349            ("read", "src/a.ts", true),
3350            ("read", "README.md", false),
3351            ("read", "src/skip/c.ts", false),
3352            ("present", "src/lib", true),
3353            ("absent", "src/new.ts", true),
3354            // Excluded, or gitignored: creating it would not change the key.
3355            ("absent", "src/skip/new.ts", false),
3356            ("absent", "src/secret.ts", false),
3357            ("absent", ".env.local", false),
3358            // Another target's output, which no declared key holds.
3359            ("absent", "src/gen/e.ts", false),
3360            ("listing", "src/gen", false),
3361            ("listing", "src/lib", true),
3362            // An exclusion reaches into it, or nothing selects all of it.
3363            ("listing", "src", false),
3364            ("listing", ".", false),
3365        ] {
3366            let generated = |path: &str| path == "src/gen" || path.starts_with("src/gen/");
3367            assert_eq!(
3368                coverage.covers(&snapshot, root.path(), &set(part, path), &generated),
3369                covered,
3370                "{part} {path}"
3371            );
3372        }
3373    }
3374
3375    #[test]
3376    fn execution_fingerprints_refresh_sources_and_preserve_artifact_exclusions() {
3377        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3378        let definition = workspace
3379            .projects
3380            .get_mut("app")
3381            .unwrap()
3382            .targets
3383            .get_mut("post")
3384            .unwrap();
3385        definition
3386            .extra
3387            .insert("qk:warm".into(), json!({"paths": ["scratch"]}));
3388        std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
3389        std::fs::create_dir(root.path().join("src")).unwrap();
3390        std::fs::write(root.path().join("src/original"), "one").unwrap();
3391        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3392        let task = &graph.tasks["app:post"];
3393        let prepared = qk_executor::prepare(&workspace, task, &BTreeMap::new()).unwrap();
3394        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3395        let inputs = || {
3396            super::inputs(
3397                &snapshot,
3398                &workspace,
3399                task,
3400                &prepared,
3401                &BTreeMap::new(),
3402                &AtomicBool::new(false),
3403            )
3404            .unwrap()
3405        };
3406        let before = inputs();
3407        // Artifacts created after startup must not change the execution key.
3408        for directory in ["generated", "dist", "scratch", "cache", "ignored"] {
3409            std::fs::create_dir_all(root.path().join(directory)).unwrap();
3410            std::fs::write(root.path().join(directory).join("new"), "artifact").unwrap();
3411        }
3412        assert_eq!(before, inputs());
3413        // This covers both post-execution verification and a later task's first
3414        // fingerprint against a snapshot created before this source existed.
3415        std::fs::write(root.path().join("src/added"), "two").unwrap();
3416        let after = inputs();
3417        assert!(after["files"].get("src/added").is_some());
3418        assert_ne!(key(&before).unwrap(), key(&after).unwrap());
3419        std::fs::remove_file(root.path().join("src/added")).unwrap();
3420        assert_eq!(before, inputs());
3421        std::fs::remove_file(root.path().join("src/original")).unwrap();
3422        assert!(inputs()["files"].get("src/original").is_none());
3423    }
3424
3425    #[test]
3426    fn membership_reuses_settled_candidates_and_detects_directory_changes() {
3427        let mut fixtures = Vec::new();
3428        for git in [false, true] {
3429            let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3430            for directory in ["src/empty", "dist", "cache", "ignored"] {
3431                std::fs::create_dir_all(root.path().join(directory)).unwrap();
3432            }
3433            std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
3434            std::fs::write(root.path().join("src/original"), "one").unwrap();
3435            if git {
3436                assert!(
3437                    paths::git(root.path(), &["init", "-q"])
3438                        .unwrap()
3439                        .status
3440                        .success()
3441                );
3442                assert!(
3443                    paths::git(root.path(), &["add", "."])
3444                        .unwrap()
3445                        .status
3446                        .success()
3447                );
3448            }
3449            let snapshot =
3450                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3451            snapshot.current_files(root.path()).unwrap();
3452            fixtures.push((root, snapshot));
3453        }
3454        // Recent directory metadata deliberately uses the conservative listing
3455        // path. Waiting lets this test exercise the actual reuse path too.
3456        std::thread::sleep(Duration::from_millis(2100));
3457        for (root, snapshot) in fixtures {
3458            let files = || snapshot.current_files(root.path()).unwrap();
3459            let before = files();
3460            assert!(Arc::ptr_eq(&before, &files()));
3461            for directory in ["generated", "dist", "cache"] {
3462                std::fs::write(root.path().join(directory).join("new"), "artifact").unwrap();
3463            }
3464            assert!(Arc::ptr_eq(&before, &files()));
3465            std::fs::write(root.path().join("src/empty/added"), "two").unwrap();
3466            assert!(files().contains("src/empty/added"));
3467            std::fs::create_dir_all(root.path().join("src/new/nested")).unwrap();
3468            std::fs::write(root.path().join("src/new/nested/added"), "three").unwrap();
3469            assert!(files().contains("src/new/nested/added"));
3470            std::fs::rename(
3471                root.path().join("src/original"),
3472                root.path().join("src/renamed"),
3473            )
3474            .unwrap();
3475            let renamed = files();
3476            assert!(!renamed.contains("src/original"));
3477            assert!(renamed.contains("src/renamed"));
3478            std::fs::remove_file(root.path().join("src/renamed")).unwrap();
3479            assert!(!files().contains("src/renamed"));
3480            // Policy files must be checked even when directory entries do not
3481            // change (editing an existing ignore file in place).
3482            std::fs::write(root.path().join(".gitignore"), "ignored/\nsrc/empty/\n").unwrap();
3483            assert!(!files().contains("src/empty/added"));
3484            std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
3485            assert!(files().contains("src/empty/added"));
3486        }
3487    }
3488
3489    #[test]
3490    fn identical_ignore_rewrites_reuse_candidates_and_changed_rules_refresh() {
3491        for name in [".gitignore", ".nxignore"] {
3492            let (root, workspace, graph) = fixture(None);
3493            let policy = root.path().join(name);
3494            std::fs::write(root.path().join("alpha"), "a").unwrap();
3495            std::fs::write(root.path().join("bravo"), "b").unwrap();
3496            std::fs::write(&policy, "alpha\n").unwrap();
3497            let snapshot =
3498                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3499            let original = snapshot.current_files(root.path()).unwrap();
3500            assert!(!original.contains("alpha"));
3501            assert!(original.contains("bravo"));
3502            for _ in 0..3 {
3503                std::fs::write(&policy, "alpha\n").unwrap();
3504                assert!(Arc::ptr_eq(
3505                    &original,
3506                    &snapshot.current_files(root.path()).unwrap()
3507                ));
3508            }
3509            // Same-length content can change while coarse timestamps appear
3510            // identical. Recent policies must still compare their contents.
3511            std::fs::write(&policy, "bravo\n").unwrap();
3512            {
3513                let mut cached = snapshot.membership.lock().unwrap();
3514                Arc::make_mut(cached.as_mut().unwrap())
3515                    .stamps
3516                    .insert(policy.clone(), membership_stamp(&policy).unwrap());
3517            }
3518            let changed = snapshot.current_files(root.path()).unwrap();
3519            assert!(!Arc::ptr_eq(&original, &changed));
3520            assert!(changed.contains("alpha"));
3521            assert!(!changed.contains("bravo"));
3522            std::fs::remove_file(&policy).unwrap();
3523            assert!(
3524                snapshot
3525                    .current_files(root.path())
3526                    .unwrap()
3527                    .contains("bravo")
3528            );
3529        }
3530    }
3531
3532    #[test]
3533    fn ignore_contents_changed_after_inventory_cannot_bless_a_listing() {
3534        let (root, workspace, graph) = fixture(None);
3535        let policy = root.path().join(".nxignore");
3536        std::fs::write(&policy, "alpha\n").unwrap();
3537        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3538        snapshot.current_files(root.path()).unwrap();
3539        let membership = snapshot.membership.lock().unwrap().clone().unwrap();
3540        std::fs::write(&policy, "bravo\n").unwrap();
3541        assert!(!membership.state(None).unwrap().0);
3542    }
3543
3544    #[test]
3545    fn a_directory_missed_by_the_inventory_cannot_enable_reuse() {
3546        let (root, workspace, graph) = fixture(None);
3547        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3548        snapshot.current_files(root.path()).unwrap();
3549        std::fs::create_dir(root.path().join("new-empty")).unwrap();
3550        let mut cached = snapshot.membership.lock().unwrap();
3551        let membership = Arc::make_mut(cached.as_mut().unwrap());
3552        // Model creation between the directory walk and child-name capture:
3553        // the new directory is in its parent's names but not in the inventory.
3554        membership
3555            .directory_entries
3556            .get_mut(root.path())
3557            .unwrap()
3558            .insert((OsString::from("new-empty"), 1));
3559        assert!(membership.entries(root.path()).unwrap().is_none());
3560        assert!(!membership.state(None).unwrap().0);
3561    }
3562
3563    #[test]
3564    fn a_policy_missed_by_discovery_cannot_enable_reuse() {
3565        let (root, workspace, graph) = fixture(None);
3566        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3567        snapshot.current_files(root.path()).unwrap();
3568        std::fs::write(root.path().join(".nxignore"), "hidden\n").unwrap();
3569        let mut cached = snapshot.membership.lock().unwrap();
3570        let membership = Arc::make_mut(cached.as_mut().unwrap());
3571        // Model a new policy appearing after discovery but before capturing
3572        // its parent's entries; its content would otherwise have no stamp.
3573        membership
3574            .directory_entries
3575            .get_mut(root.path())
3576            .unwrap()
3577            .insert((OsString::from(".nxignore"), 0));
3578        assert!(membership.entries(root.path()).unwrap().is_none());
3579        assert!(!membership.state(None).unwrap().0);
3580    }
3581
3582    #[test]
3583    fn output_publication_reuses_candidates_but_source_names_still_refresh() {
3584        for partial in [false, true] {
3585            let outputs = if partial {
3586                json!(["{projectRoot}/dist", "!{projectRoot}/dist/keep"])
3587            } else {
3588                json!(["{projectRoot}/dist"])
3589            };
3590            let (root, workspace, graph) = fixture(Some(outputs));
3591            std::fs::create_dir_all(root.path().join("src")).unwrap();
3592            std::fs::write(root.path().join("src/original"), "one").unwrap();
3593            if partial {
3594                std::fs::create_dir_all(root.path().join("dist/keep")).unwrap();
3595            }
3596            let snapshot =
3597                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3598            snapshot.current_files(root.path()).unwrap();
3599            // Policies retain their conservative timestamp window. Directory
3600            // names are freshly verified throughout the window instead.
3601            std::thread::sleep(Duration::from_millis(2100));
3602            let before = snapshot.current_files(root.path()).unwrap();
3603            std::fs::create_dir_all(root.path().join("dist")).unwrap();
3604            std::fs::write(root.path().join("dist/restored"), "artifact").unwrap();
3605            let restored = snapshot.current_files(root.path()).unwrap();
3606            assert!(Arc::ptr_eq(&before, &restored));
3607            std::fs::remove_file(root.path().join("dist/restored")).unwrap();
3608            assert!(Arc::ptr_eq(
3609                &before,
3610                &snapshot.current_files(root.path()).unwrap()
3611            ));
3612            let source = if partial { "dist/keep/new" } else { "src/new" };
3613            std::fs::write(root.path().join(source), "source").unwrap();
3614            let after = snapshot.current_files(root.path()).unwrap();
3615            assert!(after.contains(source));
3616            assert!(!Arc::ptr_eq(&before, &after));
3617            std::fs::remove_file(root.path().join(source)).unwrap();
3618            assert!(
3619                !snapshot
3620                    .current_files(root.path())
3621                    .unwrap()
3622                    .contains(source)
3623            );
3624        }
3625    }
3626
3627    #[test]
3628    fn concurrent_fingerprints_refresh_without_replacing_newer_membership() {
3629        let (root, workspace, graph) = fixture(None);
3630        std::fs::create_dir_all(root.path().join("src")).unwrap();
3631        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3632        let original = snapshot.current_files(root.path()).unwrap();
3633        let barrier = std::sync::Barrier::new(9);
3634        std::thread::scope(|scope| {
3635            let workers: Vec<_> = (0..8)
3636                .map(|_| {
3637                    scope.spawn(|| {
3638                        let mut rounds = Vec::new();
3639                        for _ in 0..6 {
3640                            barrier.wait();
3641                            rounds.push(snapshot.current_files(root.path()));
3642                            barrier.wait();
3643                        }
3644                        rounds
3645                    })
3646                })
3647                .collect();
3648            for round in 0..6 {
3649                std::fs::write(root.path().join(format!("src/new{round}")), "source").unwrap();
3650                barrier.wait();
3651                barrier.wait();
3652            }
3653            // Assertions run after synchronization, so a failed membership
3654            // check cannot strand other workers at a barrier.
3655            for worker in workers {
3656                for (round, files) in worker.join().unwrap().into_iter().enumerate() {
3657                    let files = files.unwrap();
3658                    for added in 0..=round {
3659                        assert!(files.contains(&format!("src/new{added}")));
3660                    }
3661                }
3662            }
3663        });
3664        assert!(!original.contains("src/new0"));
3665        assert!(
3666            snapshot
3667                .current_files(root.path())
3668                .unwrap()
3669                .contains("src/new5")
3670        );
3671    }
3672
3673    #[test]
3674    fn retained_candidates_keep_their_dependency_output_ignore_policy() {
3675        let (root, mut workspace, _) = fixture(None);
3676        workspace
3677            .projects
3678            .get_mut("app")
3679            .unwrap()
3680            .targets
3681            .get_mut("build")
3682            .unwrap()
3683            .inputs = Some(vec![json!("{workspaceRoot}/**/*.txt")]);
3684        std::fs::create_dir(root.path().join("src")).unwrap();
3685        for name in ["alpha", "beta", "gamma"] {
3686            for directory in ["src", "generated"] {
3687                std::fs::write(root.path().join(format!("{directory}/{name}.txt")), name).unwrap();
3688            }
3689        }
3690        let policy = |keep: &str| {
3691            let ignored: String = ["alpha", "beta", "gamma"]
3692                .into_iter()
3693                .filter(|name| *name != keep)
3694                .flat_map(|name| {
3695                    [
3696                        format!("src/{name}.txt\n"),
3697                        format!("generated/{name}.txt\n"),
3698                    ]
3699                })
3700                .collect();
3701            std::fs::write(root.path().join(".nxignore"), ignored).unwrap();
3702        };
3703        policy("alpha");
3704        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3705        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3706        let first = snapshot
3707            .current_files_for(root.path(), None, "test")
3708            .unwrap();
3709        policy("beta");
3710        let second = snapshot
3711            .current_files_for(root.path(), None, "test")
3712            .unwrap();
3713        policy("gamma");
3714        let third = snapshot
3715            .current_files_for(root.path(), None, "test")
3716            .unwrap();
3717        // Deterministically pause two fingerprints after candidate acquisition,
3718        // then let another fingerprint refresh policy twice before they resolve.
3719        let cancelled = AtomicBool::new(false);
3720        let expected = |name: &str| {
3721            BTreeSet::from([
3722                ".nxignore".into(),
3723                format!("src/{name}.txt"),
3724                format!("generated/{name}.txt"),
3725            ])
3726        };
3727        for (candidates, name) in [(first, "alpha"), (second, "beta"), (third, "gamma")] {
3728            let resolved = resolve_candidates(
3729                &snapshot,
3730                &workspace,
3731                &graph.tasks["app:build"],
3732                None,
3733                &cancelled,
3734                &candidates.files,
3735                &candidates.source_ignore,
3736            )
3737            .unwrap();
3738            assert_eq!(whole(&resolved), expected(name));
3739        }
3740        // Inspection still uses its original candidate list and original policy.
3741        let inspected = resolve(
3742            &snapshot,
3743            &workspace,
3744            &graph.tasks["app:build"],
3745            None,
3746            &cancelled,
3747        )
3748        .unwrap();
3749        assert_eq!(whole(&inspected), expected("alpha"));
3750    }
3751
3752    #[test]
3753    fn scoped_membership_defers_unrelated_changes_until_a_matching_task_asks() {
3754        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3755        let targets = &mut workspace.projects.get_mut("app").unwrap().targets;
3756        targets.get_mut("post").unwrap().inputs =
3757            Some(vec![json!("{workspaceRoot}/left/**/*.txt")]);
3758        targets.get_mut("gen").unwrap().inputs =
3759            Some(vec![json!("{workspaceRoot}/right/**/*.txt")]);
3760        targets.get_mut("build").unwrap().inputs = Some(vec![json!("{workspaceRoot}/**/*.txt")]);
3761        for directory in ["left/empty", "right/empty"] {
3762            std::fs::create_dir_all(root.path().join(directory)).unwrap();
3763        }
3764        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3765        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3766        snapshot.current_files(&workspace.root).unwrap();
3767        std::thread::sleep(Duration::from_millis(2100));
3768        let left = snapshot
3769            .membership_prefixes(&workspace, &graph.tasks["app:post"])
3770            .unwrap();
3771        let right = snapshot
3772            .membership_prefixes(&workspace, &graph.tasks["app:gen"])
3773            .unwrap();
3774        let all = snapshot
3775            .membership_prefixes(&workspace, &graph.tasks["app:build"])
3776            .unwrap();
3777        let before = snapshot
3778            .current_files_for(&workspace.root, Some(&left), "test")
3779            .unwrap();
3780        std::fs::write(root.path().join("right/empty/new.txt"), "right").unwrap();
3781        let unrelated = snapshot
3782            .current_files_for(&workspace.root, Some(&left), "test")
3783            .unwrap();
3784        assert!(Arc::ptr_eq(&before.files, &unrelated.files));
3785        assert!(!unrelated.files.contains("right/empty/new.txt"));
3786        assert!(
3787            snapshot
3788                .current_files_for(&workspace.root, Some(&right), "test")
3789                .unwrap()
3790                .files
3791                .contains("right/empty/new.txt")
3792        );
3793        std::fs::create_dir_all(root.path().join("left/empty/nested")).unwrap();
3794        std::fs::write(root.path().join("left/empty/nested/new.txt"), "left").unwrap();
3795        assert!(
3796            snapshot
3797                .current_files_for(&workspace.root, Some(&left), "test")
3798                .unwrap()
3799                .files
3800                .contains("left/empty/nested/new.txt")
3801        );
3802        std::fs::write(root.path().join("right/empty/another.txt"), "right").unwrap();
3803        assert!(
3804            snapshot
3805                .current_files_for(&workspace.root, Some(&all), "test")
3806                .unwrap()
3807                .files
3808                .contains("right/empty/another.txt")
3809        );
3810    }
3811
3812    #[test]
3813    fn membership_watches_the_directories_json_globs_select_from() {
3814        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3815        let targets = &mut workspace.projects.get_mut("app").unwrap().targets;
3816        targets.get_mut("build").unwrap().inputs = Some(vec![json!(
3817            {"json": "{workspaceRoot}/config/**/*.json", "fields": ["version"]}
3818        )]);
3819        std::fs::create_dir_all(root.path().join("config/empty")).unwrap();
3820        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3821        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3822        snapshot.current_files(&workspace.root).unwrap();
3823        std::thread::sleep(Duration::from_millis(2100));
3824        let prefixes = snapshot
3825            .membership_prefixes(&workspace, &graph.tasks["app:build"])
3826            .unwrap();
3827        snapshot
3828            .current_files_for(&workspace.root, Some(&prefixes), "test")
3829            .unwrap();
3830        std::fs::write(
3831            root.path().join("config/empty/new.json"),
3832            r#"{"version": 1}"#,
3833        )
3834        .unwrap();
3835        assert!(
3836            snapshot
3837                .current_files_for(&workspace.root, Some(&prefixes), "test")
3838                .unwrap()
3839                .files
3840                .contains("config/empty/new.json")
3841        );
3842    }
3843
3844    #[test]
3845    fn membership_watches_git_ignored_tracked_parents_and_index_policy() {
3846        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3847        std::fs::create_dir_all(root.path().join("tracked/nested")).unwrap();
3848        std::fs::write(root.path().join("tracked/.gitignore"), "nested/\n").unwrap();
3849        std::fs::write(root.path().join("tracked/nested/source"), "one").unwrap();
3850        assert!(
3851            paths::git(root.path(), &["init", "-q"])
3852                .unwrap()
3853                .status
3854                .success()
3855        );
3856        assert!(
3857            paths::git(root.path(), &["add", "-f", "tracked/nested/source"])
3858                .unwrap()
3859                .status
3860                .success()
3861        );
3862        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3863        let files = || snapshot.current_files(root.path()).unwrap();
3864        assert!(files().contains("tracked/nested/source"));
3865        std::fs::remove_file(root.path().join("tracked/nested/source")).unwrap();
3866        assert!(!files().contains("tracked/nested/source"));
3867        std::fs::write(root.path().join("tracked/nested/another"), "two").unwrap();
3868        assert!(!files().contains("tracked/nested/another"));
3869        assert!(
3870            paths::git(root.path(), &["add", "-f", "tracked/nested/another"])
3871                .unwrap()
3872                .status
3873                .success()
3874        );
3875        assert!(files().contains("tracked/nested/another"));
3876        std::fs::write(root.path().join("untracked"), "three").unwrap();
3877        assert!(files().contains("untracked"));
3878        std::fs::write(root.path().join(".git/info/exclude"), "untracked\n").unwrap();
3879        assert!(!files().contains("untracked"));
3880    }
3881
3882    #[test]
3883    fn a_new_git_config_include_invalidates_settled_listing_policy() {
3884        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3885        let policy = tempfile::tempdir().unwrap();
3886        let included = policy.path().join("included.config");
3887        let excludes = policy.path().join("excludes");
3888        std::fs::write(&excludes, "hidden\n").unwrap();
3889        std::fs::write(root.path().join("hidden"), "source").unwrap();
3890        assert!(
3891            paths::git(root.path(), &["init", "-q"])
3892                .unwrap()
3893                .status
3894                .success()
3895        );
3896        assert!(
3897            paths::git(
3898                root.path(),
3899                &["config", "include.path", included.to_str().unwrap()]
3900            )
3901            .unwrap()
3902            .status
3903            .success()
3904        );
3905        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3906        snapshot.current_files(&workspace.root).unwrap();
3907        std::thread::sleep(Duration::from_millis(2100));
3908        let before = snapshot.current_files(&workspace.root).unwrap();
3909        assert!(before.contains("hidden"));
3910        assert!(Arc::ptr_eq(
3911            &before,
3912            &snapshot.current_files(&workspace.root).unwrap()
3913        ));
3914        assert!(
3915            paths::git(
3916                root.path(),
3917                &[
3918                    "config",
3919                    "--file",
3920                    included.to_str().unwrap(),
3921                    "core.excludesfile",
3922                    excludes.to_str().unwrap(),
3923                ]
3924            )
3925            .unwrap()
3926            .status
3927            .success()
3928        );
3929        assert!(
3930            !snapshot
3931                .current_files(&workspace.root)
3932                .unwrap()
3933                .contains("hidden")
3934        );
3935    }
3936
3937    #[cfg(unix)]
3938    #[test]
3939    fn git_policy_paths_preserve_quoted_origins_and_multiline_values() {
3940        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3941        let policy = tempfile::tempdir().unwrap();
3942        // Git's text output C-quotes these origins and octal-escapes UTF-8.
3943        let included = policy.path().join("included\\é\t\n.config");
3944        let excludes = policy.path().join("excludes\\é\t\n");
3945        let replacement = policy.path().join("replacement\n");
3946        std::fs::write(&excludes, "hidden\n").unwrap();
3947        std::fs::write(&replacement, "visible\n").unwrap();
3948        for file in ["hidden", "visible"] {
3949            std::fs::write(root.path().join(file), "source").unwrap();
3950        }
3951        let git = |args: &[&str]| {
3952            let output = paths::git(root.path(), args).unwrap();
3953            assert!(output.status.success(), "{output:?}");
3954            output
3955        };
3956        git(&["init", "-q"]);
3957        git(&["config", "include.path", included.to_str().unwrap()]);
3958        git(&[
3959            "config",
3960            "--file",
3961            included.to_str().unwrap(),
3962            "core.excludesfile",
3963            excludes.to_str().unwrap(),
3964        ]);
3965        let text = git(&["config", "--show-origin", "--list"]);
3966        let text = String::from_utf8_lossy(&text.stdout);
3967        let quoted_origin = text
3968            .lines()
3969            .find_map(|line| {
3970                line.strip_prefix("file:\"")
3971                    .and_then(|_| line.split_once('\t'))
3972            })
3973            .unwrap()
3974            .0
3975            .strip_prefix("file:")
3976            .unwrap();
3977        let policies = git_membership_policies(root.path());
3978        assert!(!policies.contains(&root.path().join(quoted_origin)));
3979        assert!(policies.contains(&included));
3980        assert!(policies.contains(&excludes));
3981        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3982        let initial = snapshot.current_files(&workspace.root).unwrap();
3983        assert!(!initial.contains("hidden"));
3984        assert!(initial.contains("visible"));
3985        std::thread::sleep(Duration::from_millis(2100));
3986        let settled = snapshot.current_files(&workspace.root).unwrap();
3987        assert!(Arc::ptr_eq(
3988            &settled,
3989            &snapshot.current_files(&workspace.root).unwrap()
3990        ));
3991        git(&[
3992            "config",
3993            "--file",
3994            included.to_str().unwrap(),
3995            "core.excludesfile",
3996            replacement.to_str().unwrap(),
3997        ]);
3998        let changed = snapshot.current_files(&workspace.root).unwrap();
3999        assert!(changed.contains("hidden"));
4000        assert!(!changed.contains("visible"));
4001        assert!(git_membership_policies(root.path()).contains(&replacement));
4002    }
4003
4004    #[cfg(unix)]
4005    #[test]
4006    fn symlinked_ignore_policy_never_reuses_stale_membership() {
4007        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
4008        let policy = tempfile::NamedTempFile::new().unwrap();
4009        std::fs::write(policy.path(), "hidden\n").unwrap();
4010        std::os::unix::fs::symlink(policy.path(), root.path().join(".gitignore")).unwrap();
4011        std::fs::write(root.path().join("hidden"), "source").unwrap();
4012        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
4013        assert!(
4014            !snapshot
4015                .current_files(root.path())
4016                .unwrap()
4017                .contains("hidden")
4018        );
4019        assert!(
4020            !snapshot
4021                .membership
4022                .lock()
4023                .unwrap()
4024                .as_ref()
4025                .unwrap()
4026                .settled
4027        );
4028        std::thread::sleep(Duration::from_millis(2100));
4029        let before = snapshot.current_files(root.path()).unwrap();
4030        assert!(Arc::ptr_eq(
4031            &before,
4032            &snapshot.current_files(root.path()).unwrap()
4033        ));
4034        std::fs::write(policy.path(), "").unwrap();
4035        assert!(
4036            snapshot
4037                .current_files(root.path())
4038                .unwrap()
4039                .contains("hidden")
4040        );
4041    }
4042
4043    #[cfg(unix)]
4044    #[test]
4045    fn recent_change_time_prevents_membership_reuse_despite_old_mtime() {
4046        use std::os::unix::fs::MetadataExt;
4047        let root = tempfile::tempdir().unwrap();
4048        let old = SystemTime::UNIX_EPOCH + Duration::from_secs(1);
4049        File::open(root.path())
4050            .unwrap()
4051            .set_times(std::fs::FileTimes::new().set_modified(old))
4052            .unwrap();
4053        let metadata = std::fs::metadata(root.path()).unwrap();
4054        assert!(metadata.ctime() > 1);
4055        let stamp = Stamp::new(&metadata);
4056        assert!(stamp.settled());
4057        assert!(!stamp.membership_settled());
4058    }
4059
4060    #[test]
4061    fn inspection_keeps_deleted_candidates() {
4062        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
4063        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache"))
4064            .unwrap()
4065            .with_candidates(&["src/deleted".into()]);
4066        let resolved = resolve(
4067            &snapshot,
4068            &workspace,
4069            &graph.tasks["app:post"],
4070            None,
4071            &AtomicBool::new(false),
4072        )
4073        .unwrap();
4074        assert!(resolved.declared.files.contains("src/deleted"));
4075    }
4076
4077    #[test]
4078    fn undeclared_writes_invalidate_dependency_values() {
4079        for outputs in [None, Some(json!(["{projectRoot}/generated"]))] {
4080            let (root, workspace, graph) = fixture(outputs);
4081            let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
4082            let keys = || {
4083                dependency_keys(
4084                    &snapshot,
4085                    &workspace,
4086                    &graph,
4087                    &graph.tasks["app:build"],
4088                    &AtomicBool::new(false),
4089                )
4090                .unwrap()
4091            };
4092            let before = keys();
4093            std::fs::write(root.path().join("generated/value"), "different").unwrap();
4094            snapshot.outputs_written(&workspace, &graph.tasks["app:post"]);
4095            assert_ne!(before, keys());
4096        }
4097    }
4098
4099    #[cfg(unix)]
4100    #[test]
4101    fn dependency_symlinks_recheck_targets_outside_output_roots() {
4102        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/generated"])));
4103        workspace
4104            .projects
4105            .get_mut("app")
4106            .unwrap()
4107            .targets
4108            .get_mut("gen")
4109            .unwrap()
4110            .outputs = Some(vec!["{projectRoot}/links".into()]);
4111        std::fs::create_dir(root.path().join("links")).unwrap();
4112        std::os::unix::fs::symlink("../generated/value", root.path().join("links/value")).unwrap();
4113        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
4114        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
4115        let keys = || {
4116            dependency_keys(
4117                &snapshot,
4118                &workspace,
4119                &graph,
4120                &graph.tasks["app:build"],
4121                &AtomicBool::new(false),
4122            )
4123            .unwrap()
4124        };
4125        let before = keys();
4126        std::fs::write(root.path().join("generated/value"), "different").unwrap();
4127        snapshot.outputs_written(&workspace, &graph.tasks["app:post"]);
4128        assert_ne!(before["app:gen:**/*"], keys()["app:gen:**/*"]);
4129    }
4130    /// The digest of a git-ignored file an `includeIgnored` fileset reads is
4131    /// saved with the others, so a warm run does not read it again.
4132    #[test]
4133    fn digests_of_ignored_files_read_by_include_ignored_are_saved() {
4134        let root = tempfile::tempdir().unwrap();
4135        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
4136        std::fs::write(root.path().join(".gitignore"), "generated/\n").unwrap();
4137        std::fs::write(
4138            root.path().join("project.json"),
4139            json!({"name": "app", "targets": {"build": {"command": "true", "inputs": [
4140                {"fileset": "{projectRoot}/generated/**/*", "includeIgnored": true}
4141            ]}}})
4142            .to_string(),
4143        )
4144        .unwrap();
4145        std::fs::create_dir(root.path().join("generated")).unwrap();
4146        std::fs::write(root.path().join("generated/schema.json"), "{}").unwrap();
4147        // Digests are only saved for files old enough to have settled.
4148        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
4149        std::fs::File::options()
4150            .write(true)
4151            .open(root.path().join("generated/schema.json"))
4152            .unwrap()
4153            .set_times(std::fs::FileTimes::new().set_modified(old))
4154            .unwrap();
4155        let git = |args: &[&str]| assert!(paths::git(root.path(), args).unwrap().status.success());
4156        git(&["init", "--quiet"]);
4157        let workspace = Workspace::load(root.path()).unwrap();
4158        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
4159        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
4160        assert!(!snapshot.files.contains("generated/schema.json"));
4161        let prepared =
4162            qk_executor::prepare(&workspace, &graph.tasks["app:build"], &BTreeMap::new()).unwrap();
4163        inputs(
4164            &snapshot,
4165            &workspace,
4166            &graph.tasks["app:build"],
4167            &prepared,
4168            &BTreeMap::new(),
4169            &AtomicBool::new(false),
4170        )
4171        .unwrap();
4172        snapshot.save_digests(root.path());
4173        assert!(load_digests(root.path()).contains_key("generated/schema.json"));
4174    }
4175}