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