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/// What one task's `dependentTasksOutputFiles` glob selects of the outputs it
2764/// reads.
2765#[derive(Clone, Debug, PartialEq, Eq)]
2766pub struct DependencyGlob {
2767    pub task: String,
2768    pub pattern: String,
2769    pub selects: Selects,
2770}
2771
2772#[derive(Clone, Debug, PartialEq, Eq)]
2773pub enum Selects {
2774    /// None of the tasks it reads declares outputs, so nothing ever.
2775    NoDeclaredOutputs,
2776    /// Some of their outputs are not built, so it cannot be told.
2777    NotBuilt,
2778    /// None of the files their outputs hold now, this many.
2779    NoneOf(usize),
2780    /// Some of the files their outputs hold now.
2781    Some,
2782}
2783
2784/// What each `dependentTasksOutputFiles` glob of `graph`'s tasks selects of
2785/// its dependencies' outputs as they are on disk, without running anything.
2786pub fn dependency_globs(workspace: &Workspace, graph: &TaskGraph) -> Result<Vec<DependencyGlob>> {
2787    let snapshot = Snapshot::new(workspace, graph, &paths::cache_location(workspace))?;
2788    let cancelled = AtomicBool::new(false);
2789    let mut globs = Vec::new();
2790    for task in graph.tasks.values() {
2791        // A task whose inputs cannot be resolved fails as it runs instead.
2792        let Ok(resolved) = resolve(&snapshot, workspace, task, None, &cancelled) else {
2793            continue;
2794        };
2795        for (pattern, transitive) in resolved.dependency_output_inputs() {
2796            let mut selected = task.dependencies.clone();
2797            if transitive {
2798                let mut pending = selected.clone();
2799                while let Some(id) = pending.pop_first() {
2800                    for dependency in &graph.tasks[&id].dependencies {
2801                        if selected.insert(dependency.clone()) {
2802                            pending.insert(dependency.clone());
2803                        }
2804                    }
2805                }
2806            }
2807            let matcher = snapshot.pattern(pattern, false)?;
2808            // A dependency not built yet may still produce what it matches.
2809            let (mut declared, mut files, mut matched, mut unbuilt) = (false, 0, false, false);
2810            for id in &selected {
2811                let dependency = &graph.tasks[id];
2812                if !Outputs::new(workspace, dependency)?.declared() {
2813                    continue;
2814                }
2815                declared = true;
2816                let outputs = snapshot.dependency_outputs(workspace, dependency)?;
2817                unbuilt |= outputs.files.is_empty();
2818                files += outputs.files.len();
2819                matched |= outputs.files.iter().any(|path| matcher.is_match(path));
2820            }
2821            globs.push(DependencyGlob {
2822                task: task.id.clone(),
2823                pattern: pattern.to_owned(),
2824                selects: match (declared, matched, unbuilt) {
2825                    (false, ..) => Selects::NoDeclaredOutputs,
2826                    (_, true, _) => Selects::Some,
2827                    (_, _, true) => Selects::NotBuilt,
2828                    _ => Selects::NoneOf(files),
2829                },
2830            });
2831        }
2832    }
2833    Ok(globs)
2834}
2835
2836#[cfg(test)]
2837mod tests {
2838
2839    /// Every file keyed by its whole content, declared or inferred.
2840    fn whole(resolved: &Resolved) -> BTreeSet<String> {
2841        resolved.whole_files().map(str::to_owned).collect()
2842    }
2843    use super::*;
2844    use qk_taskgraph::Request;
2845
2846    fn fixture(outputs: Option<Value>) -> (tempfile::TempDir, Workspace, TaskGraph) {
2847        let root = tempfile::tempdir().unwrap();
2848        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
2849        let mut post = json!({"command": "true"});
2850        if let Some(outputs) = outputs {
2851            post["outputs"] = outputs;
2852        }
2853        std::fs::write(root.path().join("project.json"), json!({"name":"app", "targets": {
2854            "gen": {"command":"true", "outputs":["{projectRoot}/generated"]},
2855            "post": post,
2856            "build": {"command":"true", "dependsOn":["gen", "post"], "inputs":[{"dependentTasksOutputFiles":"**/*"}]}
2857        }}).to_string()).unwrap();
2858        std::fs::create_dir(root.path().join("generated")).unwrap();
2859        std::fs::write(root.path().join("generated/value"), "one").unwrap();
2860        let workspace = Workspace::load(root.path()).unwrap();
2861        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
2862        (root, workspace, graph)
2863    }
2864
2865    /// A `json` glob selects a dependency's declared outputs, keyed by their
2866    /// fields, and makes that dependency a producer, as a fileset does.
2867
2868    #[test]
2869    fn keys_ignore_the_order_object_fields_were_written_in() {
2870        let written = json!({"options": {"cwd": "app", "command": "x"}, "args": ["a", "b"]});
2871        let reordered = json!({"args": ["a", "b"], "options": {"command": "x", "cwd": "app"}});
2872        assert_eq!(key(&written).unwrap(), key(&reordered).unwrap());
2873        let swapped = json!({"options": {"cwd": "app", "command": "x"}, "args": ["b", "a"]});
2874        assert_ne!(key(&written).unwrap(), key(&swapped).unwrap());
2875    }
2876    #[test]
2877    fn json_globs_select_dependency_outputs() {
2878        let root = tempfile::tempdir().unwrap();
2879        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
2880        for (path, content) in [
2881            (
2882                "apps/app/project.json",
2883                json!({"name": "app", "implicitDependencies": ["lib"], "targets": {
2884                    "build": {"command": "true", "dependsOn": ["^build"], "inputs": [
2885                        {"json": "{workspaceRoot}/libs/lib/out/*.json", "fields": ["version"]}
2886                    ]}
2887                }}),
2888            ),
2889            (
2890                "libs/lib/project.json",
2891                json!({"name": "lib", "targets": {
2892                    "build": {"command": "true", "outputs": ["{projectRoot}/out"]}
2893                }}),
2894            ),
2895            (
2896                "libs/lib/out/meta.json",
2897                json!({"version": 2, "built": "now"}),
2898            ),
2899        ] {
2900            let path = root.path().join(path);
2901            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2902            std::fs::write(path, content.to_string()).unwrap();
2903        }
2904        let workspace = Workspace::load(root.path()).unwrap();
2905        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
2906        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
2907        let resolved = resolve(
2908            &snapshot,
2909            &workspace,
2910            &graph.tasks["app:build"],
2911            None,
2912            &AtomicBool::new(false),
2913        )
2914        .unwrap();
2915        assert_eq!(
2916            resolved.declared.values.get("json:libs/lib/out/meta.json"),
2917            Some(&json!({"version": 2}))
2918        );
2919        assert_eq!(
2920            resolved.declared.producers,
2921            BTreeSet::from(["lib:build".to_owned()])
2922        );
2923    }
2924
2925    #[test]
2926    fn execution_fingerprints_refresh_sources_and_preserve_artifact_exclusions() {
2927        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
2928        let definition = workspace
2929            .projects
2930            .get_mut("app")
2931            .unwrap()
2932            .targets
2933            .get_mut("post")
2934            .unwrap();
2935        definition
2936            .extra
2937            .insert("qk:warm".into(), json!({"paths": ["scratch"]}));
2938        std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
2939        std::fs::create_dir(root.path().join("src")).unwrap();
2940        std::fs::write(root.path().join("src/original"), "one").unwrap();
2941        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
2942        let task = &graph.tasks["app:post"];
2943        let prepared = qk_executor::prepare(&workspace, task, &BTreeMap::new()).unwrap();
2944        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
2945        let inputs = || {
2946            super::inputs(
2947                &snapshot,
2948                &workspace,
2949                task,
2950                &prepared,
2951                &BTreeMap::new(),
2952                &AtomicBool::new(false),
2953            )
2954            .unwrap()
2955        };
2956        let before = inputs();
2957        // Artifacts created after startup must not change the execution key.
2958        for directory in ["generated", "dist", "scratch", "cache", "ignored"] {
2959            std::fs::create_dir_all(root.path().join(directory)).unwrap();
2960            std::fs::write(root.path().join(directory).join("new"), "artifact").unwrap();
2961        }
2962        assert_eq!(before, inputs());
2963        // This covers both post-execution verification and a later task's first
2964        // fingerprint against a snapshot created before this source existed.
2965        std::fs::write(root.path().join("src/added"), "two").unwrap();
2966        let after = inputs();
2967        assert!(after["files"].get("src/added").is_some());
2968        assert_ne!(key(&before).unwrap(), key(&after).unwrap());
2969        std::fs::remove_file(root.path().join("src/added")).unwrap();
2970        assert_eq!(before, inputs());
2971        std::fs::remove_file(root.path().join("src/original")).unwrap();
2972        assert!(inputs()["files"].get("src/original").is_none());
2973    }
2974
2975    #[test]
2976    fn membership_reuses_settled_candidates_and_detects_directory_changes() {
2977        let mut fixtures = Vec::new();
2978        for git in [false, true] {
2979            let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
2980            for directory in ["src/empty", "dist", "cache", "ignored"] {
2981                std::fs::create_dir_all(root.path().join(directory)).unwrap();
2982            }
2983            std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
2984            std::fs::write(root.path().join("src/original"), "one").unwrap();
2985            if git {
2986                assert!(
2987                    paths::git(root.path(), &["init", "-q"])
2988                        .unwrap()
2989                        .status
2990                        .success()
2991                );
2992                assert!(
2993                    paths::git(root.path(), &["add", "."])
2994                        .unwrap()
2995                        .status
2996                        .success()
2997                );
2998            }
2999            let snapshot =
3000                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3001            snapshot.current_files(root.path()).unwrap();
3002            fixtures.push((root, snapshot));
3003        }
3004        // Recent directory metadata deliberately uses the conservative listing
3005        // path. Waiting lets this test exercise the actual reuse path too.
3006        std::thread::sleep(Duration::from_millis(2100));
3007        for (root, snapshot) in fixtures {
3008            let files = || snapshot.current_files(root.path()).unwrap();
3009            let before = files();
3010            assert!(Arc::ptr_eq(&before, &files()));
3011            for directory in ["generated", "dist", "cache"] {
3012                std::fs::write(root.path().join(directory).join("new"), "artifact").unwrap();
3013            }
3014            assert!(Arc::ptr_eq(&before, &files()));
3015            std::fs::write(root.path().join("src/empty/added"), "two").unwrap();
3016            assert!(files().contains("src/empty/added"));
3017            std::fs::create_dir_all(root.path().join("src/new/nested")).unwrap();
3018            std::fs::write(root.path().join("src/new/nested/added"), "three").unwrap();
3019            assert!(files().contains("src/new/nested/added"));
3020            std::fs::rename(
3021                root.path().join("src/original"),
3022                root.path().join("src/renamed"),
3023            )
3024            .unwrap();
3025            let renamed = files();
3026            assert!(!renamed.contains("src/original"));
3027            assert!(renamed.contains("src/renamed"));
3028            std::fs::remove_file(root.path().join("src/renamed")).unwrap();
3029            assert!(!files().contains("src/renamed"));
3030            // Policy files must be checked even when directory entries do not
3031            // change (editing an existing ignore file in place).
3032            std::fs::write(root.path().join(".gitignore"), "ignored/\nsrc/empty/\n").unwrap();
3033            assert!(!files().contains("src/empty/added"));
3034            std::fs::write(root.path().join(".gitignore"), "ignored/\n").unwrap();
3035            assert!(files().contains("src/empty/added"));
3036        }
3037    }
3038
3039    #[test]
3040    fn identical_ignore_rewrites_reuse_candidates_and_changed_rules_refresh() {
3041        for name in [".gitignore", ".nxignore"] {
3042            let (root, workspace, graph) = fixture(None);
3043            let policy = root.path().join(name);
3044            std::fs::write(root.path().join("alpha"), "a").unwrap();
3045            std::fs::write(root.path().join("bravo"), "b").unwrap();
3046            std::fs::write(&policy, "alpha\n").unwrap();
3047            let snapshot =
3048                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3049            let original = snapshot.current_files(root.path()).unwrap();
3050            assert!(!original.contains("alpha"));
3051            assert!(original.contains("bravo"));
3052            for _ in 0..3 {
3053                std::fs::write(&policy, "alpha\n").unwrap();
3054                assert!(Arc::ptr_eq(
3055                    &original,
3056                    &snapshot.current_files(root.path()).unwrap()
3057                ));
3058            }
3059            // Same-length content can change while coarse timestamps appear
3060            // identical. Recent policies must still compare their contents.
3061            std::fs::write(&policy, "bravo\n").unwrap();
3062            {
3063                let mut cached = snapshot.membership.lock().unwrap();
3064                Arc::make_mut(cached.as_mut().unwrap())
3065                    .stamps
3066                    .insert(policy.clone(), membership_stamp(&policy).unwrap());
3067            }
3068            let changed = snapshot.current_files(root.path()).unwrap();
3069            assert!(!Arc::ptr_eq(&original, &changed));
3070            assert!(changed.contains("alpha"));
3071            assert!(!changed.contains("bravo"));
3072            std::fs::remove_file(&policy).unwrap();
3073            assert!(
3074                snapshot
3075                    .current_files(root.path())
3076                    .unwrap()
3077                    .contains("bravo")
3078            );
3079        }
3080    }
3081
3082    #[test]
3083    fn ignore_contents_changed_after_inventory_cannot_bless_a_listing() {
3084        let (root, workspace, graph) = fixture(None);
3085        let policy = root.path().join(".nxignore");
3086        std::fs::write(&policy, "alpha\n").unwrap();
3087        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3088        snapshot.current_files(root.path()).unwrap();
3089        let membership = snapshot.membership.lock().unwrap().clone().unwrap();
3090        std::fs::write(&policy, "bravo\n").unwrap();
3091        assert!(!membership.state(None).unwrap().0);
3092    }
3093
3094    #[test]
3095    fn a_directory_missed_by_the_inventory_cannot_enable_reuse() {
3096        let (root, workspace, graph) = fixture(None);
3097        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3098        snapshot.current_files(root.path()).unwrap();
3099        std::fs::create_dir(root.path().join("new-empty")).unwrap();
3100        let mut cached = snapshot.membership.lock().unwrap();
3101        let membership = Arc::make_mut(cached.as_mut().unwrap());
3102        // Model creation between the directory walk and child-name capture:
3103        // the new directory is in its parent's names but not in the inventory.
3104        membership
3105            .directory_entries
3106            .get_mut(root.path())
3107            .unwrap()
3108            .insert((OsString::from("new-empty"), 1));
3109        assert!(membership.entries(root.path()).unwrap().is_none());
3110        assert!(!membership.state(None).unwrap().0);
3111    }
3112
3113    #[test]
3114    fn a_policy_missed_by_discovery_cannot_enable_reuse() {
3115        let (root, workspace, graph) = fixture(None);
3116        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3117        snapshot.current_files(root.path()).unwrap();
3118        std::fs::write(root.path().join(".nxignore"), "hidden\n").unwrap();
3119        let mut cached = snapshot.membership.lock().unwrap();
3120        let membership = Arc::make_mut(cached.as_mut().unwrap());
3121        // Model a new policy appearing after discovery but before capturing
3122        // its parent's entries; its content would otherwise have no stamp.
3123        membership
3124            .directory_entries
3125            .get_mut(root.path())
3126            .unwrap()
3127            .insert((OsString::from(".nxignore"), 0));
3128        assert!(membership.entries(root.path()).unwrap().is_none());
3129        assert!(!membership.state(None).unwrap().0);
3130    }
3131
3132    #[test]
3133    fn output_publication_reuses_candidates_but_source_names_still_refresh() {
3134        for partial in [false, true] {
3135            let outputs = if partial {
3136                json!(["{projectRoot}/dist", "!{projectRoot}/dist/keep"])
3137            } else {
3138                json!(["{projectRoot}/dist"])
3139            };
3140            let (root, workspace, graph) = fixture(Some(outputs));
3141            std::fs::create_dir_all(root.path().join("src")).unwrap();
3142            std::fs::write(root.path().join("src/original"), "one").unwrap();
3143            if partial {
3144                std::fs::create_dir_all(root.path().join("dist/keep")).unwrap();
3145            }
3146            let snapshot =
3147                Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3148            snapshot.current_files(root.path()).unwrap();
3149            // Policies retain their conservative timestamp window. Directory
3150            // names are freshly verified throughout the window instead.
3151            std::thread::sleep(Duration::from_millis(2100));
3152            let before = snapshot.current_files(root.path()).unwrap();
3153            std::fs::create_dir_all(root.path().join("dist")).unwrap();
3154            std::fs::write(root.path().join("dist/restored"), "artifact").unwrap();
3155            let restored = snapshot.current_files(root.path()).unwrap();
3156            assert!(Arc::ptr_eq(&before, &restored));
3157            std::fs::remove_file(root.path().join("dist/restored")).unwrap();
3158            assert!(Arc::ptr_eq(
3159                &before,
3160                &snapshot.current_files(root.path()).unwrap()
3161            ));
3162            let source = if partial { "dist/keep/new" } else { "src/new" };
3163            std::fs::write(root.path().join(source), "source").unwrap();
3164            let after = snapshot.current_files(root.path()).unwrap();
3165            assert!(after.contains(source));
3166            assert!(!Arc::ptr_eq(&before, &after));
3167            std::fs::remove_file(root.path().join(source)).unwrap();
3168            assert!(
3169                !snapshot
3170                    .current_files(root.path())
3171                    .unwrap()
3172                    .contains(source)
3173            );
3174        }
3175    }
3176
3177    #[test]
3178    fn concurrent_fingerprints_refresh_without_replacing_newer_membership() {
3179        let (root, workspace, graph) = fixture(None);
3180        std::fs::create_dir_all(root.path().join("src")).unwrap();
3181        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3182        let original = snapshot.current_files(root.path()).unwrap();
3183        let barrier = std::sync::Barrier::new(9);
3184        std::thread::scope(|scope| {
3185            let workers: Vec<_> = (0..8)
3186                .map(|_| {
3187                    scope.spawn(|| {
3188                        let mut rounds = Vec::new();
3189                        for _ in 0..6 {
3190                            barrier.wait();
3191                            rounds.push(snapshot.current_files(root.path()));
3192                            barrier.wait();
3193                        }
3194                        rounds
3195                    })
3196                })
3197                .collect();
3198            for round in 0..6 {
3199                std::fs::write(root.path().join(format!("src/new{round}")), "source").unwrap();
3200                barrier.wait();
3201                barrier.wait();
3202            }
3203            // Assertions run after synchronization, so a failed membership
3204            // check cannot strand other workers at a barrier.
3205            for worker in workers {
3206                for (round, files) in worker.join().unwrap().into_iter().enumerate() {
3207                    let files = files.unwrap();
3208                    for added in 0..=round {
3209                        assert!(files.contains(&format!("src/new{added}")));
3210                    }
3211                }
3212            }
3213        });
3214        assert!(!original.contains("src/new0"));
3215        assert!(
3216            snapshot
3217                .current_files(root.path())
3218                .unwrap()
3219                .contains("src/new5")
3220        );
3221    }
3222
3223    #[test]
3224    fn retained_candidates_keep_their_dependency_output_ignore_policy() {
3225        let (root, mut workspace, _) = fixture(None);
3226        workspace
3227            .projects
3228            .get_mut("app")
3229            .unwrap()
3230            .targets
3231            .get_mut("build")
3232            .unwrap()
3233            .inputs = Some(vec![json!("{workspaceRoot}/**/*.txt")]);
3234        std::fs::create_dir(root.path().join("src")).unwrap();
3235        for name in ["alpha", "beta", "gamma"] {
3236            for directory in ["src", "generated"] {
3237                std::fs::write(root.path().join(format!("{directory}/{name}.txt")), name).unwrap();
3238            }
3239        }
3240        let policy = |keep: &str| {
3241            let ignored: String = ["alpha", "beta", "gamma"]
3242                .into_iter()
3243                .filter(|name| *name != keep)
3244                .flat_map(|name| {
3245                    [
3246                        format!("src/{name}.txt\n"),
3247                        format!("generated/{name}.txt\n"),
3248                    ]
3249                })
3250                .collect();
3251            std::fs::write(root.path().join(".nxignore"), ignored).unwrap();
3252        };
3253        policy("alpha");
3254        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3255        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3256        let first = snapshot
3257            .current_files_for(root.path(), None, "test")
3258            .unwrap();
3259        policy("beta");
3260        let second = snapshot
3261            .current_files_for(root.path(), None, "test")
3262            .unwrap();
3263        policy("gamma");
3264        let third = snapshot
3265            .current_files_for(root.path(), None, "test")
3266            .unwrap();
3267        // Deterministically pause two fingerprints after candidate acquisition,
3268        // then let another fingerprint refresh policy twice before they resolve.
3269        let cancelled = AtomicBool::new(false);
3270        let expected = |name: &str| {
3271            BTreeSet::from([
3272                ".nxignore".into(),
3273                "nx.json".into(),
3274                "project.json".into(),
3275                format!("src/{name}.txt"),
3276                format!("generated/{name}.txt"),
3277            ])
3278        };
3279        for (candidates, name) in [(first, "alpha"), (second, "beta"), (third, "gamma")] {
3280            let resolved = resolve_candidates(
3281                &snapshot,
3282                &workspace,
3283                &graph.tasks["app:build"],
3284                None,
3285                &cancelled,
3286                &candidates.files,
3287                &candidates.source_ignore,
3288            )
3289            .unwrap();
3290            assert_eq!(whole(&resolved), expected(name));
3291        }
3292        // Inspection still uses its original candidate list and original policy.
3293        let inspected = resolve(
3294            &snapshot,
3295            &workspace,
3296            &graph.tasks["app:build"],
3297            None,
3298            &cancelled,
3299        )
3300        .unwrap();
3301        assert_eq!(whole(&inspected), expected("alpha"));
3302    }
3303
3304    #[test]
3305    fn scoped_membership_defers_unrelated_changes_until_a_matching_task_asks() {
3306        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3307        let targets = &mut workspace.projects.get_mut("app").unwrap().targets;
3308        targets.get_mut("post").unwrap().inputs =
3309            Some(vec![json!("{workspaceRoot}/left/**/*.txt")]);
3310        targets.get_mut("gen").unwrap().inputs =
3311            Some(vec![json!("{workspaceRoot}/right/**/*.txt")]);
3312        targets.get_mut("build").unwrap().inputs = Some(vec![json!("{workspaceRoot}/**/*.txt")]);
3313        for directory in ["left/empty", "right/empty"] {
3314            std::fs::create_dir_all(root.path().join(directory)).unwrap();
3315        }
3316        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3317        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3318        snapshot.current_files(&workspace.root).unwrap();
3319        std::thread::sleep(Duration::from_millis(2100));
3320        let left = snapshot
3321            .membership_prefixes(&workspace, &graph.tasks["app:post"])
3322            .unwrap();
3323        let right = snapshot
3324            .membership_prefixes(&workspace, &graph.tasks["app:gen"])
3325            .unwrap();
3326        let all = snapshot
3327            .membership_prefixes(&workspace, &graph.tasks["app:build"])
3328            .unwrap();
3329        let before = snapshot
3330            .current_files_for(&workspace.root, Some(&left), "test")
3331            .unwrap();
3332        std::fs::write(root.path().join("right/empty/new.txt"), "right").unwrap();
3333        let unrelated = snapshot
3334            .current_files_for(&workspace.root, Some(&left), "test")
3335            .unwrap();
3336        assert!(Arc::ptr_eq(&before.files, &unrelated.files));
3337        assert!(!unrelated.files.contains("right/empty/new.txt"));
3338        assert!(
3339            snapshot
3340                .current_files_for(&workspace.root, Some(&right), "test")
3341                .unwrap()
3342                .files
3343                .contains("right/empty/new.txt")
3344        );
3345        std::fs::create_dir_all(root.path().join("left/empty/nested")).unwrap();
3346        std::fs::write(root.path().join("left/empty/nested/new.txt"), "left").unwrap();
3347        assert!(
3348            snapshot
3349                .current_files_for(&workspace.root, Some(&left), "test")
3350                .unwrap()
3351                .files
3352                .contains("left/empty/nested/new.txt")
3353        );
3354        std::fs::write(root.path().join("right/empty/another.txt"), "right").unwrap();
3355        assert!(
3356            snapshot
3357                .current_files_for(&workspace.root, Some(&all), "test")
3358                .unwrap()
3359                .files
3360                .contains("right/empty/another.txt")
3361        );
3362    }
3363
3364    #[test]
3365    fn membership_watches_the_directories_json_globs_select_from() {
3366        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/dist"])));
3367        let targets = &mut workspace.projects.get_mut("app").unwrap().targets;
3368        targets.get_mut("build").unwrap().inputs = Some(vec![json!(
3369            {"json": "{workspaceRoot}/config/**/*.json", "fields": ["version"]}
3370        )]);
3371        std::fs::create_dir_all(root.path().join("config/empty")).unwrap();
3372        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3373        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3374        snapshot.current_files(&workspace.root).unwrap();
3375        std::thread::sleep(Duration::from_millis(2100));
3376        let prefixes = snapshot
3377            .membership_prefixes(&workspace, &graph.tasks["app:build"])
3378            .unwrap();
3379        snapshot
3380            .current_files_for(&workspace.root, Some(&prefixes), "test")
3381            .unwrap();
3382        std::fs::write(
3383            root.path().join("config/empty/new.json"),
3384            r#"{"version": 1}"#,
3385        )
3386        .unwrap();
3387        assert!(
3388            snapshot
3389                .current_files_for(&workspace.root, Some(&prefixes), "test")
3390                .unwrap()
3391                .files
3392                .contains("config/empty/new.json")
3393        );
3394    }
3395
3396    #[test]
3397    fn membership_watches_git_ignored_tracked_parents_and_index_policy() {
3398        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3399        std::fs::create_dir_all(root.path().join("tracked/nested")).unwrap();
3400        std::fs::write(root.path().join("tracked/.gitignore"), "nested/\n").unwrap();
3401        std::fs::write(root.path().join("tracked/nested/source"), "one").unwrap();
3402        assert!(
3403            paths::git(root.path(), &["init", "-q"])
3404                .unwrap()
3405                .status
3406                .success()
3407        );
3408        assert!(
3409            paths::git(root.path(), &["add", "-f", "tracked/nested/source"])
3410                .unwrap()
3411                .status
3412                .success()
3413        );
3414        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3415        let files = || snapshot.current_files(root.path()).unwrap();
3416        assert!(files().contains("tracked/nested/source"));
3417        std::fs::remove_file(root.path().join("tracked/nested/source")).unwrap();
3418        assert!(!files().contains("tracked/nested/source"));
3419        std::fs::write(root.path().join("tracked/nested/another"), "two").unwrap();
3420        assert!(!files().contains("tracked/nested/another"));
3421        assert!(
3422            paths::git(root.path(), &["add", "-f", "tracked/nested/another"])
3423                .unwrap()
3424                .status
3425                .success()
3426        );
3427        assert!(files().contains("tracked/nested/another"));
3428        std::fs::write(root.path().join("untracked"), "three").unwrap();
3429        assert!(files().contains("untracked"));
3430        std::fs::write(root.path().join(".git/info/exclude"), "untracked\n").unwrap();
3431        assert!(!files().contains("untracked"));
3432    }
3433
3434    #[test]
3435    fn a_new_git_config_include_invalidates_settled_listing_policy() {
3436        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3437        let policy = tempfile::tempdir().unwrap();
3438        let included = policy.path().join("included.config");
3439        let excludes = policy.path().join("excludes");
3440        std::fs::write(&excludes, "hidden\n").unwrap();
3441        std::fs::write(root.path().join("hidden"), "source").unwrap();
3442        assert!(
3443            paths::git(root.path(), &["init", "-q"])
3444                .unwrap()
3445                .status
3446                .success()
3447        );
3448        assert!(
3449            paths::git(
3450                root.path(),
3451                &["config", "include.path", included.to_str().unwrap()]
3452            )
3453            .unwrap()
3454            .status
3455            .success()
3456        );
3457        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3458        snapshot.current_files(&workspace.root).unwrap();
3459        std::thread::sleep(Duration::from_millis(2100));
3460        let before = snapshot.current_files(&workspace.root).unwrap();
3461        assert!(before.contains("hidden"));
3462        assert!(Arc::ptr_eq(
3463            &before,
3464            &snapshot.current_files(&workspace.root).unwrap()
3465        ));
3466        assert!(
3467            paths::git(
3468                root.path(),
3469                &[
3470                    "config",
3471                    "--file",
3472                    included.to_str().unwrap(),
3473                    "core.excludesfile",
3474                    excludes.to_str().unwrap(),
3475                ]
3476            )
3477            .unwrap()
3478            .status
3479            .success()
3480        );
3481        assert!(
3482            !snapshot
3483                .current_files(&workspace.root)
3484                .unwrap()
3485                .contains("hidden")
3486        );
3487    }
3488
3489    #[cfg(unix)]
3490    #[test]
3491    fn git_policy_paths_preserve_quoted_origins_and_multiline_values() {
3492        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3493        let policy = tempfile::tempdir().unwrap();
3494        // Git's text output C-quotes these origins and octal-escapes UTF-8.
3495        let included = policy.path().join("included\\é\t\n.config");
3496        let excludes = policy.path().join("excludes\\é\t\n");
3497        let replacement = policy.path().join("replacement\n");
3498        std::fs::write(&excludes, "hidden\n").unwrap();
3499        std::fs::write(&replacement, "visible\n").unwrap();
3500        for file in ["hidden", "visible"] {
3501            std::fs::write(root.path().join(file), "source").unwrap();
3502        }
3503        let git = |args: &[&str]| {
3504            let output = paths::git(root.path(), args).unwrap();
3505            assert!(output.status.success(), "{output:?}");
3506            output
3507        };
3508        git(&["init", "-q"]);
3509        git(&["config", "include.path", included.to_str().unwrap()]);
3510        git(&[
3511            "config",
3512            "--file",
3513            included.to_str().unwrap(),
3514            "core.excludesfile",
3515            excludes.to_str().unwrap(),
3516        ]);
3517        let text = git(&["config", "--show-origin", "--list"]);
3518        let text = String::from_utf8_lossy(&text.stdout);
3519        let quoted_origin = text
3520            .lines()
3521            .find_map(|line| {
3522                line.strip_prefix("file:\"")
3523                    .and_then(|_| line.split_once('\t'))
3524            })
3525            .unwrap()
3526            .0
3527            .strip_prefix("file:")
3528            .unwrap();
3529        let policies = git_membership_policies(root.path());
3530        assert!(!policies.contains(&root.path().join(quoted_origin)));
3531        assert!(policies.contains(&included));
3532        assert!(policies.contains(&excludes));
3533        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3534        let initial = snapshot.current_files(&workspace.root).unwrap();
3535        assert!(!initial.contains("hidden"));
3536        assert!(initial.contains("visible"));
3537        std::thread::sleep(Duration::from_millis(2100));
3538        let settled = snapshot.current_files(&workspace.root).unwrap();
3539        assert!(Arc::ptr_eq(
3540            &settled,
3541            &snapshot.current_files(&workspace.root).unwrap()
3542        ));
3543        git(&[
3544            "config",
3545            "--file",
3546            included.to_str().unwrap(),
3547            "core.excludesfile",
3548            replacement.to_str().unwrap(),
3549        ]);
3550        let changed = snapshot.current_files(&workspace.root).unwrap();
3551        assert!(changed.contains("hidden"));
3552        assert!(!changed.contains("visible"));
3553        assert!(git_membership_policies(root.path()).contains(&replacement));
3554    }
3555
3556    #[cfg(unix)]
3557    #[test]
3558    fn symlinked_ignore_policy_never_reuses_stale_membership() {
3559        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3560        let policy = tempfile::NamedTempFile::new().unwrap();
3561        std::fs::write(policy.path(), "hidden\n").unwrap();
3562        std::os::unix::fs::symlink(policy.path(), root.path().join(".gitignore")).unwrap();
3563        std::fs::write(root.path().join("hidden"), "source").unwrap();
3564        let snapshot = Snapshot::new(&workspace, &graph, &workspace.root.join("cache")).unwrap();
3565        assert!(
3566            !snapshot
3567                .current_files(root.path())
3568                .unwrap()
3569                .contains("hidden")
3570        );
3571        assert!(
3572            !snapshot
3573                .membership
3574                .lock()
3575                .unwrap()
3576                .as_ref()
3577                .unwrap()
3578                .settled
3579        );
3580        std::thread::sleep(Duration::from_millis(2100));
3581        let before = snapshot.current_files(root.path()).unwrap();
3582        assert!(Arc::ptr_eq(
3583            &before,
3584            &snapshot.current_files(root.path()).unwrap()
3585        ));
3586        std::fs::write(policy.path(), "").unwrap();
3587        assert!(
3588            snapshot
3589                .current_files(root.path())
3590                .unwrap()
3591                .contains("hidden")
3592        );
3593    }
3594
3595    #[cfg(unix)]
3596    #[test]
3597    fn recent_change_time_prevents_membership_reuse_despite_old_mtime() {
3598        use std::os::unix::fs::MetadataExt;
3599        let root = tempfile::tempdir().unwrap();
3600        let old = SystemTime::UNIX_EPOCH + Duration::from_secs(1);
3601        File::open(root.path())
3602            .unwrap()
3603            .set_times(std::fs::FileTimes::new().set_modified(old))
3604            .unwrap();
3605        let metadata = std::fs::metadata(root.path()).unwrap();
3606        assert!(metadata.ctime() > 1);
3607        let stamp = Stamp::new(&metadata);
3608        assert!(stamp.settled());
3609        assert!(!stamp.membership_settled());
3610    }
3611
3612    #[test]
3613    fn inspection_keeps_deleted_candidates() {
3614        let (root, workspace, graph) = fixture(Some(json!(["{projectRoot}/dist"])));
3615        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache"))
3616            .unwrap()
3617            .with_candidates(&["src/deleted".into()]);
3618        let resolved = resolve(
3619            &snapshot,
3620            &workspace,
3621            &graph.tasks["app:post"],
3622            None,
3623            &AtomicBool::new(false),
3624        )
3625        .unwrap();
3626        assert!(resolved.declared.files.contains("src/deleted"));
3627    }
3628
3629    #[test]
3630    fn undeclared_writes_invalidate_dependency_values() {
3631        for outputs in [None, Some(json!(["{projectRoot}/generated"]))] {
3632            let (root, workspace, graph) = fixture(outputs);
3633            let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3634            let keys = || {
3635                dependency_keys(
3636                    &snapshot,
3637                    &workspace,
3638                    &graph,
3639                    &graph.tasks["app:build"],
3640                    &AtomicBool::new(false),
3641                )
3642                .unwrap()
3643            };
3644            let before = keys();
3645            std::fs::write(root.path().join("generated/value"), "different").unwrap();
3646            snapshot.outputs_written(&workspace, &graph.tasks["app:post"]);
3647            assert_ne!(before, keys());
3648        }
3649    }
3650
3651    #[cfg(unix)]
3652    #[test]
3653    fn dependency_symlinks_recheck_targets_outside_output_roots() {
3654        let (root, mut workspace, _) = fixture(Some(json!(["{projectRoot}/generated"])));
3655        workspace
3656            .projects
3657            .get_mut("app")
3658            .unwrap()
3659            .targets
3660            .get_mut("gen")
3661            .unwrap()
3662            .outputs = Some(vec!["{projectRoot}/links".into()]);
3663        std::fs::create_dir(root.path().join("links")).unwrap();
3664        std::os::unix::fs::symlink("../generated/value", root.path().join("links/value")).unwrap();
3665        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3666        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3667        let keys = || {
3668            dependency_keys(
3669                &snapshot,
3670                &workspace,
3671                &graph,
3672                &graph.tasks["app:build"],
3673                &AtomicBool::new(false),
3674            )
3675            .unwrap()
3676        };
3677        let before = keys();
3678        std::fs::write(root.path().join("generated/value"), "different").unwrap();
3679        snapshot.outputs_written(&workspace, &graph.tasks["app:post"]);
3680        assert_ne!(before["app:gen:**/*"], keys()["app:gen:**/*"]);
3681    }
3682    /// The digest of a git-ignored file an `includeIgnored` fileset reads is
3683    /// saved with the others, so a warm run does not read it again.
3684    #[test]
3685    fn digests_of_ignored_files_read_by_include_ignored_are_saved() {
3686        let root = tempfile::tempdir().unwrap();
3687        std::fs::write(root.path().join("nx.json"), "{}").unwrap();
3688        std::fs::write(root.path().join(".gitignore"), "generated/\n").unwrap();
3689        std::fs::write(
3690            root.path().join("project.json"),
3691            json!({"name": "app", "targets": {"build": {"command": "true", "inputs": [
3692                {"fileset": "{projectRoot}/generated/**/*", "includeIgnored": true}
3693            ]}}})
3694            .to_string(),
3695        )
3696        .unwrap();
3697        std::fs::create_dir(root.path().join("generated")).unwrap();
3698        std::fs::write(root.path().join("generated/schema.json"), "{}").unwrap();
3699        // Digests are only saved for files old enough to have settled.
3700        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
3701        std::fs::File::options()
3702            .write(true)
3703            .open(root.path().join("generated/schema.json"))
3704            .unwrap()
3705            .set_times(std::fs::FileTimes::new().set_modified(old))
3706            .unwrap();
3707        let git = |args: &[&str]| {
3708            assert!(
3709                std::process::Command::new("git")
3710                    .args(args)
3711                    .current_dir(root.path())
3712                    .output()
3713                    .unwrap()
3714                    .status
3715                    .success()
3716            )
3717        };
3718        git(&["init", "--quiet"]);
3719        let workspace = Workspace::load(root.path()).unwrap();
3720        let graph = TaskGraph::build(&workspace, &[Request::parse("app:build").unwrap()]).unwrap();
3721        let snapshot = Snapshot::new(&workspace, &graph, &root.path().join("cache")).unwrap();
3722        assert!(!snapshot.files.contains("generated/schema.json"));
3723        let prepared =
3724            qk_executor::prepare(&workspace, &graph.tasks["app:build"], &BTreeMap::new()).unwrap();
3725        inputs(
3726            &snapshot,
3727            &workspace,
3728            &graph.tasks["app:build"],
3729            &prepared,
3730            &BTreeMap::new(),
3731            &AtomicBool::new(false),
3732        )
3733        .unwrap();
3734        snapshot.save_digests(root.path());
3735        assert!(load_digests(root.path()).contains_key("generated/schema.json"));
3736    }
3737}