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    fn file_value(&self, root: &Path, path: &str) -> Result<Value> {
1112        self.file_value_with_links(root, path, &mut BTreeSet::new())
1113    }
1114
1115    fn file_value_with_links(
1116        &self,
1117        root: &Path,
1118        path: &str,
1119        visiting: &mut BTreeSet<PathBuf>,
1120    ) -> Result<Value> {
1121        self.safe_parents(root, path)?;
1122        let absolute = root.join(path);
1123        let metadata = std::fs::symlink_metadata(&absolute)?;
1124        if metadata.file_type().is_symlink() {
1125            let target = std::fs::read_link(&absolute)?;
1126            // A dangling link is keyed as such, so the key changes once it resolves.
1127            let Ok(resolved) = absolute.canonicalize() else {
1128                return Ok(json!({"link":target, "dangling":true}));
1129            };
1130            let Ok(relative) = resolved.strip_prefix(&self.canonical_root) else {
1131                bail!("input symlink resolves outside the workspace: {path}");
1132            };
1133            if resolved.is_file() {
1134                let metadata = std::fs::metadata(&resolved)?;
1135                let key = paths::relative(Path::new(""), relative)?;
1136                return Ok(
1137                    json!({"link":target, "content":self.digest(&key, &resolved, &metadata)?,
1138                    "mode":crate::store::mode(&metadata) & 0o111 != 0}),
1139                );
1140            }
1141            let relative = paths::relative(Path::new(""), relative)?;
1142            if relative.is_empty() {
1143                bail!("input symlink resolves to the workspace root: {path}");
1144            }
1145            if !visiting.insert(resolved.clone()) {
1146                bail!("directory input symlink cycle: {path}");
1147            }
1148            let mut contents = BTreeMap::new();
1149            // Selecting the link explicitly reads its target, even when source
1150            // discovery ignores that target or another link is nested inside it.
1151            for entry in walkdir::WalkDir::new(&resolved).follow_links(false) {
1152                let entry = entry?;
1153                if entry.file_type().is_dir() {
1154                    continue;
1155                }
1156                let file = paths::relative(&self.canonical_root, entry.path())?;
1157                let value = self.file_value_with_links(&self.canonical_root, &file, visiting)?;
1158                contents.insert(
1159                    file.strip_prefix(&relative).unwrap_or(&file).to_owned(),
1160                    value,
1161                );
1162            }
1163            visiting.remove(&resolved);
1164            return Ok(json!({"link":target, "directory":contents}));
1165        }
1166        if !metadata.is_file() {
1167            bail!("input is not a regular file: {path}");
1168        }
1169        // Only the executable bit, which is all git records: other permission
1170        // bits follow the checkout's umask and would keep machines apart.
1171        let mode = crate::store::mode(&metadata) & 0o111 != 0;
1172        Ok(json!({"content":self.digest(path, &absolute, &metadata)?, "mode":mode}))
1173    }
1174}
1175
1176/// Reads and parses a pnpm lockfile, `None` when there is none. One qk cannot
1177/// read is reported, and kept as unreadable so tasks key its whole content.
1178fn parse_lockfile(path: &Path) -> Option<Arc<Installed>> {
1179    let text = std::fs::read_to_string(path).ok()?;
1180    let lockfile = match Lockfile::parse(&text) {
1181        Ok(lockfile) => Some(lockfile),
1182        Err(error) => {
1183            qk_executor::status!("qk: pnpm-lock.yaml: keying tasks by the whole file ({error:#})");
1184            None
1185        }
1186    };
1187    Some(Arc::new(Installed {
1188        content: blake3::hash(text.as_bytes()).to_hex().to_string(),
1189        lockfile,
1190        digests: Mutex::default(),
1191    }))
1192}
1193
1194fn load_digests(root: &Path) -> HashMap<String, (Stamp, String)> {
1195    #[derive(serde::Deserialize)]
1196    struct Saved {
1197        version: u32,
1198        entries: HashMap<String, (Stamp, String)>,
1199    }
1200    std::fs::read(digests_path(root))
1201        .ok()
1202        .and_then(|bytes| serde_json::from_slice::<Saved>(&bytes).ok())
1203        .filter(|saved| saved.version == 1)
1204        .map(|saved| saved.entries)
1205        .unwrap_or_default()
1206}
1207
1208/// Apply the same source policy to startup and refreshed file membership.
1209/// Remove declared artifacts and cache storage from a refreshed source listing.
1210fn exclude_artifacts(files: &mut BTreeSet<String>, outputs: &[Outputs], cache: Option<&Path>) {
1211    let mut generated = BTreeSet::new();
1212    for outputs in outputs {
1213        for anchor in outputs.anchors() {
1214            generated.extend(
1215                under(files, anchor)
1216                    .filter(|path| outputs.matches(path))
1217                    .cloned(),
1218            );
1219        }
1220    }
1221    files.retain(|path| {
1222        !generated.contains(path) && cache.is_none_or(|cache| !Path::new(path).starts_with(cache))
1223    });
1224}
1225
1226/// Files equal to `prefix` or below it, using the sorted order of the set.
1227impl Snapshot {
1228    /// The project whose root most specifically contains `path`, as Nx assigns
1229    /// files to projects.
1230    fn owner(&self, path: &str) -> Option<&str> {
1231        let mut path = path;
1232        loop {
1233            if let Some(project) = self.roots.get(path) {
1234                return Some(project);
1235            }
1236            match path.rfind('/') {
1237                Some(slash) => path = &path[..slash],
1238                None if path != "." => path = ".",
1239                None => return None,
1240            }
1241        }
1242    }
1243}
1244
1245fn under<'a>(files: &'a BTreeSet<String>, prefix: &'a str) -> impl Iterator<Item = &'a String> {
1246    files
1247        .range::<str, _>((
1248            std::ops::Bound::Included(prefix),
1249            std::ops::Bound::Unbounded,
1250        ))
1251        .take_while(move |path| path.starts_with(prefix))
1252        .filter(move |path| path.len() == prefix.len() || path.as_bytes()[prefix.len()] == b'/')
1253}
1254
1255/// Compiled root ignore rules used by input discovery and project watching.
1256pub struct SourceIgnore(ignore::gitignore::Gitignore);
1257
1258impl SourceIgnore {
1259    /// Root ignore rules shared by caching and watch, including tracked files.
1260    pub fn new(root: &Path) -> Result<Self> {
1261        let mut builder = ignore::gitignore::GitignoreBuilder::new(root);
1262        for name in [".gitignore", ".nxignore"] {
1263            let path = root.join(name);
1264            if path.is_file()
1265                && let Some(error) = builder.add(path)
1266            {
1267                return Err(error.into());
1268            }
1269        }
1270        Ok(Self(builder.build()?))
1271    }
1272
1273    fn matches_directory(&self, path: &str) -> bool {
1274        self.matches(path) || self.0.matched(path, true).is_ignore()
1275    }
1276
1277    /// Whether a workspace-relative file or its parent is ignored.
1278    pub fn matches(&self, path: &str) -> bool {
1279        // A file whitelist cannot reinclude it beneath an excluded directory.
1280        Path::new(path)
1281            .ancestors()
1282            .skip(1)
1283            .take_while(|parent| !parent.as_os_str().is_empty())
1284            .any(|parent| self.0.matched(parent, true).is_ignore())
1285            || self.0.matched(path, false).is_ignore()
1286    }
1287}
1288
1289/// Source files visible to Nx, with runner state and root ignore rules removed.
1290pub fn source_files(root: &Path) -> Result<BTreeSet<String>> {
1291    let lines =
1292        |output: std::io::Result<std::process::Output>| -> Option<Result<BTreeSet<String>>> {
1293            let output = output.ok().filter(|output| output.status.success())?;
1294            Some(
1295                output
1296                    .stdout
1297                    .split(|byte| *byte == 0)
1298                    .filter(|path| !path.is_empty())
1299                    .map(|path| {
1300                        String::from_utf8(path.to_vec()).context("input paths must be UTF-8")
1301                    })
1302                    .collect(),
1303            )
1304        };
1305    // Tracked files deleted from the working tree are listed as cached; git
1306    // names them in a second listing, which is cheaper than checking each file.
1307    // Skip-worktree entries are listed whether or not they are on disk and never
1308    // as deleted, so those few are checked; `-v` tags them `S`.
1309    let (listed, deleted) = if root.join(".nxignore").is_file() {
1310        // Nx negations can reinclude Git-ignored files, so this policy needs
1311        // the walker regardless of what Git lists. Avoid launching Git here.
1312        (None, None)
1313    } else {
1314        std::thread::scope(|scope| {
1315            let deleted =
1316                scope.spawn(|| paths::git(root, &["ls-files", "--deleted", "-z", "--", "."]));
1317            let listed = paths::git(
1318                root,
1319                &[
1320                    "ls-files",
1321                    "-v",
1322                    "--cached",
1323                    "--others",
1324                    "--exclude-standard",
1325                    "-z",
1326                    "--",
1327                    ".",
1328                ],
1329            );
1330            (
1331                lines(listed),
1332                lines(deleted.join().expect("git listing thread panicked")),
1333            )
1334        })
1335    };
1336    let candidates = match (listed, deleted) {
1337        (Some(listed), Some(deleted)) => {
1338            let deleted = deleted?;
1339            let mut files = BTreeSet::new();
1340            for entry in listed? {
1341                let Some((tag, path)) = entry.split_once(' ') else {
1342                    bail!("unexpected git ls-files entry {entry:?}");
1343                };
1344                let absent =
1345                    matches!(tag, "S" | "s") && std::fs::symlink_metadata(root.join(path)).is_err();
1346                if !absent && !deleted.contains(path) {
1347                    files.insert(path.to_owned());
1348                }
1349            }
1350            files
1351        }
1352        _ => {
1353            let mut files = BTreeSet::new();
1354            for entry in ignore::WalkBuilder::new(root)
1355                .hidden(false)
1356                .parents(false)
1357                .git_global(false)
1358                .require_git(false)
1359                .ignore(false)
1360                .add_custom_ignore_filename(".nxignore")
1361                .follow_links(false)
1362                .filter_entry(|entry| {
1363                    !matches!(
1364                        entry.file_name().to_str(),
1365                        Some(".git" | ".qk" | "node_modules")
1366                    )
1367                })
1368                .build()
1369            {
1370                let entry = entry?;
1371                if entry.file_type().is_some_and(|kind| !kind.is_dir()) {
1372                    files.insert(paths::relative(root, entry.path())?);
1373                }
1374            }
1375            files
1376        }
1377    };
1378    let ignore = SourceIgnore::new(root)?;
1379    Ok(candidates
1380        .into_iter()
1381        .filter(|path| {
1382            !ignore.matches(path)
1383                && !path
1384                    .split('/')
1385                    .any(|part| matches!(part, ".git" | ".qk" | "node_modules"))
1386        })
1387        .collect())
1388}
1389
1390/// The text of `path` as a `json` input keys it: only `fields` when given,
1391/// without `exclude`. A `.yaml` or `.yml` file is read as YAML, and any other
1392/// as JSON or JSONC. `None` when it cannot be read so.
1393pub(crate) fn json_projection(path: &str, text: &str, fields: &JsonFields) -> Option<Value> {
1394    let mut value: Value = if path.ends_with(".yaml") || path.ends_with(".yml") {
1395        serde_yaml_ng::from_str(text).ok()?
1396    } else {
1397        jsonc_parser::parse_to_serde_value(text, &Default::default()).ok()?
1398    };
1399    if let Some(fields) = &fields.fields {
1400        let mut kept = json!({});
1401        for field in fields {
1402            if let Some(found) = json_path(&value, field) {
1403                set_json_path(&mut kept, field, found.clone());
1404            }
1405        }
1406        value = kept;
1407    }
1408    for field in &fields.exclude {
1409        remove_json_path(&mut value, field);
1410    }
1411    Some(value)
1412}
1413
1414fn json_path<'v>(value: &'v Value, path: &str) -> Option<&'v Value> {
1415    path.split('.')
1416        .try_fold(value, |value, part| value.get(part))
1417}
1418
1419fn set_json_path(target: &mut Value, path: &str, value: Value) {
1420    let mut parts = path.split('.').peekable();
1421    let mut current = target;
1422    while let Some(part) = parts.next() {
1423        let Value::Object(object) = current else {
1424            return;
1425        };
1426        if parts.peek().is_none() {
1427            object.insert(part.to_owned(), value);
1428            return;
1429        }
1430        current = object.entry(part).or_insert_with(|| json!({}));
1431    }
1432}
1433
1434fn remove_json_path(target: &mut Value, path: &str) {
1435    let (parent, last) = match path.rsplit_once('.') {
1436        Some((parent, last)) => (Some(parent), last),
1437        None => (None, path),
1438    };
1439    let parent = match parent {
1440        Some(parent) => parent
1441            .split('.')
1442            .try_fold(&mut *target, |value, part| value.get_mut(part)),
1443        None => Some(target),
1444    };
1445    if let Some(Value::Object(object)) = parent {
1446        object.remove(last);
1447    }
1448}
1449
1450struct FilePattern {
1451    matcher: Arc<Pattern>,
1452    prefix: String,
1453    excluded: bool,
1454    /// The project a project fileset selects the files of.
1455    owner: Option<String>,
1456}
1457
1458/// A `json` glob, kept to select dependency outputs once they are written.
1459struct JsonGlob {
1460    matcher: Arc<Pattern>,
1461    prefix: String,
1462    /// The project whose files it selects, or `None` for the workspace's.
1463    owner: Option<String>,
1464    fields: JsonFields,
1465}
1466
1467#[derive(Default)]
1468struct FileSelection {
1469    patterns: Vec<FilePattern>,
1470    included: BTreeSet<String>,
1471    excluded: BTreeSet<String>,
1472}
1473
1474#[derive(PartialEq, Eq, PartialOrd, Ord)]
1475enum FileScope {
1476    Workspace,
1477    Project(String),
1478}
1479
1480struct Resolver<'a> {
1481    workspace: &'a Workspace,
1482    snapshot: &'a Snapshot,
1483    candidates: &'a BTreeSet<String>,
1484    selected: BTreeSet<String>,
1485    scopes: BTreeMap<FileScope, FileSelection>,
1486    values: BTreeMap<String, Value>,
1487    json_fields: BTreeMap<String, JsonFields>,
1488    json_globs: Vec<JsonGlob>,
1489    named_stack: Vec<(String, String)>,
1490    /// Dependency named inputs already expanded for `^` inputs.
1491    expanded: BTreeSet<(String, String)>,
1492    external: BTreeSet<String>,
1493    /// `includeIgnored` globs, resolved, by the project that reads them and
1494    /// whether they came with `dependencies: true`: each is one group, whose
1495    /// negations filter all of its positives.
1496    ignored: BTreeMap<(String, bool), Vec<String>>,
1497    external_declared: bool,
1498    /// Every project whose inputs were read, as Nx hashes each one's
1499    /// configuration.
1500    projects: BTreeSet<String>,
1501    /// `None` resolves which inputs a task has without evaluating env or
1502    /// runtime inputs.
1503    prepared: Option<&'a PreparedTask>,
1504    cancelled: &'a AtomicBool,
1505}
1506
1507impl<'a> Resolver<'a> {
1508    fn new(
1509        snapshot: &'a Snapshot,
1510        workspace: &'a Workspace,
1511        prepared: Option<&'a PreparedTask>,
1512        cancelled: &'a AtomicBool,
1513        candidates: &'a BTreeSet<String>,
1514    ) -> Self {
1515        Self {
1516            workspace,
1517            snapshot,
1518            candidates,
1519            selected: BTreeSet::new(),
1520            scopes: BTreeMap::new(),
1521            values: BTreeMap::new(),
1522            json_fields: BTreeMap::new(),
1523            json_globs: Vec::new(),
1524            named_stack: Vec::new(),
1525            expanded: BTreeSet::new(),
1526            external: BTreeSet::new(),
1527            ignored: BTreeMap::new(),
1528            external_declared: false,
1529            projects: BTreeSet::new(),
1530            prepared,
1531            cancelled,
1532        }
1533    }
1534
1535    fn task_inputs(&mut self, task: &Task) -> Result<()> {
1536        self.projects.insert(task.project.clone());
1537        for input in declared_inputs(task) {
1538            self.input(&task.project, &input)?;
1539        }
1540        // As in Nx, a continuous task serving this one counts its own inputs
1541        // here.
1542        let snapshot = self.snapshot;
1543        for (project, inputs) in snapshot.servers.get(&task.id).into_iter().flatten() {
1544            for input in inputs {
1545                self.input(project, input)
1546                    .with_context(|| format!("inputs of {project}, which serves this task"))?;
1547            }
1548        }
1549        Ok(())
1550    }
1551
1552    fn input(&mut self, project: &str, input: &Value) -> Result<()> {
1553        self.projects.insert(project.to_owned());
1554        // Nx 24's `always` keeps an input in a hash taken from an Ultracache
1555        // recording. qk hashes no recordings, so the input reads as without it.
1556        if let Value::Object(object) = input
1557            && let Some(always) = object.get("always")
1558        {
1559            // As in Nx, `always` keeps an input on purpose, so a project
1560            // pattern it selects nothing with is a mistake.
1561            if always.as_bool().context("input always must be boolean")?
1562                && let Some(Value::String(name)) = object.get("input")
1563                && let Some(projects) = object.get("projects")
1564            {
1565                let patterns: Vec<String> = match projects {
1566                    Value::String(pattern) => vec![pattern.clone()],
1567                    other => serde_json::from_value(other.clone())
1568                        .context("input projects must be a string or an array")?,
1569                };
1570                for pattern in patterns.iter().filter(|pattern| {
1571                    !pattern.starts_with('!')
1572                        && !matches!(pattern.as_str(), "self" | "dependencies")
1573                }) {
1574                    if qk_graph::select_projects(
1575                        &self.workspace.projects,
1576                        std::slice::from_ref(pattern),
1577                        &[],
1578                    )?
1579                    .is_empty()
1580                    {
1581                        bail!(
1582                            "the input {{\"input\": \"{name}\", \"projects\"}} with \"always\": true selects \"{pattern}\", which matches no project"
1583                        );
1584                    }
1585                }
1586            }
1587            let mut object = object.clone();
1588            object.remove("always");
1589            return self.input(project, &Value::Object(object));
1590        }
1591        match input {
1592            // As in Nx, `^{projectRoot}/…` and `^{workspaceRoot}/…` are a
1593            // fileset of every project the project depends on, directly or
1594            // not, and `^name` is `name` of each of them.
1595            Value::String(name)
1596                if name.starts_with("^{projectRoot}") || name.starts_with("^{workspaceRoot}") =>
1597            {
1598                self.dependency_fileset(project, &name[1..])?;
1599            }
1600            Value::String(name) if name.starts_with('^') => {
1601                self.dependencies_named(project, &name[1..])?;
1602            }
1603            // The object spellings of named inputs, as Nx reads them.
1604            Value::Object(object)
1605                if object.contains_key("input") && !object.contains_key("fileset") =>
1606            {
1607                let name = object["input"]
1608                    .as_str()
1609                    .context("input must name a named input")?;
1610                let projects = object.get("projects");
1611                let dependencies = object.get("dependencies") == Some(&json!(true))
1612                    || projects == Some(&json!("dependencies"));
1613                let listed = projects.filter(|projects| {
1614                    **projects != json!("self") && **projects != json!("dependencies")
1615                });
1616                if (dependencies || listed.is_some()) && !self.named_stack.is_empty() {
1617                    bail!("named inputs can only refer to named inputs of their own project");
1618                }
1619                if let Some(listed) = listed {
1620                    let patterns: Vec<String> = match listed {
1621                        Value::String(pattern) => vec![pattern.clone()],
1622                        other => serde_json::from_value(other.clone())
1623                            .context("input projects must be a string or an array")?,
1624                    };
1625                    // Nx's native hasher reads these patterns, not the
1626                    // `findMatchingProjects` the rest of Nx uses.
1627                    for selected in qk_config::find_matching_projects(
1628                        &patterns,
1629                        &self.workspace.projects,
1630                        qk_config::Reader::Native,
1631                    ) {
1632                        // As in Nx 24, `dependencies: true` beside `projects`
1633                        // is each selected project's `^name`, not its own.
1634                        if dependencies {
1635                            self.dependencies_named(&selected, name)?;
1636                        } else if self.expanded.insert((selected.clone(), name.to_owned())) {
1637                            self.named(&selected, name)?;
1638                        }
1639                    }
1640                } else if dependencies {
1641                    self.dependencies_named(project, name)?;
1642                } else {
1643                    self.named(project, name)?;
1644                }
1645            }
1646            Value::Object(object) if object.contains_key("fileset") => {
1647                if let Some(key) = object.keys().find(|key| {
1648                    !matches!(key.as_str(), "fileset" | "dependencies" | "includeIgnored")
1649                }) {
1650                    bail!("unsupported fileset input field {key:?}");
1651                }
1652                let flag = |name: &str| {
1653                    object
1654                        .get(name)
1655                        .map(|value| {
1656                            value
1657                                .as_bool()
1658                                .with_context(|| format!("{name} must be boolean"))
1659                        })
1660                        .transpose()
1661                        .map(Option::unwrap_or_default)
1662                };
1663                let (dependencies, include_ignored) =
1664                    (flag("dependencies")?, flag("includeIgnored")?);
1665                let pattern = object["fileset"]
1666                    .as_str()
1667                    .context("fileset input must be a glob")?
1668                    .to_owned();
1669                validate_fileset(&pattern)?;
1670                match (dependencies, include_ignored) {
1671                    (false, false) => self.fileset(project, &pattern)?,
1672                    (true, false) => self.dependency_fileset(project, &pattern)?,
1673                    (false, true) => self.ignored_fileset(project, &pattern, false),
1674                    (true, true) => {
1675                        if !self.named_stack.is_empty() {
1676                            bail!(
1677                                "named inputs can only refer to named inputs of their own project"
1678                            );
1679                        }
1680                        for dependency in self.dependency_closure(project) {
1681                            self.ignored_fileset(&dependency, &pattern, true);
1682                        }
1683                    }
1684                }
1685            }
1686            Value::Object(object)
1687                if object.len() == 1 && object.contains_key("workingDirectory") =>
1688            {
1689                let mode = object["workingDirectory"].as_str().unwrap_or_default();
1690                let directory = std::env::current_dir()?;
1691                let value = match mode {
1692                    "absolute" => directory.to_string_lossy().into_owned(),
1693                    "relative" => {
1694                        let root = self.workspace.root.canonicalize()?;
1695                        let directory = directory.canonicalize()?;
1696                        paths::relative(&root, &directory)
1697                            .unwrap_or_else(|_| directory.to_string_lossy().into_owned())
1698                    }
1699                    _ => bail!("workingDirectory must be \"relative\" or \"absolute\""),
1700                };
1701                self.values
1702                    .insert(format!("workingDirectory:{mode}"), json!(value));
1703            }
1704            Value::Object(object) if object.contains_key("json") => {
1705                self.json(project, object)?;
1706            }
1707            // As in Nx, a string names a named input when there is one, and is
1708            // a fileset otherwise.
1709            Value::String(name) if self.has_named(project, name) => self.named(project, name)?,
1710            Value::String(pattern) => {
1711                validate_fileset(pattern)?;
1712                self.fileset(project, pattern)?
1713            }
1714            Value::Object(object) if object.len() == 1 && object.contains_key("env") => {
1715                let name = object["env"]
1716                    .as_str()
1717                    .context("env input must name a variable")?;
1718                let Some(prepared) = self.prepared else {
1719                    self.values.insert(format!("env:{name}"), Value::Null);
1720                    return Ok(());
1721                };
1722                let value = prepared
1723                    .env
1724                    .get(std::ffi::OsStr::new(name))
1725                    .map(|value| {
1726                        value
1727                            .to_str()
1728                            .map(str::to_owned)
1729                            .context("declared env input must be UTF-8")
1730                    })
1731                    .transpose()?;
1732                self.values.insert(format!("env:{name}"), json!(value));
1733            }
1734            Value::Object(object) if object.len() == 1 && object.contains_key("runtime") => {
1735                let command = object["runtime"]
1736                    .as_str()
1737                    .context("runtime input must be a command")?;
1738                let Some(prepared) = self.prepared else {
1739                    self.values
1740                        .insert(format!("runtime:{command}"), Value::Null);
1741                    return Ok(());
1742                };
1743                let memo = RuntimeKey {
1744                    command: command.into(),
1745                    environment: prepared.runtime_env.clone(),
1746                };
1747                let slot = self
1748                    .snapshot
1749                    .runtime
1750                    .lock()
1751                    .unwrap()
1752                    .entry(memo)
1753                    .or_default()
1754                    .clone();
1755                let mut saved = slot.lock().unwrap();
1756                if let Some(value) = saved.as_ref() {
1757                    self.values
1758                        .insert(format!("runtime:{command}"), value.clone());
1759                    return Ok(());
1760                }
1761                let _profile = crate::profile::span(command, "runtime");
1762                let mut prepared = prepared.clone();
1763                prepared.env = prepared.runtime_env.clone();
1764                prepared.execution.clear();
1765                prepared.node_path = None;
1766                prepared.commands = vec![command.into()];
1767                prepared.cwd = self.workspace.root.clone();
1768                prepared.parallel = false;
1769                // Its output is hashed, so it must not depend on a terminal.
1770                prepared.pseudo_terminal = false;
1771                let log = tempfile::NamedTempFile::new()?;
1772                let capture = Capture::new(Some(log.as_file().try_clone()?), Display::Hidden);
1773                if execute_captured(&prepared, self.cancelled, Some(&capture))? != Outcome::Success
1774                {
1775                    bail!("runtime input did not succeed");
1776                }
1777                let mut stdout = blake3::Hasher::new();
1778                let mut stderr = blake3::Hasher::new();
1779                read_capture(File::open(log.path())?, |error, bytes| {
1780                    if error {
1781                        stderr.update(bytes);
1782                    } else {
1783                        stdout.update(bytes);
1784                    }
1785                    Ok(())
1786                })?;
1787                let value = json!([
1788                    stdout.finalize().to_hex().to_string(),
1789                    stderr.finalize().to_hex().to_string()
1790                ]);
1791                *saved = Some(value.clone());
1792                self.values.insert(format!("runtime:{command}"), value);
1793            }
1794            Value::Object(object) if object.contains_key("dependentTasksOutputFiles") => {
1795                if object
1796                    .keys()
1797                    .any(|key| !matches!(key.as_str(), "dependentTasksOutputFiles" | "transitive"))
1798                {
1799                    bail!("unsupported output input field");
1800                }
1801                let pattern = object["dependentTasksOutputFiles"]
1802                    .as_str()
1803                    .context("dependentTasksOutputFiles must be a glob")?;
1804                self.snapshot.pattern(pattern, false)?;
1805                let transitive = object
1806                    .get("transitive")
1807                    .map(|value| value.as_bool().context("transitive must be boolean"))
1808                    .transpose()?
1809                    .unwrap_or(false);
1810                // Resolved before execution too, so inspection can display the
1811                // selection without reading generated files. dependency_keys
1812                // hashes these files after the dependencies finish.
1813                let value = self
1814                    .values
1815                    .entry(format!("dependentTasksOutputFiles:{pattern}"))
1816                    .or_insert(json!(false));
1817                if transitive {
1818                    *value = json!(true);
1819                }
1820            }
1821            Value::Object(object)
1822                if object.len() == 1 && object.contains_key("externalDependencies") =>
1823            {
1824                let names: Vec<String> =
1825                    serde_json::from_value(object["externalDependencies"].clone())?;
1826                // As in Nx, a workspace project is no external dependency.
1827                if let Some(name) = names
1828                    .iter()
1829                    .find(|name| self.workspace.projects.contains_key(*name))
1830                {
1831                    if self.snapshot.projects.dependencies[project]
1832                        .iter()
1833                        .any(|edge| edge.target == *name)
1834                    {
1835                        bail!(
1836                            "the externalDependency {name:?} of {project} is not an external node and is already a dependency; remove it from the externalDependencies inputs"
1837                        );
1838                    }
1839                    bail!(
1840                        "the externalDependency {name:?} of {project} is not an external node; if it is a dependency, add it to the project's implicitDependencies"
1841                    );
1842                }
1843                self.external.extend(names);
1844                self.external_declared = true;
1845            }
1846            _ => bail!("unsupported task input declaration"),
1847        }
1848        Ok(())
1849    }
1850
1851    fn fileset(&mut self, project: &str, pattern: &str) -> Result<()> {
1852        self.projects.insert(project.to_owned());
1853        let (exclude, pattern) = pattern
1854            .strip_prefix('!')
1855            .map(|pattern| (true, pattern))
1856            .unwrap_or((false, pattern));
1857        // Nx hashes workspace files and each project's files in separate
1858        // scopes, a project's being only the files it owns: those of a project
1859        // nested in its root are that project's. A fileset is the project's
1860        // when it starts from `{projectRoot}/`, and the workspace's otherwise,
1861        // where only one starting from `{workspaceRoot}/` selects anything.
1862        let (scope, owner) = if pattern.starts_with("{projectRoot}/") {
1863            (
1864                FileScope::Project(project.to_owned()),
1865                Some(project.to_owned()),
1866            )
1867        } else if pattern.starts_with("{workspaceRoot}/") {
1868            (FileScope::Workspace, None)
1869        } else {
1870            return Ok(());
1871        };
1872        let pattern = paths::expand_glob(self.workspace, project, pattern)?;
1873        let matcher = self.snapshot.fileset_pattern(&pattern, exclude)?;
1874        let (prefix, _) = crate::ignored::partition(pattern.trim_end_matches('/'));
1875        let candidates: Box<dyn Iterator<Item = &String>> = if prefix.is_empty() {
1876            Box::new(self.candidates.iter())
1877        } else {
1878            Box::new(under(self.candidates, &prefix))
1879        };
1880        let snapshot = self.snapshot;
1881        let selection = self.scopes.entry(scope).or_default();
1882        let selected = if exclude {
1883            &mut selection.excluded
1884        } else {
1885            &mut selection.included
1886        };
1887        selected.extend(
1888            candidates
1889                .filter(|file| matcher.is_match(file))
1890                .filter(|file| owner.is_none() || snapshot.owner(file) == owner.as_deref())
1891                .cloned(),
1892        );
1893        selection.patterns.push(FilePattern {
1894            matcher,
1895            prefix,
1896            excluded: exclude,
1897            owner,
1898        });
1899        Ok(())
1900    }
1901
1902    /// An `includeIgnored` glob of `project`, with its tokens resolved as
1903    /// Nx's `resolve_files_glob` resolves them, to read from disk later.
1904    fn ignored_fileset(&mut self, project: &str, pattern: &str, dependencies: bool) {
1905        // The root and name go in escaped, as for every fileset; Nx inserts
1906        // them as they are.
1907        let root = &self.workspace.projects[project].root;
1908        let resolved = if root == "." {
1909            pattern.replace("{projectRoot}/", "")
1910        } else {
1911            pattern.replace("{projectRoot}", &crate::glob::escape(root))
1912        }
1913        .replace("{projectName}", &crate::glob::escape(project));
1914        let resolved = match resolved.strip_prefix("!{workspaceRoot}/") {
1915            Some(rest) => format!("!{rest}"),
1916            None => resolved
1917                .strip_prefix("{workspaceRoot}/")
1918                .map(str::to_owned)
1919                .unwrap_or(resolved),
1920        };
1921        self.ignored
1922            .entry((project.to_owned(), dependencies))
1923            .or_default()
1924            .push(resolved);
1925    }
1926
1927    /// A fileset of every project `project` depends on, directly or not.
1928    fn dependency_fileset(&mut self, project: &str, pattern: &str) -> Result<()> {
1929        if !self.named_stack.is_empty() {
1930            bail!("named inputs can only refer to named inputs of their own project");
1931        }
1932        for dependency in self.dependency_closure(project) {
1933            self.fileset(&dependency, pattern)?;
1934        }
1935        Ok(())
1936    }
1937
1938    /// Whether `name` names one of `project`'s named inputs.
1939    fn has_named(&self, project: &str, name: &str) -> bool {
1940        name == "default"
1941            || self.workspace.projects[project]
1942                .named_inputs
1943                .contains_key(name)
1944    }
1945
1946    /// Every project `project` depends on, directly or not.
1947    fn dependency_closure(&self, project: &str) -> BTreeSet<String> {
1948        let mut closure = BTreeSet::new();
1949        let mut pending = vec![project.to_owned()];
1950        while let Some(current) = pending.pop() {
1951            for edge in &self.snapshot.projects.dependencies[&current] {
1952                if edge.target != project && closure.insert(edge.target.clone()) {
1953                    pending.push(edge.target.clone());
1954                }
1955            }
1956        }
1957        closure
1958    }
1959
1960    /// As in Nx, `^name` is `name` of every project the project depends on.
1961    fn dependencies_named(&mut self, project: &str, name: &str) -> Result<()> {
1962        for dependency in self.dependency_closure(project) {
1963            if self.expanded.insert((dependency.clone(), name.to_owned())) {
1964                self.named(&dependency, name)?;
1965            }
1966        }
1967        Ok(())
1968    }
1969
1970    /// A JSON input: the fields of a JSON file, rather than all of it, or of
1971    /// each file a glob selects. `fields` keeps only the named dotted paths;
1972    /// `excludeFields` removes them.
1973    fn json(&mut self, project: &str, object: &serde_json::Map<String, Value>) -> Result<()> {
1974        for key in object.keys() {
1975            if !matches!(key.as_str(), "json" | "fields" | "excludeFields") {
1976                bail!("unsupported json input field {key:?}");
1977            }
1978        }
1979        let declared = object["json"]
1980            .as_str()
1981            .context("json input must name a file")?;
1982        validate_fileset(declared)?;
1983        let path = paths::expand_glob(self.workspace, project, declared)?;
1984        let list = |name: &str| -> Result<Option<Vec<String>>> {
1985            object
1986                .get(name)
1987                .map(|value| {
1988                    serde_json::from_value(value.clone())
1989                        .with_context(|| format!("json input {name} must be an array of strings"))
1990                })
1991                .transpose()
1992        };
1993        let fields = JsonFields {
1994            fields: list("fields")?,
1995            exclude: list("excludeFields")?.unwrap_or_default(),
1996        };
1997        if crate::glob::names_a_path(&path) {
1998            let path = crate::glob::literal_path(&path);
1999            paths::validate_path(&path)?;
2000            return self.json_file(path, &fields);
2001        }
2002        // As in Nx, a glob selects the files a fileset from the same root
2003        // would: the project's own, or the workspace's.
2004        let owner = if declared.starts_with("{projectRoot}") {
2005            Some(project)
2006        } else if declared.starts_with("{workspaceRoot}/") {
2007            None
2008        } else {
2009            return Ok(());
2010        };
2011        let matcher = self.snapshot.pattern(&path, false)?;
2012        let snapshot = self.snapshot;
2013        let matched: Vec<String> = self
2014            .candidates
2015            .iter()
2016            .filter(|file| matcher.is_match(file))
2017            .filter(|file| owner.is_none() || snapshot.owner(file) == owner)
2018            .cloned()
2019            .collect();
2020        for file in matched {
2021            self.json_file(file, &fields)?;
2022        }
2023        self.json_globs.push(JsonGlob {
2024            matcher,
2025            prefix: crate::ignored::partition(&path).0,
2026            owner: owner.map(str::to_owned),
2027            fields,
2028        });
2029        Ok(())
2030    }
2031
2032    /// One file a `json` input selects, keyed by its fields.
2033    fn json_file(&mut self, path: String, fields: &JsonFields) -> Result<()> {
2034        let value = match std::fs::read_to_string(self.workspace.root.join(&path)) {
2035            Ok(text) => match json_projection(&path, &text, fields) {
2036                Some(value) => value,
2037                // As in Nx, a file it cannot read is keyed by its content,
2038                // without the field filters. Nx reads no YAML, so it keys a
2039                // YAML file whole where qk keys its fields.
2040                None => {
2041                    self.selected.insert(path);
2042                    return Ok(());
2043                }
2044            },
2045            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Value::Null,
2046            Err(error) => return Err(error.into()),
2047        };
2048        self.values.insert(format!("json:{path}"), value);
2049        self.json_fields.insert(path, fields.clone());
2050        Ok(())
2051    }
2052
2053    fn named(&mut self, project: &str, name: &str) -> Result<()> {
2054        let identity = (project.to_owned(), name.to_owned());
2055        if self.named_stack.contains(&identity) {
2056            bail!("named input cycle at {project}:{name}");
2057        }
2058        self.named_stack.push(identity);
2059        let inputs = self.workspace.projects[project]
2060            .named_inputs
2061            .get(name)
2062            .cloned()
2063            .or_else(|| (name == "default").then(|| vec![json!("{projectRoot}/**/*")]))
2064            .with_context(|| format!("unknown named input {name:?}"))?;
2065        for input in &inputs {
2066            self.input(project, input)?;
2067        }
2068        self.named_stack.pop();
2069        Ok(())
2070    }
2071}
2072
2073/// As Nx's `validate_file_set`: a fileset starts from `{projectRoot}` or
2074/// `{workspaceRoot}`, after its `!`.
2075fn validate_fileset(fileset: &str) -> Result<()> {
2076    let body = fileset.strip_prefix('!').unwrap_or(fileset);
2077    if !body.starts_with("{projectRoot}") && !body.starts_with("{workspaceRoot}") {
2078        bail!(
2079            "{fileset:?} is an invalid fileset: filesets have to start with either {{workspaceRoot}} or {{projectRoot}}, and a named input must be defined"
2080        );
2081    }
2082    Ok(())
2083}
2084
2085/// A task's declared inputs, or Nx's default when it declares none.
2086fn declared_inputs(task: &Task) -> Vec<Value> {
2087    task.definition
2088        .inputs
2089        .clone()
2090        .unwrap_or_else(|| vec![json!("default"), json!("^default")])
2091}
2092
2093/// The continuous tasks serving a task, whose inputs count as its own, as Nx
2094/// hashes them: its continuous dependencies, theirs in turn, and so on, each
2095/// by its project and declared inputs. A dependency declared with
2096/// `inputs: false` is not followed, though a server it leads to still counts
2097/// when another way reaches it.
2098fn servers(graph: &TaskGraph, id: &str) -> Vec<(String, Vec<Value>)> {
2099    let mut servers = Vec::new();
2100    let mut visited = BTreeSet::from([id]);
2101    let mut pending = std::collections::VecDeque::from([id]);
2102    while let Some(current) = pending.pop_front() {
2103        let task = &graph.tasks[current];
2104        for dependency in &task.dependencies {
2105            let Some(server) = graph.tasks.get(dependency) else {
2106                continue;
2107            };
2108            if server.definition.continuous != Some(true)
2109                || !task.edge(dependency).inputs
2110                || !visited.insert(dependency)
2111            {
2112                continue;
2113            }
2114            servers.push((server.project.clone(), declared_inputs(server)));
2115            pending.push_back(dependency);
2116        }
2117    }
2118    servers
2119}
2120
2121pub fn resolve(
2122    snapshot: &Snapshot,
2123    workspace: &Workspace,
2124    task: &Task,
2125    prepared: Option<&PreparedTask>,
2126    cancelled: &AtomicBool,
2127) -> Result<Resolved> {
2128    resolve_candidates(
2129        snapshot,
2130        workspace,
2131        task,
2132        prepared,
2133        cancelled,
2134        &snapshot.files,
2135        &snapshot.source_ignore,
2136    )
2137}
2138
2139fn resolve_candidates(
2140    snapshot: &Snapshot,
2141    workspace: &Workspace,
2142    task: &Task,
2143    prepared: Option<&PreparedTask>,
2144    cancelled: &AtomicBool,
2145    candidates: &BTreeSet<String>,
2146    source_ignore: &SourceIgnore,
2147) -> Result<Resolved> {
2148    let mut resolver = Resolver::new(snapshot, workspace, prepared, cancelled, candidates);
2149    resolver.task_inputs(task)?;
2150    // Dependency outputs may also be declared sources, for filesets and `json`
2151    // globs alike. Downstream and unrelated
2152    // outputs remain artifacts, so producing them cannot invalidate an upstream task.
2153    let mut upstream = BTreeSet::new();
2154    let mut pending: Vec<_> = task.dependencies.iter().cloned().collect();
2155    while let Some(id) = pending.pop() {
2156        if upstream.insert(id.clone())
2157            && let Some(dependencies) = snapshot.task_dependencies.get(&id)
2158        {
2159            pending.extend(dependencies.iter().cloned());
2160        }
2161    }
2162    let own_outputs = Outputs::new(workspace, task)
2163        .ok()
2164        .filter(Outputs::is_explicit);
2165    let mut producers = BTreeSet::new();
2166    for (producer, declared) in &snapshot.generated_tasks {
2167        if producer.id == task.id || !upstream.contains(&producer.id) {
2168            continue;
2169        }
2170        let overlaps = |a: &str, b: &str| {
2171            a.is_empty()
2172                || a == b
2173                || a.strip_prefix(b).is_some_and(|rest| rest.starts_with('/'))
2174                || b.strip_prefix(a).is_some_and(|rest| rest.starts_with('/'))
2175        };
2176        let relevant = resolver
2177            .scopes
2178            .values()
2179            .flat_map(|scope| &scope.patterns)
2180            .filter(|pattern| !pattern.excluded)
2181            .map(|pattern| &pattern.prefix)
2182            .chain(resolver.json_globs.iter().map(|glob| &glob.prefix))
2183            .any(|prefix| {
2184                declared.anchors().any(|anchor| {
2185                    overlaps(prefix, anchor)
2186                        && (!source_ignore.matches_directory(anchor)
2187                            || !workspace.root.join(anchor).is_dir())
2188                })
2189            });
2190        if !relevant {
2191            continue;
2192        }
2193        producers.insert(producer.id.clone());
2194        let outputs = snapshot.dependency_outputs(workspace, producer)?;
2195        let mut json = Vec::new();
2196        for path in &outputs.files {
2197            if source_ignore.matches(path)
2198                || own_outputs.as_ref().is_some_and(|own| own.matches(path))
2199            {
2200                continue;
2201            }
2202            json.extend(
2203                resolver
2204                    .json_globs
2205                    .iter()
2206                    .filter(|glob| {
2207                        glob.matcher.is_match(path)
2208                            && (glob.owner.is_none()
2209                                || snapshot.owner(path) == glob.owner.as_deref())
2210                    })
2211                    .map(|glob| (path.clone(), glob.fields.clone())),
2212            );
2213            for selection in resolver.scopes.values_mut() {
2214                for pattern in &selection.patterns {
2215                    if pattern.matcher.is_match(path)
2216                        && (pattern.owner.is_none()
2217                            || snapshot.owner(path) == pattern.owner.as_deref())
2218                    {
2219                        if pattern.excluded {
2220                            selection.excluded.insert(path.clone());
2221                        } else {
2222                            selection.included.insert(path.clone());
2223                        }
2224                    }
2225                }
2226            }
2227        }
2228        for (path, fields) in json {
2229            resolver.json_file(path, &fields)?;
2230        }
2231    }
2232    // A changed file affected selection adds counts whatever produces it, as
2233    // in Nx, where a declared output is a file like any other.
2234    for selection in resolver.scopes.values() {
2235        resolver.selected.extend(
2236            selection
2237                .included
2238                .difference(&selection.excluded)
2239                .filter(|path| {
2240                    snapshot.extra_candidates.contains(*path)
2241                        || own_outputs.as_ref().is_none_or(|own| !own.matches(path))
2242                })
2243                .cloned(),
2244        );
2245    }
2246    // `includeIgnored` groups read the disk, gitignored files included, and
2247    // a changed path they name counts whether or not it is there. As in Nx,
2248    // one reading another task's declared outputs makes that task a producer.
2249    let mut ignored = BTreeSet::new();
2250    for ((project, _), globs) in &resolver.ignored {
2251        let group = Group::new(
2252            project,
2253            globs,
2254            workspace
2255                .projects
2256                .values()
2257                .map(|project| project.root.as_str()),
2258        )?;
2259        let found = group.expand(&workspace.root)?;
2260        ignored.extend(
2261            found
2262                .into_iter()
2263                .chain(
2264                    snapshot
2265                        .extra_candidates
2266                        .iter()
2267                        .filter(|path| group.matches(path))
2268                        .cloned(),
2269                )
2270                // A task's own outputs are no input of it, as for any fileset.
2271                .filter(|path| own_outputs.as_ref().is_none_or(|own| !own.matches(path))),
2272        );
2273        for (producer, declared) in &snapshot.generated_tasks {
2274            if producer.id != task.id
2275                && upstream.contains(&producer.id)
2276                && declared.declared()
2277                && reads_outputs(&group, declared)
2278            {
2279                producers.insert(producer.id.clone());
2280            }
2281        }
2282    }
2283    resolver.selected.extend(ignored.iter().cloned());
2284    let mut declared = Declared {
2285        files: resolver.selected,
2286        ignored,
2287        values: resolver.values,
2288        json_fields: resolver.json_fields,
2289        external: resolver.external,
2290        external_declared: resolver.external_declared,
2291        projects: resolver.projects,
2292        producers,
2293    };
2294    // `dependentTasksOutputFiles` reads its direct dependencies' declared
2295    // outputs, or with `transitive` those of every task it depends on.
2296    let reads: Vec<bool> = declared
2297        .values
2298        .iter()
2299        .filter(|(name, _)| name.starts_with("dependentTasksOutputFiles:"))
2300        .map(|(_, transitive)| transitive == &Value::Bool(true))
2301        .collect();
2302    if !reads.is_empty() {
2303        let transitive = reads.contains(&true);
2304        for (producer, outputs) in &snapshot.generated_tasks {
2305            let read = if transitive {
2306                upstream.contains(&producer.id)
2307            } else {
2308                task.dependencies.contains(&producer.id)
2309            };
2310            if read && outputs.declared() {
2311                declared.producers.insert(producer.id.clone());
2312            }
2313        }
2314    }
2315    let mut inferred = infer(snapshot, workspace, task)?;
2316    // As in Nx, a task naming its external dependencies hashes those in place
2317    // of every installed package, so the root importer's installs count only
2318    // for the root project's own tasks.
2319    if declared.external_declared
2320        && let Some(importers) = &mut inferred.lockfile
2321    {
2322        let root = workspace.projects[&task.project].root == ".";
2323        if !root {
2324            importers.remove(".");
2325        }
2326    }
2327    Ok(join(declared, inferred))
2328}
2329
2330/// Whether an `includeIgnored` group may read files `outputs` declares, as
2331/// Nx's `GlobShape::may_read` judges it from the globs alone: a positive's
2332/// directory and an output's meet, the one holding the other, unless the
2333/// output lies in a project the positive does not reach, and their
2334/// extensions, where both have one, agree.
2335fn reads_outputs(group: &Group, outputs: &Outputs) -> bool {
2336    let holds = |outer: &str, inner: &str| {
2337        outer.is_empty()
2338            || inner == outer
2339            || inner
2340                .strip_prefix(outer)
2341                .is_some_and(|rest| rest.starts_with('/'))
2342    };
2343    group.reads().any(|(root, extension)| {
2344        outputs.globs().iter().any(|output| {
2345            let (prefix, _) = crate::ignored::partition(output);
2346            (holds(root, &prefix) || holds(&prefix, root))
2347                && !group
2348                    .skipped_below(root)
2349                    .iter()
2350                    .any(|project| holds(project, &prefix))
2351                && match (extension, crate::ignored::extension(output)) {
2352                    (Some(read), Some(written)) => read == written,
2353                    _ => true,
2354                }
2355        })
2356    })
2357}
2358
2359/// What qk adds to `task`'s key on its own, whatever its inputs declare.
2360fn infer(snapshot: &Snapshot, workspace: &Workspace, task: &Task) -> Result<Inferred> {
2361    let readable = snapshot
2362        .installed(&workspace.root, &task.id)?
2363        .is_some_and(|installed| installed.lockfile.is_some());
2364    let exists = |path: &str| {
2365        workspace.root.join(path).is_file() || snapshot.extra_candidates.contains(path)
2366    };
2367    let mut inferred = Inferred {
2368        lockfile_readable: readable,
2369        ..Inferred::default()
2370    };
2371    // Workspace resolution and configuration. Dotenv files are not keyed, as
2372    // in Nx: they hold per-machine values and credentials, and a task's `env`
2373    // inputs key the variables it declares. The root tsconfig, as Nx hashes it
2374    // into every task. The root package.json is not, as in Nx: what the root
2375    // importer installs counts for every task through the lockfile, and the
2376    // rest of it is the root project's manifest.
2377    inferred.tsconfig = crate::inputs::ROOT_TSCONFIG_FILES
2378        .into_iter()
2379        .find(|name| exists(name))
2380        .map(str::to_owned);
2381    for path in [
2382        "nx.json",
2383        ".gitignore",
2384        ".nxignore",
2385        qk_config::LOCAL_WORKSPACE,
2386        "package-lock.json",
2387        "yarn.lock",
2388        "bun.lock",
2389    ] {
2390        if exists(path) {
2391            inferred.files.insert(path.into());
2392        }
2393    }
2394    if let Some(extended) = &workspace.extended {
2395        inferred.files.insert(extended.clone());
2396    }
2397    // A pnpm lockfile qk can read is keyed by what the task's projects
2398    // install, and the workspace file without the resolution keys whose effect
2399    // lands in it.
2400    if exists("pnpm-workspace.yaml") {
2401        if readable {
2402            inferred.workspace_file = true;
2403        } else {
2404            inferred.files.insert("pnpm-workspace.yaml".into());
2405        }
2406    }
2407    if exists("pnpm-lock.yaml") && !readable {
2408        inferred.files.insert("pnpm-lock.yaml".into());
2409    }
2410    // The task's own manifests count whole, its package scripts and dependency
2411    // declarations with them. A dependency's package.json counts by what it
2412    // decides for dependents, such as where their imports of it resolve; its
2413    // installs count through the lockfile.
2414    let mut packages = BTreeSet::from([task.project.clone()]);
2415    let mut pending = packages.clone();
2416    while let Some(project) = pending.pop_first() {
2417        for edge in &snapshot.projects.dependencies[&project] {
2418            if packages.insert(edge.target.clone()) {
2419                pending.insert(edge.target.clone());
2420            }
2421        }
2422    }
2423    for project in &packages {
2424        let own = *project == task.project;
2425        for name in ["project.json", qk_config::LOCAL_OVERRIDES, "package.json"] {
2426            if !own && name != "package.json" {
2427                continue;
2428            }
2429            let path = Path::new(&workspace.projects[project].root).join(name);
2430            let path = path.strip_prefix(".").unwrap_or(&path).to_owned();
2431            if !workspace.root.join(&path).is_file() {
2432                continue;
2433            }
2434            let path = path
2435                .to_str()
2436                .context("project path must be UTF-8")?
2437                .replace('\\', "/");
2438            if own {
2439                inferred.files.insert(path);
2440                continue;
2441            }
2442            let text = std::fs::read_to_string(workspace.root.join(&path))
2443                .with_context(|| format!("cannot read {path}"))?;
2444            match manifest_for_dependents(&text, readable) {
2445                Some(value) => {
2446                    inferred.manifests.insert(path, value);
2447                }
2448                None => {
2449                    inferred.files.insert(path);
2450                }
2451            }
2452        }
2453    }
2454    if readable {
2455        // The root importer's packages resolve from every package in the
2456        // workspace, so they count for every task.
2457        inferred.lockfile = Some(
2458            std::iter::once(".".to_owned())
2459                .chain(
2460                    packages
2461                        .iter()
2462                        .map(|project| workspace.projects[project].root.clone()),
2463                )
2464                .collect(),
2465        );
2466    }
2467    Ok(inferred)
2468}
2469
2470/// `declared` and `inferred` together. A file both select is left to the
2471/// declared inputs, which count all of it.
2472fn join(declared: Declared, mut inferred: Inferred) -> Resolved {
2473    let mut covered = BTreeSet::new();
2474    inferred.files.retain(|path| {
2475        let keep = !declared.files.contains(path);
2476        if !keep {
2477            covered.insert(path.clone());
2478        }
2479        keep
2480    });
2481    inferred.manifests.retain(|path, _| {
2482        let keep = !declared.files.contains(path);
2483        if !keep {
2484            covered.insert(path.clone());
2485        }
2486        keep
2487    });
2488    if inferred.lockfile.is_some() && declared.files.contains("pnpm-lock.yaml") {
2489        inferred.lockfile = None;
2490        covered.insert("pnpm-lock.yaml".into());
2491    }
2492    if inferred.workspace_file && declared.files.contains("pnpm-workspace.yaml") {
2493        inferred.workspace_file = false;
2494        covered.insert("pnpm-workspace.yaml".into());
2495    }
2496    if let Some(tsconfig) = inferred
2497        .tsconfig
2498        .take_if(|path| declared.files.contains(path))
2499    {
2500        covered.insert(tsconfig);
2501    }
2502    inferred.covered = covered;
2503    Resolved { declared, inferred }
2504}
2505
2506/// What a task's key is computed from, as JSON: kept by the history so a
2507/// changed key can be explained.
2508pub fn inputs(
2509    snapshot: &Snapshot,
2510    workspace: &Workspace,
2511    task: &Task,
2512    prepared: &PreparedTask,
2513    dependencies: &BTreeMap<String, String>,
2514    cancelled: &AtomicBool,
2515) -> Result<Value> {
2516    let prefixes = snapshot.membership_prefixes(workspace, task)?;
2517    let candidates = snapshot.current_files_for(&workspace.root, Some(&prefixes), &task.id)?;
2518    let Resolved { declared, inferred } = resolve_candidates(
2519        snapshot,
2520        workspace,
2521        task,
2522        Some(prepared),
2523        cancelled,
2524        &candidates.files,
2525        &candidates.source_ignore,
2526    )?;
2527    let file_values = |paths: &BTreeSet<String>| {
2528        paths
2529            .iter()
2530            .map(|path| {
2531                let value = snapshot
2532                    .file_value(&workspace.root, path)
2533                    .with_context(|| format!("cannot read input {path}"))?;
2534                Ok((path.clone(), value))
2535            })
2536            .collect::<Result<BTreeMap<_, _>>>()
2537    };
2538    let mut files = file_values(&(&declared.files - &declared.ignored))?;
2539    for path in &declared.ignored {
2540        if let Some(value) = snapshot
2541            .ignored_value(&workspace.root, path)
2542            .with_context(|| format!("cannot read input {path}"))?
2543        {
2544            files.insert(path.clone(), value);
2545        }
2546    }
2547    let mut values = declared.values;
2548    let mut configuration = json!({ "files": file_values(&inferred.files)? });
2549    let installed = snapshot.installed(&workspace.root, &task.id)?;
2550    if let (Some(importers), Some(installed)) = (&inferred.lockfile, &installed)
2551        && let Some(lockfile) = &installed.lockfile
2552    {
2553        let importers: BTreeMap<_, _> = importers
2554            .iter()
2555            .filter(|importer| lockfile.has_importer(importer))
2556            .map(|importer| {
2557                let digest = installed.digest(&format!("importer:{importer}"), || {
2558                    lockfile.installed(importer).unwrap_or_default()
2559                });
2560                (importer.clone(), digest)
2561            })
2562            .collect();
2563        configuration["lockfile"] = json!({
2564            "global": installed.digest("global", || BTreeSet::from([lockfile.global().to_string()])),
2565            "importers": importers,
2566        });
2567        // A lockfile keyed whole already covers the packages it installs.
2568        if !declared.external.is_empty() {
2569            let external: BTreeMap<_, _> = declared
2570                .external
2571                .iter()
2572                .map(|name| {
2573                    let digest =
2574                        installed.digest(&format!("package:{name}"), || lockfile.package(name));
2575                    // As in Nx, a package nothing installs is an error.
2576                    if digest == blake3::hash(b"").to_hex().as_str() {
2577                        bail!(
2578                            "the externalDependency {name:?} of {} could not be found",
2579                            task.id
2580                        );
2581                    }
2582                    Ok((name.clone(), digest))
2583                })
2584                .collect::<Result<_>>()?;
2585            values.insert("externalDependencies".into(), json!(external));
2586        }
2587    }
2588    if inferred.workspace_file {
2589        configuration["workspaceFile"] = match workspace_without_resolution(&workspace.root) {
2590            Some(value) => value,
2591            None => snapshot.file_value(&workspace.root, "pnpm-workspace.yaml")?,
2592        };
2593    }
2594    if !inferred.manifests.is_empty() {
2595        configuration["manifests"] = json!(inferred.manifests);
2596    }
2597    if let Some(path) = &inferred.tsconfig {
2598        let parsed = std::fs::read_to_string(workspace.root.join(path))
2599            .ok()
2600            .and_then(|text| TsConfig::parse(&text));
2601        configuration["tsconfig"] = match parsed {
2602            Some(tsconfig) if crate::inputs::selectively_hash_tsconfig(workspace) => json!({
2603                "rest": tsconfig.rest,
2604                "paths": tsconfig.paths_of(&declared.projects, |target| snapshot.owner(target)),
2605            }),
2606            Some(tsconfig) => json!({ "rest": tsconfig.rest }),
2607            None => snapshot.file_value(&workspace.root, path)?,
2608        };
2609    }
2610    // Warm state configuration never changes a result, and as in Nx a
2611    // target's metadata, such as the run command shown for a script, is
2612    // description only.
2613    let mut definition = task.definition.clone();
2614    definition.extra.remove("qk:warm");
2615    definition.extra.remove("qk:threads");
2616    definition.extra.remove("metadata");
2617    let hash = json!({
2618        "schema":"qk-local-v4", "qk":env!("CARGO_PKG_VERSION"),
2619        "platform":[std::env::consts::OS, std::env::consts::ARCH], "workspace":snapshot.workspace_prefix,
2620        "id":task.id, "args":task.args, "definition":definition, "packageManager":workspace.package_manager,
2621        "files":files, "values":values, "inferred":configuration, "dependencies":dependencies,
2622    });
2623    Ok(hash)
2624}
2625
2626/// The key for a task's inputs. Objects are keyed with their fields sorted,
2627/// so the order they were written in, which configuration keeps, does not
2628/// change the key.
2629pub fn key(inputs: &Value) -> Result<String> {
2630    Ok(blake3::hash(&serde_json::to_vec(&sorted(inputs))?)
2631        .to_hex()
2632        .to_string())
2633}
2634
2635/// `value` with every object's fields in key order.
2636fn sorted(value: &Value) -> Value {
2637    match value {
2638        Value::Object(object) => {
2639            let mut fields: Vec<_> = object.iter().collect();
2640            fields.sort_unstable_by_key(|(name, _)| *name);
2641            Value::Object(
2642                fields
2643                    .into_iter()
2644                    .map(|(name, value)| (name.clone(), sorted(value)))
2645                    .collect(),
2646            )
2647        }
2648        Value::Array(items) => Value::Array(items.iter().map(sorted).collect()),
2649        other => other.clone(),
2650    }
2651}
2652
2653pub fn fingerprint(
2654    snapshot: &Snapshot,
2655    workspace: &Workspace,
2656    task: &Task,
2657    prepared: &PreparedTask,
2658    dependencies: &BTreeMap<String, String>,
2659    cancelled: &AtomicBool,
2660) -> Result<String> {
2661    key(&inputs(
2662        snapshot,
2663        workspace,
2664        task,
2665        prepared,
2666        dependencies,
2667        cancelled,
2668    )?)
2669}
2670
2671/// The dependency outputs a task's `dependentTasksOutputFiles` inputs read,
2672/// as Nx hashes them: the files each glob selects of the declared outputs of
2673/// its direct dependencies, or with `transitive` of every task it depends on.
2674/// Nothing else about a dependency keys a task.
2675pub(crate) fn dependency_keys(
2676    snapshot: &Snapshot,
2677    workspace: &Workspace,
2678    graph: &TaskGraph,
2679    task: &Task,
2680    cancelled: &AtomicBool,
2681) -> Result<BTreeMap<String, String>> {
2682    dependency_keys_impl(snapshot, workspace, graph, task, cancelled, false)
2683}
2684
2685/// Read dependency artifacts again before accepting an execution as unchanged.
2686pub(crate) fn recheck_dependency_keys(
2687    snapshot: &Snapshot,
2688    workspace: &Workspace,
2689    graph: &TaskGraph,
2690    task: &Task,
2691    cancelled: &AtomicBool,
2692) -> Result<BTreeMap<String, String>> {
2693    dependency_keys_impl(snapshot, workspace, graph, task, cancelled, true)
2694}
2695
2696fn dependency_keys_impl(
2697    snapshot: &Snapshot,
2698    workspace: &Workspace,
2699    graph: &TaskGraph,
2700    task: &Task,
2701    cancelled: &AtomicBool,
2702    fresh: bool,
2703) -> Result<BTreeMap<String, String>> {
2704    let resolved = resolve(snapshot, workspace, task, None, cancelled)?;
2705    let selections: Vec<_> = resolved.dependency_output_inputs().collect();
2706    let mut keys = BTreeMap::new();
2707    let mut fresh_outputs = HashMap::new();
2708    for (pattern, transitive) in selections {
2709        let matcher = snapshot.pattern(pattern, false)?;
2710        let mut selected = task.dependencies.clone();
2711        if transitive {
2712            let mut pending = selected.clone();
2713            while let Some(id) = pending.pop_first() {
2714                for dependency in &graph.tasks[&id].dependencies {
2715                    if selected.insert(dependency.clone()) {
2716                        pending.insert(dependency.clone());
2717                    }
2718                }
2719            }
2720        }
2721        for id in selected {
2722            // As in Nx, a dependency without declared outputs offers none.
2723            if !Outputs::new(workspace, &graph.tasks[&id])?.declared() {
2724                continue;
2725            }
2726            let outputs = if fresh {
2727                if !fresh_outputs.contains_key(&id) {
2728                    fresh_outputs.insert(
2729                        id.clone(),
2730                        Arc::new(snapshot.fresh_dependency_outputs(workspace, &graph.tasks[&id])?),
2731                    );
2732                }
2733                fresh_outputs[&id].clone()
2734            } else {
2735                snapshot.dependency_outputs(workspace, &graph.tasks[&id])?
2736            };
2737            let mut files = BTreeMap::new();
2738            for path in outputs.files.iter().filter(|path| matcher.is_match(path)) {
2739                let known = outputs.values.lock().unwrap().get(path).cloned();
2740                let value = match known {
2741                    Some(value) => value,
2742                    None => {
2743                        let value = snapshot.file_value(&workspace.root, path)?;
2744                        // Links depend on paths outside the declared output roots.
2745                        if value.get("link").is_none() {
2746                            outputs
2747                                .values
2748                                .lock()
2749                                .unwrap()
2750                                .insert(path.clone(), value.clone());
2751                        }
2752                        value
2753                    }
2754                };
2755                files.insert(path.clone(), value);
2756            }
2757            keys.insert(format!("{id}:{pattern}"), key(&json!(files))?);
2758        }
2759    }
2760    Ok(keys)
2761}
2762
2763#[cfg(test)]
2764mod tests {
2765
2766    /// Every file keyed by its whole content, declared or inferred.
2767    fn whole(resolved: &Resolved) -> BTreeSet<String> {
2768        resolved.whole_files().map(str::to_owned).collect()
2769    }
2770    use super::*;
2771    use qk_taskgraph::Request;
2772
2773    fn fixture(outputs: Option<Value>) -> (tempfile::TempDir, Workspace, TaskGraph) {
2774        let root = tempfile::tempdir().unwrap();
2775        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
2776        let mut post = json!({"command": "true"});
2777        if let Some(outputs) = outputs {
2778            post["outputs"] = outputs;
2779        }
2780        std::fs::write(root.path().join("project.json"), json!({"name":"app", "targets": {
2781            "gen": {"command":"true", "outputs":["{projectRoot}/generated"]},
2782            "post": post,
2783            "build": {"command":"true", "dependsOn":["gen", "post"], "inputs":[{"dependentTasksOutputFiles":"**/*"}]}
2784        }}).to_string()).unwrap();
2785        std::fs::create_dir(root.path().join("generated")).unwrap();
2786        std::fs::write(root.path().join("generated/value"), "one").unwrap();
2787        let workspace = Workspace::load(root.path()).unwrap();
2788        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
2789        (root, workspace, graph)
2790    }
2791
2792    /// A `json` glob selects a dependency's declared outputs, keyed by their
2793    /// fields, and makes that dependency a producer, as a fileset does.
2794
2795    #[test]
2796    fn keys_ignore_the_order_object_fields_were_written_in() {
2797        let written = json!({"options": {"cwd": "app", "command": "x"}, "args": ["a", "b"]});
2798        let reordered = json!({"args": ["a", "b"], "options": {"command": "x", "cwd": "app"}});
2799        assert_eq!(key(&written).unwrap(), key(&reordered).unwrap());
2800        let swapped = json!({"options": {"cwd": "app", "command": "x"}, "args": ["b", "a"]});
2801        assert_ne!(key(&written).unwrap(), key(&swapped).unwrap());
2802    }
2803    #[test]
2804    fn json_globs_select_dependency_outputs() {
2805        let root = tempfile::tempdir().unwrap();
2806        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
2807        for (path, content) in [
2808            (
2809                "apps/app/project.json",
2810                json!({"name": "app", "implicitDependencies": ["lib"], "targets": {
2811                    "build": {"command": "true", "dependsOn": ["^build"], "inputs": [
2812                        {"json": "{workspaceRoot}/libs/lib/out/*.json", "fields": ["version"]}
2813                    ]}
2814                }}),
2815            ),
2816            (
2817                "libs/lib/project.json",
2818                json!({"name": "lib", "targets": {
2819                    "build": {"command": "true", "outputs": ["{projectRoot}/out"]}
2820                }}),
2821            ),
2822            (
2823                "libs/lib/out/meta.json",
2824                json!({"version": 2, "built": "now"}),
2825            ),
2826        ] {
2827            let path = root.path().join(path);
2828            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2829            std::fs::write(path, content.to_string()).unwrap();
2830        }
2831        let workspace = Workspace::load(root.path()).unwrap();
2832        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
2833        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
2834        let resolved = resolve(
2835            &snapshot,
2836            &workspace,
2837            &graph.tasks["app:build"],
2838            None,
2839            &AtomicBool::new(false),
2840        )
2841        .unwrap();
2842        assert_eq!(
2843            resolved.declared.values.get("json:libs/lib/out/meta.json"),
2844            Some(&json!({"version": 2}))
2845        );
2846        assert_eq!(
2847            resolved.declared.producers,
2848            BTreeSet::from(["lib:build".to_owned()])
2849        );
2850    }
2851
2852    #[test]
2853    fn execution_fingerprints_refresh_sources_and_preserve_artifact_exclusions() {
2854        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
2855        let definition = workspace
2856            .projects
2857            .get_mut("app")
2858            .unwrap()
2859            .targets
2860            .get_mut("post")
2861            .unwrap();
2862        definition
2863            .extra
2864            .insert("qk:warm".into(), json!({"paths": ["scratch"]}));
2865        std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
2866        std::fs::create_dir(root.path().join("src")).unwrap();
2867        std::fs::write(root.path().join("src/original"), "one").unwrap();
2868        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
2869        let task = &graph.tasks["app:post"];
2870        let prepared = qk_executor::prepare(&workspace, task, &BTreeMap::new()).unwrap();
2871        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
2872        let inputs = || {
2873            super::inputs(
2874                &snapshot,
2875                &workspace,
2876                task,
2877                &prepared,
2878                &BTreeMap::new(),
2879                &AtomicBool::new(false),
2880            )
2881            .unwrap()
2882        };
2883        let before = inputs();
2884        // Artifacts created after startup must not change the execution key.
2885        for directory in ["generated", "dist", "scratch", "cache", "ignored"] {
2886            std::fs::create_dir_all(root.path().join(directory)).unwrap();
2887            std::fs::write(root.path().join(directory).join("new"), "artifact").unwrap();
2888        }
2889        assert_eq!(before, inputs());
2890        // This covers both post-execution verification and a later task's first
2891        // fingerprint against a snapshot created before this source existed.
2892        std::fs::write(root.path().join("src/added"), "two").unwrap();
2893        let after = inputs();
2894        assert!(after["files"].get("src/added").is_some());
2895        assert_ne!(key(&before).unwrap(), key(&after).unwrap());
2896        std::fs::remove_file(root.path().join("src/added")).unwrap();
2897        assert_eq!(before, inputs());
2898        std::fs::remove_file(root.path().join("src/original")).unwrap();
2899        assert!(inputs()["files"].get("src/original").is_none());
2900    }
2901
2902    #[test]
2903    fn membership_reuses_settled_candidates_and_detects_directory_changes() {
2904        let mut fixtures = Vec::new();
2905        for git in [false, true] {
2906            let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
2907            for directory in ["src/empty", "dist", "cache", "ignored"] {
2908                std::fs::create_dir_all(root.path().join(directory)).unwrap();
2909            }
2910            std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
2911            std::fs::write(root.path().join("src/original"), "one").unwrap();
2912            if git {
2913                assert!(
2914                    paths::git(root.path(), &["init", "-q"])
2915                        .unwrap()
2916                        .status
2917                        .success()
2918                );
2919                assert!(
2920                    paths::git(root.path(), &["add", "."])
2921                        .unwrap()
2922                        .status
2923                        .success()
2924                );
2925            }
2926            let snapshot =
2927                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
2928            snapshot.current_files(root.path()).unwrap();
2929            fixtures.push((root, snapshot));
2930        }
2931        // Recent directory metadata deliberately uses the conservative listing
2932        // path. Waiting lets this test exercise the actual reuse path too.
2933        std::thread::sleep(Duration::from_millis(2100));
2934        for (root, snapshot) in fixtures {
2935            let files = || snapshot.current_files(root.path()).unwrap();
2936            let before = files();
2937            assert!(Arc::ptr_eq(&before, &files()));
2938            for directory in ["generated", "dist", "cache"] {
2939                std::fs::write(root.path().join(directory).join("new"), "artifact").unwrap();
2940            }
2941            assert!(Arc::ptr_eq(&before, &files()));
2942            std::fs::write(root.path().join("src/empty/added"), "two").unwrap();
2943            assert!(files().contains("src/empty/added"));
2944            std::fs::create_dir_all(root.path().join("src/new/nested")).unwrap();
2945            std::fs::write(root.path().join("src/new/nested/added"), "three").unwrap();
2946            assert!(files().contains("src/new/nested/added"));
2947            std::fs::rename(
2948                root.path().join("src/original"),
2949                root.path().join("src/renamed"),
2950            )
2951            .unwrap();
2952            let renamed = files();
2953            assert!(!renamed.contains("src/original"));
2954            assert!(renamed.contains("src/renamed"));
2955            std::fs::remove_file(root.path().join("src/renamed")).unwrap();
2956            assert!(!files().contains("src/renamed"));
2957            // Policy files must be checked even when directory entries do not
2958            // change (editing an existing ignore file in place).
2959            std::fs::write(root.path().join(".gitignore"), "ignored/\nsrc/empty/\n").unwrap();
2960            assert!(!files().contains("src/empty/added"));
2961            std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
2962            assert!(files().contains("src/empty/added"));
2963        }
2964    }
2965
2966    #[test]
2967    fn identical_ignore_rewrites_reuse_candidates_and_changed_rules_refresh() {
2968        for name in [".gitignore", ".nxignore"] {
2969            let (root, workspace, graph) = fixture(None);
2970            let policy = root.path().join(name);
2971            std::fs::write(root.path().join("alpha"), "a").unwrap();
2972            std::fs::write(root.path().join("bravo"), "b").unwrap();
2973            std::fs::write(&policy, "alpha\n").unwrap();
2974            let snapshot =
2975                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
2976            let original = snapshot.current_files(root.path()).unwrap();
2977            assert!(!original.contains("alpha"));
2978            assert!(original.contains("bravo"));
2979            for _ in 0..3 {
2980                std::fs::write(&policy, "alpha\n").unwrap();
2981                assert!(Arc::ptr_eq(
2982                    &original,
2983                    &snapshot.current_files(root.path()).unwrap()
2984                ));
2985            }
2986            // Same-length content can change while coarse timestamps appear
2987            // identical. Recent policies must still compare their contents.
2988            std::fs::write(&policy, "bravo\n").unwrap();
2989            {
2990                let mut cached = snapshot.membership.lock().unwrap();
2991                Arc::make_mut(cached.as_mut().unwrap())
2992                    .stamps
2993                    .insert(policy.clone(), membership_stamp(&policy).unwrap());
2994            }
2995            let changed = snapshot.current_files(root.path()).unwrap();
2996            assert!(!Arc::ptr_eq(&original, &changed));
2997            assert!(changed.contains("alpha"));
2998            assert!(!changed.contains("bravo"));
2999            std::fs::remove_file(&policy).unwrap();
3000            assert!(
3001                snapshot
3002                    .current_files(root.path())
3003                    .unwrap()
3004                    .contains("bravo")
3005            );
3006        }
3007    }
3008
3009    #[test]
3010    fn ignore_contents_changed_after_inventory_cannot_bless_a_listing() {
3011        let (root, workspace, graph) = fixture(None);
3012        let policy = root.path().join(".nxignore");
3013        std::fs::write(&policy, "alpha\n").unwrap();
3014        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3015        snapshot.current_files(root.path()).unwrap();
3016        let membership = snapshot.membership.lock().unwrap().clone().unwrap();
3017        std::fs::write(&policy, "bravo\n").unwrap();
3018        assert!(!membership.state(None).unwrap().0);
3019    }
3020
3021    #[test]
3022    fn a_directory_missed_by_the_inventory_cannot_enable_reuse() {
3023        let (root, workspace, graph) = fixture(None);
3024        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3025        snapshot.current_files(root.path()).unwrap();
3026        std::fs::create_dir(root.path().join("new-empty")).unwrap();
3027        let mut cached = snapshot.membership.lock().unwrap();
3028        let membership = Arc::make_mut(cached.as_mut().unwrap());
3029        // Model creation between the directory walk and child-name capture:
3030        // the new directory is in its parent's names but not in the inventory.
3031        membership
3032            .directory_entries
3033            .get_mut(root.path())
3034            .unwrap()
3035            .insert((OsString::from("new-empty"), 1));
3036        assert!(membership.entries(root.path()).unwrap().is_none());
3037        assert!(!membership.state(None).unwrap().0);
3038    }
3039
3040    #[test]
3041    fn a_policy_missed_by_discovery_cannot_enable_reuse() {
3042        let (root, workspace, graph) = fixture(None);
3043        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3044        snapshot.current_files(root.path()).unwrap();
3045        std::fs::write(root.path().join(".nxignore"), "hidden\n").unwrap();
3046        let mut cached = snapshot.membership.lock().unwrap();
3047        let membership = Arc::make_mut(cached.as_mut().unwrap());
3048        // Model a new policy appearing after discovery but before capturing
3049        // its parent's entries; its content would otherwise have no stamp.
3050        membership
3051            .directory_entries
3052            .get_mut(root.path())
3053            .unwrap()
3054            .insert((OsString::from(".nxignore"), 0));
3055        assert!(membership.entries(root.path()).unwrap().is_none());
3056        assert!(!membership.state(None).unwrap().0);
3057    }
3058
3059    #[test]
3060    fn output_publication_reuses_candidates_but_source_names_still_refresh() {
3061        for partial in [false, true] {
3062            let outputs = if partial {
3063                json!(["{projectRoot}/dist", "!{projectRoot}/dist/keep"])
3064            } else {
3065                json!(["{projectRoot}/dist"])
3066            };
3067            let (root, workspace, graph) = fixture(Some(outputs));
3068            std::fs::create_dir_all(root.path().join("src")).unwrap();
3069            std::fs::write(root.path().join("src/original"), "one").unwrap();
3070            if partial {
3071                std::fs::create_dir_all(root.path().join("dist/keep")).unwrap();
3072            }
3073            let snapshot =
3074                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3075            snapshot.current_files(root.path()).unwrap();
3076            // Policies retain their conservative timestamp window. Directory
3077            // names are freshly verified throughout the window instead.
3078            std::thread::sleep(Duration::from_millis(2100));
3079            let before = snapshot.current_files(root.path()).unwrap();
3080            std::fs::create_dir_all(root.path().join("dist")).unwrap();
3081            std::fs::write(root.path().join("dist/restored"), "artifact").unwrap();
3082            let restored = snapshot.current_files(root.path()).unwrap();
3083            assert!(Arc::ptr_eq(&before, &restored));
3084            std::fs::remove_file(root.path().join("dist/restored")).unwrap();
3085            assert!(Arc::ptr_eq(
3086                &before,
3087                &snapshot.current_files(root.path()).unwrap()
3088            ));
3089            let source = if partial { "dist/keep/new" } else { "src/new" };
3090            std::fs::write(root.path().join(source), "source").unwrap();
3091            let after = snapshot.current_files(root.path()).unwrap();
3092            assert!(after.contains(source));
3093            assert!(!Arc::ptr_eq(&before, &after));
3094            std::fs::remove_file(root.path().join(source)).unwrap();
3095            assert!(
3096                !snapshot
3097                    .current_files(root.path())
3098                    .unwrap()
3099                    .contains(source)
3100            );
3101        }
3102    }
3103
3104    #[test]
3105    fn concurrent_fingerprints_refresh_without_replacing_newer_membership() {
3106        let (root, workspace, graph) = fixture(None);
3107        std::fs::create_dir_all(root.path().join("src")).unwrap();
3108        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3109        let original = snapshot.current_files(root.path()).unwrap();
3110        let barrier = std::sync::Barrier::new(9);
3111        std::thread::scope(|scope| {
3112            let workers: Vec<_> = (0..8)
3113                .map(|_| {
3114                    scope.spawn(|| {
3115                        let mut rounds = Vec::new();
3116                        for _ in 0..6 {
3117                            barrier.wait();
3118                            rounds.push(snapshot.current_files(root.path()));
3119                            barrier.wait();
3120                        }
3121                        rounds
3122                    })
3123                })
3124                .collect();
3125            for round in 0..6 {
3126                std::fs::write(root.path().join(format!("src/new{round}")), "source").unwrap();
3127                barrier.wait();
3128                barrier.wait();
3129            }
3130            // Assertions run after synchronization, so a failed membership
3131            // check cannot strand other workers at a barrier.
3132            for worker in workers {
3133                for (round, files) in worker.join().unwrap().into_iter().enumerate() {
3134                    let files = files.unwrap();
3135                    for added in 0..=round {
3136                        assert!(files.contains(&format!("src/new{added}")));
3137                    }
3138                }
3139            }
3140        });
3141        assert!(!original.contains("src/new0"));
3142        assert!(
3143            snapshot
3144                .current_files(root.path())
3145                .unwrap()
3146                .contains("src/new5")
3147        );
3148    }
3149
3150    #[test]
3151    fn retained_candidates_keep_their_dependency_output_ignore_policy() {
3152        let (root, mut workspace, _) = fixture(None);
3153        workspace
3154            .projects
3155            .get_mut("app")
3156            .unwrap()
3157            .targets
3158            .get_mut("build")
3159            .unwrap()
3160            .inputs = Some(vec![json!("{workspaceRoot}/**/*.txt")]);
3161        std::fs::create_dir(root.path().join("src")).unwrap();
3162        for name in ["alpha", "beta", "gamma"] {
3163            for directory in ["src", "generated"] {
3164                std::fs::write(root.path().join(format!("{directory}/{name}.txt")), name).unwrap();
3165            }
3166        }
3167        let policy = |keep: &str| {
3168            let ignored: String = ["alpha", "beta", "gamma"]
3169                .into_iter()
3170                .filter(|name| *name != keep)
3171                .flat_map(|name| {
3172                    [
3173                        format!("src/{name}.txt\n"),
3174                        format!("generated/{name}.txt\n"),
3175                    ]
3176                })
3177                .collect();
3178            std::fs::write(root.path().join(".nxignore"), ignored).unwrap();
3179        };
3180        policy("alpha");
3181        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3182        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3183        let first = snapshot
3184            .current_files_for(root.path(), None, "test")
3185            .unwrap();
3186        policy("beta");
3187        let second = snapshot
3188            .current_files_for(root.path(), None, "test")
3189            .unwrap();
3190        policy("gamma");
3191        let third = snapshot
3192            .current_files_for(root.path(), None, "test")
3193            .unwrap();
3194        // Deterministically pause two fingerprints after candidate acquisition,
3195        // then let another fingerprint refresh policy twice before they resolve.
3196        let cancelled = AtomicBool::new(false);
3197        let expected = |name: &str| {
3198            BTreeSet::from([
3199                ".nxignore".into(),
3200                "nx.json".into(),
3201                "project.json".into(),
3202                format!("src/{name}.txt"),
3203                format!("generated/{name}.txt"),
3204            ])
3205        };
3206        for (candidates, name) in [(first, "alpha"), (second, "beta"), (third, "gamma")] {
3207            let resolved = resolve_candidates(
3208                &snapshot,
3209                &workspace,
3210                &graph.tasks["app:build"],
3211                None,
3212                &cancelled,
3213                &candidates.files,
3214                &candidates.source_ignore,
3215            )
3216            .unwrap();
3217            assert_eq!(whole(&resolved), expected(name));
3218        }
3219        // Inspection still uses its original candidate list and original policy.
3220        let inspected = resolve(
3221            &snapshot,
3222            &workspace,
3223            &graph.tasks["app:build"],
3224            None,
3225            &cancelled,
3226        )
3227        .unwrap();
3228        assert_eq!(whole(&inspected), expected("alpha"));
3229    }
3230
3231    #[test]
3232    fn scoped_membership_defers_unrelated_changes_until_a_matching_task_asks() {
3233        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3234        let targets = &mut workspace.projects.get_mut("app").unwrap().targets;
3235        targets.get_mut("post").unwrap().inputs =
3236            Some(vec![json!("{workspaceRoot}/left/**/*.txt")]);
3237        targets.get_mut("gen").unwrap().inputs =
3238            Some(vec![json!("{workspaceRoot}/right/**/*.txt")]);
3239        targets.get_mut("build").unwrap().inputs = Some(vec![json!("{workspaceRoot}/**/*.txt")]);
3240        for directory in ["left/empty", "right/empty"] {
3241            std::fs::create_dir_all(root.path().join(directory)).unwrap();
3242        }
3243        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3244        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3245        snapshot.current_files(&workspace.root).unwrap();
3246        std::thread::sleep(Duration::from_millis(2100));
3247        let left = snapshot
3248            .membership_prefixes(&workspace, &graph.tasks["app:post"])
3249            .unwrap();
3250        let right = snapshot
3251            .membership_prefixes(&workspace, &graph.tasks["app:gen"])
3252            .unwrap();
3253        let all = snapshot
3254            .membership_prefixes(&workspace, &graph.tasks["app:build"])
3255            .unwrap();
3256        let before = snapshot
3257            .current_files_for(&workspace.root, Some(&left), "test")
3258            .unwrap();
3259        std::fs::write(root.path().join("right/empty/new.txt"), "right").unwrap();
3260        let unrelated = snapshot
3261            .current_files_for(&workspace.root, Some(&left), "test")
3262            .unwrap();
3263        assert!(Arc::ptr_eq(&before.files, &unrelated.files));
3264        assert!(!unrelated.files.contains("right/empty/new.txt"));
3265        assert!(
3266            snapshot
3267                .current_files_for(&workspace.root, Some(&right), "test")
3268                .unwrap()
3269                .files
3270                .contains("right/empty/new.txt")
3271        );
3272        std::fs::create_dir_all(root.path().join("left/empty/nested")).unwrap();
3273        std::fs::write(root.path().join("left/empty/nested/new.txt"), "left").unwrap();
3274        assert!(
3275            snapshot
3276                .current_files_for(&workspace.root, Some(&left), "test")
3277                .unwrap()
3278                .files
3279                .contains("left/empty/nested/new.txt")
3280        );
3281        std::fs::write(root.path().join("right/empty/another.txt"), "right").unwrap();
3282        assert!(
3283            snapshot
3284                .current_files_for(&workspace.root, Some(&all), "test")
3285                .unwrap()
3286                .files
3287                .contains("right/empty/another.txt")
3288        );
3289    }
3290
3291    #[test]
3292    fn membership_watches_the_directories_json_globs_select_from() {
3293        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3294        let targets = &mut workspace.projects.get_mut("app").unwrap().targets;
3295        targets.get_mut("build").unwrap().inputs = Some(vec![json!(
3296            {"json": "{workspaceRoot}/config/**/*.json", "fields": ["version"]}
3297        )]);
3298        std::fs::create_dir_all(root.path().join("config/empty")).unwrap();
3299        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3300        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3301        snapshot.current_files(&workspace.root).unwrap();
3302        std::thread::sleep(Duration::from_millis(2100));
3303        let prefixes = snapshot
3304            .membership_prefixes(&workspace, &graph.tasks["app:build"])
3305            .unwrap();
3306        snapshot
3307            .current_files_for(&workspace.root, Some(&prefixes), "test")
3308            .unwrap();
3309        std::fs::write(
3310            root.path().join("config/empty/new.json"),
3311            r#"{"version": 1}"#,
3312        )
3313        .unwrap();
3314        assert!(
3315            snapshot
3316                .current_files_for(&workspace.root, Some(&prefixes), "test")
3317                .unwrap()
3318                .files
3319                .contains("config/empty/new.json")
3320        );
3321    }
3322
3323    #[test]
3324    fn membership_watches_git_ignored_tracked_parents_and_index_policy() {
3325        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3326        std::fs::create_dir_all(root.path().join("tracked/nested")).unwrap();
3327        std::fs::write(root.path().join("tracked/.gitignore"), "nested/\n").unwrap();
3328        std::fs::write(root.path().join("tracked/nested/source"), "one").unwrap();
3329        assert!(
3330            paths::git(root.path(), &["init", "-q"])
3331                .unwrap()
3332                .status
3333                .success()
3334        );
3335        assert!(
3336            paths::git(root.path(), &["add", "-f", "tracked/nested/source"])
3337                .unwrap()
3338                .status
3339                .success()
3340        );
3341        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3342        let files = || snapshot.current_files(root.path()).unwrap();
3343        assert!(files().contains("tracked/nested/source"));
3344        std::fs::remove_file(root.path().join("tracked/nested/source")).unwrap();
3345        assert!(!files().contains("tracked/nested/source"));
3346        std::fs::write(root.path().join("tracked/nested/another"), "two").unwrap();
3347        assert!(!files().contains("tracked/nested/another"));
3348        assert!(
3349            paths::git(root.path(), &["add", "-f", "tracked/nested/another"])
3350                .unwrap()
3351                .status
3352                .success()
3353        );
3354        assert!(files().contains("tracked/nested/another"));
3355        std::fs::write(root.path().join("untracked"), "three").unwrap();
3356        assert!(files().contains("untracked"));
3357        std::fs::write(root.path().join(".git/info/exclude"), "untracked\n").unwrap();
3358        assert!(!files().contains("untracked"));
3359    }
3360
3361    #[test]
3362    fn a_new_git_config_include_invalidates_settled_listing_policy() {
3363        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3364        let policy = tempfile::tempdir().unwrap();
3365        let included = policy.path().join("included.config");
3366        let excludes = policy.path().join("excludes");
3367        std::fs::write(&excludes, "hidden\n").unwrap();
3368        std::fs::write(root.path().join("hidden"), "source").unwrap();
3369        assert!(
3370            paths::git(root.path(), &["init", "-q"])
3371                .unwrap()
3372                .status
3373                .success()
3374        );
3375        assert!(
3376            paths::git(
3377                root.path(),
3378                &["config", "include.path", included.to_str().unwrap()]
3379            )
3380            .unwrap()
3381            .status
3382            .success()
3383        );
3384        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3385        snapshot.current_files(&workspace.root).unwrap();
3386        std::thread::sleep(Duration::from_millis(2100));
3387        let before = snapshot.current_files(&workspace.root).unwrap();
3388        assert!(before.contains("hidden"));
3389        assert!(Arc::ptr_eq(
3390            &before,
3391            &snapshot.current_files(&workspace.root).unwrap()
3392        ));
3393        assert!(
3394            paths::git(
3395                root.path(),
3396                &[
3397                    "config",
3398                    "--file",
3399                    included.to_str().unwrap(),
3400                    "core.excludesfile",
3401                    excludes.to_str().unwrap(),
3402                ]
3403            )
3404            .unwrap()
3405            .status
3406            .success()
3407        );
3408        assert!(
3409            !snapshot
3410                .current_files(&workspace.root)
3411                .unwrap()
3412                .contains("hidden")
3413        );
3414    }
3415
3416    #[cfg(unix)]
3417    #[test]
3418    fn git_policy_paths_preserve_quoted_origins_and_multiline_values() {
3419        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3420        let policy = tempfile::tempdir().unwrap();
3421        // Git's text output C-quotes these origins and octal-escapes UTF-8.
3422        let included = policy.path().join("included\\é\t\n.config");
3423        let excludes = policy.path().join("excludes\\é\t\n");
3424        let replacement = policy.path().join("replacement\n");
3425        std::fs::write(&excludes, "hidden\n").unwrap();
3426        std::fs::write(&replacement, "visible\n").unwrap();
3427        for file in ["hidden", "visible"] {
3428            std::fs::write(root.path().join(file), "source").unwrap();
3429        }
3430        let git = |args: &[&str]| {
3431            let output = paths::git(root.path(), args).unwrap();
3432            assert!(output.status.success(), "{output:?}");
3433            output
3434        };
3435        git(&["init", "-q"]);
3436        git(&["config", "include.path", included.to_str().unwrap()]);
3437        git(&[
3438            "config",
3439            "--file",
3440            included.to_str().unwrap(),
3441            "core.excludesfile",
3442            excludes.to_str().unwrap(),
3443        ]);
3444        let text = git(&["config", "--show-origin", "--list"]);
3445        let text = String::from_utf8_lossy(&text.stdout);
3446        let quoted_origin = text
3447            .lines()
3448            .find_map(|line| {
3449                line.strip_prefix("file:\"")
3450                    .and_then(|_| line.split_once('\t'))
3451            })
3452            .unwrap()
3453            .0
3454            .strip_prefix("file:")
3455            .unwrap();
3456        let policies = git_membership_policies(root.path());
3457        assert!(!policies.contains(&root.path().join(quoted_origin)));
3458        assert!(policies.contains(&included));
3459        assert!(policies.contains(&excludes));
3460        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3461        let initial = snapshot.current_files(&workspace.root).unwrap();
3462        assert!(!initial.contains("hidden"));
3463        assert!(initial.contains("visible"));
3464        std::thread::sleep(Duration::from_millis(2100));
3465        let settled = snapshot.current_files(&workspace.root).unwrap();
3466        assert!(Arc::ptr_eq(
3467            &settled,
3468            &snapshot.current_files(&workspace.root).unwrap()
3469        ));
3470        git(&[
3471            "config",
3472            "--file",
3473            included.to_str().unwrap(),
3474            "core.excludesfile",
3475            replacement.to_str().unwrap(),
3476        ]);
3477        let changed = snapshot.current_files(&workspace.root).unwrap();
3478        assert!(changed.contains("hidden"));
3479        assert!(!changed.contains("visible"));
3480        assert!(git_membership_policies(root.path()).contains(&replacement));
3481    }
3482
3483    #[cfg(unix)]
3484    #[test]
3485    fn symlinked_ignore_policy_never_reuses_stale_membership() {
3486        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3487        let policy = tempfile::NamedTempFile::new().unwrap();
3488        std::fs::write(policy.path(), "hidden\n").unwrap();
3489        std::os::unix::fs::symlink(policy.path(), root.path().join(".gitignore")).unwrap();
3490        std::fs::write(root.path().join("hidden"), "source").unwrap();
3491        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3492        assert!(
3493            !snapshot
3494                .current_files(root.path())
3495                .unwrap()
3496                .contains("hidden")
3497        );
3498        assert!(
3499            !snapshot
3500                .membership
3501                .lock()
3502                .unwrap()
3503                .as_ref()
3504                .unwrap()
3505                .settled
3506        );
3507        std::thread::sleep(Duration::from_millis(2100));
3508        let before = snapshot.current_files(root.path()).unwrap();
3509        assert!(Arc::ptr_eq(
3510            &before,
3511            &snapshot.current_files(root.path()).unwrap()
3512        ));
3513        std::fs::write(policy.path(), "").unwrap();
3514        assert!(
3515            snapshot
3516                .current_files(root.path())
3517                .unwrap()
3518                .contains("hidden")
3519        );
3520    }
3521
3522    #[cfg(unix)]
3523    #[test]
3524    fn recent_change_time_prevents_membership_reuse_despite_old_mtime() {
3525        use std::os::unix::fs::MetadataExt;
3526        let root = tempfile::tempdir().unwrap();
3527        let old = SystemTime::UNIX_EPOCH + Duration::from_secs(1);
3528        File::open(root.path())
3529            .unwrap()
3530            .set_times(std::fs::FileTimes::new().set_modified(old))
3531            .unwrap();
3532        let metadata = std::fs::metadata(root.path()).unwrap();
3533        assert!(metadata.ctime() > 1);
3534        let stamp = Stamp::new(&metadata);
3535        assert!(stamp.settled());
3536        assert!(!stamp.membership_settled());
3537    }
3538
3539    #[test]
3540    fn inspection_keeps_deleted_candidates() {
3541        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3542        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache"))
3543            .unwrap()
3544            .with_candidates(&["src/deleted".into()]);
3545        let resolved = resolve(
3546            &snapshot,
3547            &workspace,
3548            &graph.tasks["app:post"],
3549            None,
3550            &AtomicBool::new(false),
3551        )
3552        .unwrap();
3553        assert!(resolved.declared.files.contains("src/deleted"));
3554    }
3555
3556    #[test]
3557    fn undeclared_writes_invalidate_dependency_values() {
3558        for outputs in [None, Some(json!(["{projectRoot}/generated"]))] {
3559            let (root, workspace, graph) = fixture(outputs);
3560            let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3561            let keys = || {
3562                dependency_keys(
3563                    &snapshot,
3564                    &workspace,
3565                    &graph,
3566                    &graph.tasks["app:build"],
3567                    &AtomicBool::new(false),
3568                )
3569                .unwrap()
3570            };
3571            let before = keys();
3572            std::fs::write(root.path().join("generated/value"), "different").unwrap();
3573            snapshot.outputs_written(&workspace, &graph.tasks["app:post"]);
3574            assert_ne!(before, keys());
3575        }
3576    }
3577
3578    #[cfg(unix)]
3579    #[test]
3580    fn dependency_symlinks_recheck_targets_outside_output_roots() {
3581        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/generated"])));
3582        workspace
3583            .projects
3584            .get_mut("app")
3585            .unwrap()
3586            .targets
3587            .get_mut("gen")
3588            .unwrap()
3589            .outputs = Some(vec!["{projectRoot}/links".into()]);
3590        std::fs::create_dir(root.path().join("links")).unwrap();
3591        std::os::unix::fs::symlink("../generated/value", root.path().join("links/value")).unwrap();
3592        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3593        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3594        let keys = || {
3595            dependency_keys(
3596                &snapshot,
3597                &workspace,
3598                &graph,
3599                &graph.tasks["app:build"],
3600                &AtomicBool::new(false),
3601            )
3602            .unwrap()
3603        };
3604        let before = keys();
3605        std::fs::write(root.path().join("generated/value"), "different").unwrap();
3606        snapshot.outputs_written(&workspace, &graph.tasks["app:post"]);
3607        assert_ne!(before["app:gen:**/*"], keys()["app:gen:**/*"]);
3608    }
3609    /// The digest of a git-ignored file an `includeIgnored` fileset reads is
3610    /// saved with the others, so a warm run does not read it again.
3611    #[test]
3612    fn digests_of_ignored_files_read_by_include_ignored_are_saved() {
3613        let root = tempfile::tempdir().unwrap();
3614        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
3615        std::fs::write(root.path().join(".gitignore"), "generated/\n").unwrap();
3616        std::fs::write(
3617            root.path().join("project.json"),
3618            json!({"name": "app", "targets": {"build": {"command": "true", "inputs": [
3619                {"fileset": "{projectRoot}/generated/**/*", "includeIgnored": true}
3620            ]}}})
3621            .to_string(),
3622        )
3623        .unwrap();
3624        std::fs::create_dir(root.path().join("generated")).unwrap();
3625        std::fs::write(root.path().join("generated/schema.json"), "{}").unwrap();
3626        // Digests are only saved for files old enough to have settled.
3627        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
3628        std::fs::File::options()
3629            .write(true)
3630            .open(root.path().join("generated/schema.json"))
3631            .unwrap()
3632            .set_times(std::fs::FileTimes::new().set_modified(old))
3633            .unwrap();
3634        let git = |args: &[&str]| {
3635            assert!(
3636                std::process::Command::new("git")
3637                    .args(args)
3638                    .current_dir(root.path())
3639                    .output()
3640                    .unwrap()
3641                    .status
3642                    .success()
3643            )
3644        };
3645        git(&["init", "--quiet"]);
3646        let workspace = Workspace::load(root.path()).unwrap();
3647        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3648        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3649        assert!(!snapshot.files.contains("generated/schema.json"));
3650        let prepared =
3651            qk_executor::prepare(&workspace, &graph.tasks["app:build"], &BTreeMap::new()).unwrap();
3652        inputs(
3653            &snapshot,
3654            &workspace,
3655            &graph.tasks["app:build"],
3656            &prepared,
3657            &BTreeMap::new(),
3658            &AtomicBool::new(false),
3659        )
3660        .unwrap();
3661        snapshot.save_digests(root.path());
3662        assert!(load_digests(root.path()).contains_key("generated/schema.json"));
3663    }
3664}