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