@mmerterden/multi-agent-pipeline 20.41.0 → 20.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +1 -1
  3. package/README.tr.md +1 -1
  4. package/docs/ecosystem.md +45 -8
  5. package/docs/facts.json +7 -7
  6. package/docs/features.md +9 -4
  7. package/install/claude.mjs +34 -1
  8. package/install/templates/claude-hooks.json +12 -1
  9. package/manifest.json +106 -86
  10. package/package.json +3 -2
  11. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  12. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  13. package/pipeline/lib/args.mjs +131 -4
  14. package/pipeline/lib/bg-launch.mjs +5 -2
  15. package/pipeline/lib/credential-store.sh +11 -1
  16. package/pipeline/lib/hook-once.mjs +134 -0
  17. package/pipeline/lib/isotonic.mjs +73 -0
  18. package/pipeline/lib/low-disk.mjs +153 -0
  19. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  20. package/pipeline/lib/md2confluence-v3.py +8 -7
  21. package/pipeline/lib/model-dispatch.sh +26 -2
  22. package/pipeline/lib/normalize-text.mjs +135 -0
  23. package/pipeline/lib/outbound-gate.mjs +21 -3
  24. package/pipeline/lib/plan-todos.sh +17 -4
  25. package/pipeline/lib/redact.mjs +12 -3
  26. package/pipeline/lib/risky-settings.mjs +198 -0
  27. package/pipeline/lib/route-state.sh +1 -0
  28. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  29. package/pipeline/lib/session-usage.mjs +232 -0
  30. package/pipeline/lib/source-digest.mjs +211 -0
  31. package/pipeline/lib/tdd-evidence.mjs +250 -17
  32. package/pipeline/lib/untrusted-fence.mjs +132 -1
  33. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  34. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  35. package/pipeline/multi-agent-refs/features/doctor.md +51 -4
  36. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  37. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  38. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  39. package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
  40. package/pipeline/multi-agent-refs/help/en.md +1 -1
  41. package/pipeline/multi-agent-refs/help/tr.md +1 -1
  42. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  43. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
  44. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  45. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  46. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  47. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  48. package/pipeline/office/toolkit.json +1 -1
  49. package/pipeline/rules/outside-the-pipeline.md +1 -1
  50. package/pipeline/schemas/doctor-report.schema.json +47 -0
  51. package/pipeline/schemas/plan-todos.schema.json +29 -1
  52. package/pipeline/schemas/prefs.schema.json +63 -0
  53. package/pipeline/schemas/route-config.schema.json +51 -0
  54. package/pipeline/schemas/secret-patterns.json +17 -1
  55. package/pipeline/schemas/toolkit-path-params.json +15 -1
  56. package/pipeline/scripts/_cost-advise.mjs +357 -0
  57. package/pipeline/scripts/_cost-budget.mjs +78 -0
  58. package/pipeline/scripts/_cost.mjs +29 -0
  59. package/pipeline/scripts/_decode_text.py +107 -0
  60. package/pipeline/scripts/_guard-probe.mjs +406 -0
  61. package/pipeline/scripts/_guard_rules.py +206 -0
  62. package/pipeline/scripts/_memory-policy.mjs +1 -25
  63. package/pipeline/scripts/_retrieval.mjs +148 -2
  64. package/pipeline/scripts/_secret-scan.mjs +6 -1
  65. package/pipeline/scripts/_stack-routing.mjs +1 -0
  66. package/pipeline/scripts/_test-gaming.mjs +346 -0
  67. package/pipeline/scripts/agent-guard.py +8 -1
  68. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  69. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  70. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  71. package/pipeline/scripts/capture-resume.sh +9 -1
  72. package/pipeline/scripts/cost-analyze.mjs +66 -4
  73. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  74. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  75. package/pipeline/scripts/doctor.mjs +169 -44
  76. package/pipeline/scripts/evidence-gate.mjs +90 -0
  77. package/pipeline/scripts/gate-ledger.mjs +76 -21
  78. package/pipeline/scripts/gc-tmp.sh +5 -0
  79. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  80. package/pipeline/scripts/learnings-ledger.mjs +16 -12
  81. package/pipeline/scripts/note-agent-event.mjs +2 -0
  82. package/pipeline/scripts/note-mcp-failure.mjs +9 -2
  83. package/pipeline/scripts/note-skill-use.mjs +4 -1
  84. package/pipeline/scripts/pre-commit-check.sh +2 -2
  85. package/pipeline/scripts/pre-push-check.sh +8 -1
  86. package/pipeline/scripts/publish-staged.mjs +324 -0
  87. package/pipeline/scripts/route-learn.mjs +628 -0
  88. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  89. package/pipeline/scripts/scan-agent-config.sh +1 -1
  90. package/pipeline/scripts/statusline.mjs +309 -0
  91. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  92. package/pipeline/scripts/triage-memory.mjs +12 -4
  93. package/pipeline/scripts/uninstall.mjs +1 -0
  94. package/pipeline/skills/.skill-manifest.json +8 -4
  95. package/pipeline/skills/.skills-index.json +14 -3
  96. package/pipeline/skills/shared/README.md +5 -4
  97. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  98. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  99. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  100. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  102. package/pipeline/skills/skill-copies.json +4 -0
  103. package/pipeline/skills/skills-index.md +3 -2
@@ -130,6 +130,7 @@ case "$ACTION" in
130
130
  echo "free: $FREE$([ "$FREE" = "true" ] && echo " (data policy: $([ "$TRAIN" = "true" ] && echo any || echo no-training))")"
131
131
  echo "ceiling: $CEIL"
132
132
  echo "decisions: $REC"
133
+ echo "learned: $(jq -r '.global.modelRouting.learned.enabled // false' "$PREFS")"
133
134
  echo ""
134
135
 
135
136
  if [ "$ENABLED" != "true" ]; then
@@ -232,10 +232,14 @@ export const SECRET_PATTERNS = [
232
232
  id: "url-with-credentials",
233
233
  label: "URL with embedded credentials",
234
234
  kind: "context",
235
- re: /\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:[^\s/@]+@/g,
235
+ re: /\b[a-z][a-z0-9+.-]{0,31}:\/\/[^\s/:@]{1,255}:[^\s/@]+@/g,
236
236
  lead: null,
237
237
  blockEnd: null,
238
- samples: [["https://user:", "s", 12, "@example.com/x.git"]],
238
+ samples: [
239
+ ["https://user:", "s", 12, "@example.com/x.git"],
240
+ ["https://user:", "s", 300, "@example.com/x.git"],
241
+ ["https://user:", "s", 2000, "@example.com/x.git"],
242
+ ],
239
243
  },
240
244
  {
241
245
  id: "bearer-header",
@@ -21,18 +21,42 @@
21
21
  * from the end of each file; a file cut that way is reported `truncated`,
22
22
  * so an undercount is visible rather than silent.
23
23
  *
24
+ * Codex CLI keeps its own ledger: `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`
25
+ * (and `archived_sessions/`), where `event_msg` / `token_count` events carry a
26
+ * RUNNING total (`info.total_token_usage`) and `turn_context` names the model.
27
+ * `codexUsageSince` sums the deltas between consecutive totals; a total that
28
+ * goes down is a reset (compaction or a new thread) and starts a fresh base
29
+ * rather than producing a negative delta. Cached input is a subset of
30
+ * `input_tokens`, so fresh input is the difference; reasoning tokens are part
31
+ * of `output_tokens` and are not added twice. A forked rollout replays its
32
+ * parent's events, so an event counts once per (session, time, totals). A
33
+ * Codex home with rollouts but no event in that shape is reported as an
34
+ * unrecognized format, UNMEASURED rather than zero.
35
+ *
24
36
  * Prices come from cost-table.json through _cost.mjs. Cache writes are priced
25
37
  * by lifetime: `usage.cache_creation` splits them into 1h writes (2x input)
26
38
  * and 5m writes (1.25x input); a write the split does not cover prices at
27
39
  * 1.25x. The result is an estimate at list price and says so.
28
40
  *
41
+ * Run directly it prints one window's usage:
42
+ *
43
+ * session-usage.mjs [--host claude|codex] [--since <ISO> | --days N] [--json]
44
+ *
45
+ * `--host claude` (the default) reads `~/.claude/projects`; `--host codex`
46
+ * reads `$CODEX_HOME` or `~/.codex`. The window defaults to today. A host that
47
+ * cannot be read prints UNMEASURED and exits 0; a usage error exits 2.
48
+ *
29
49
  * @module pipeline/lib/session-usage
30
50
  */
31
51
 
32
52
  import { closeSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
53
+ import { homedir } from "node:os";
33
54
  import { basename, dirname, join } from "node:path";
34
55
 
35
56
  import { modelRateLookup, priceUsage } from "../scripts/_cost.mjs";
57
+ import { ArgsError, parseArgs, unknownSubcommand } from "./args.mjs";
58
+ import { exitOnHelp } from "./cli-help.mjs";
59
+ import { invokedDirectly } from "./invoked-directly.mjs";
36
60
 
37
61
  export const DEFAULT_MAX_BYTES = 64 * 1024 * 1024;
38
62
  const CHUNK = 1024 * 1024;
@@ -386,3 +410,211 @@ export function createUsageCache({ maxBytes = DEFAULT_MAX_BYTES } = {}) {
386
410
  },
387
411
  };
388
412
  }
413
+
414
+ const CODEX_FIELDS = ["input_tokens", "cached_input_tokens", "output_tokens"];
415
+
416
+ /** Every `rollout-*.jsonl` under a Codex home, active sessions before archived. */
417
+ function codexRollouts(home) {
418
+ const out = [];
419
+ const walk = (dir, depth) => {
420
+ for (const e of listDir(dir)) {
421
+ const p = join(dir, e.name);
422
+ if (e.isDirectory() && depth > 0) walk(p, depth - 1);
423
+ else if (e.isFile() && e.name.startsWith("rollout-") && e.name.endsWith(".jsonl"))
424
+ out.push(p);
425
+ }
426
+ };
427
+ for (const sub of ["sessions", "archived_sessions"]) {
428
+ const before = out.length;
429
+ walk(join(home, sub), 4);
430
+ const added = out.splice(before).sort();
431
+ out.push(...added);
432
+ }
433
+ return out;
434
+ }
435
+
436
+ /**
437
+ * Codex CLI usage of every token_count event stamped at or after `since`.
438
+ *
439
+ * @param {string} home the Codex home, `$CODEX_HOME` or `~/.codex`
440
+ * @param {{since?: number}} [opts]
441
+ */
442
+ export function codexUsageSince(home, { since = 0 } = {}) {
443
+ const models = emptyModels();
444
+ const result = (extra) => {
445
+ const priced = priceModels(models);
446
+ return {
447
+ host: "codex",
448
+ since: new Date(since).toISOString(),
449
+ models,
450
+ totals: sumModels(models),
451
+ usd: priced.usd,
452
+ unpricedModels: priced.unpricedModels,
453
+ estimated: true,
454
+ ...extra,
455
+ };
456
+ };
457
+ let files;
458
+ try {
459
+ statSync(home);
460
+ files = codexRollouts(home);
461
+ } catch {
462
+ return result({
463
+ measured: false,
464
+ format: "absent",
465
+ reason: `no Codex home at ${home}`,
466
+ files: 0,
467
+ malformed: 0,
468
+ resets: 0,
469
+ });
470
+ }
471
+ const seenFiles = new Set();
472
+ const seenEvents = new Set();
473
+ let read = 0;
474
+ let events = 0;
475
+ let malformed = 0;
476
+ let resets = 0;
477
+ for (const path of files) {
478
+ const id = basename(path);
479
+ if (seenFiles.has(id)) continue;
480
+ seenFiles.add(id);
481
+ let model = "";
482
+ let session = id;
483
+ let prev = null;
484
+ try {
485
+ eachLine(path, 0, (text) => {
486
+ if (
487
+ !text.includes('"token_count"') &&
488
+ !text.includes('"turn_context"') &&
489
+ !text.includes('"session_meta"')
490
+ )
491
+ return;
492
+ let line;
493
+ try {
494
+ line = JSON.parse(text);
495
+ } catch {
496
+ malformed += 1;
497
+ return;
498
+ }
499
+ const payload = line?.payload;
500
+ if (line?.type === "session_meta") {
501
+ if (typeof payload?.id === "string" && payload.id) session = payload.id;
502
+ return;
503
+ }
504
+ if (line?.type === "turn_context") {
505
+ if (typeof payload?.model === "string") model = payload.model;
506
+ return;
507
+ }
508
+ const total = payload?.type === "token_count" ? payload.info?.total_token_usage : null;
509
+ if (!total || typeof total !== "object") return;
510
+ events += 1;
511
+ const reset = prev !== null && CODEX_FIELDS.some((f) => tokens(total[f]) < tokens(prev[f]));
512
+ if (reset) resets += 1;
513
+ const delta = {};
514
+ for (const f of CODEX_FIELDS)
515
+ delta[f] = tokens(total[f]) - (prev && !reset ? tokens(prev[f]) : 0);
516
+ prev = total;
517
+ if (CODEX_FIELDS.every((f) => delta[f] === 0)) return;
518
+ const t = Date.parse(line.timestamp);
519
+ if (!Number.isFinite(t) || (since > 0 && t < since)) return;
520
+ const key = JSON.stringify([
521
+ session,
522
+ line.timestamp,
523
+ ...CODEX_FIELDS.map((f) => tokens(total[f])),
524
+ ]);
525
+ if (seenEvents.has(key)) return;
526
+ seenEvents.add(key);
527
+ const name = MODEL_ID.test(model) ? model : "unknown";
528
+ const m = (models[name] ??= emptyModel());
529
+ const cached = Math.min(delta.cached_input_tokens, delta.input_tokens);
530
+ m.input += delta.input_tokens - cached;
531
+ m.cacheRead += cached;
532
+ m.output += delta.output_tokens;
533
+ m.messages += 1;
534
+ });
535
+ read += 1;
536
+ } catch {
537
+ /* unreadable rollout: counted by its absence from `files` */
538
+ }
539
+ }
540
+ if (read > 0 && events === 0) {
541
+ return result({
542
+ measured: false,
543
+ format: "unrecognized",
544
+ reason: `${read} rollout(s) under ${home} carry no token_count event in the expected shape`,
545
+ files: read,
546
+ malformed,
547
+ resets,
548
+ });
549
+ }
550
+ if (read === 0) {
551
+ return result({
552
+ measured: false,
553
+ format: "absent",
554
+ reason: `no Codex rollouts under ${home}`,
555
+ files: 0,
556
+ malformed,
557
+ resets,
558
+ });
559
+ }
560
+ return result({ measured: true, format: "rollout", files: read, malformed, resets });
561
+ }
562
+
563
+ const HOSTS = ["claude", "codex"];
564
+
565
+ function cli(argv, env) {
566
+ const { flags } = parseArgs(argv, {
567
+ unknown: "error",
568
+ booleans: ["json"],
569
+ strings: ["host", "since", "days"],
570
+ positionals: false,
571
+ });
572
+ const host = flags.host ?? "claude";
573
+ if (!HOSTS.includes(host)) throw unknownSubcommand(host, HOSTS);
574
+ let since = startOfLocalDay();
575
+ if (flags.since !== undefined) {
576
+ since = Date.parse(flags.since);
577
+ if (!Number.isFinite(since))
578
+ throw new ArgsError(`--since takes an ISO date`, { kind: "unexpected", token: flags.since });
579
+ } else if (flags.days !== undefined) {
580
+ const days = Number(flags.days);
581
+ if (!(days > 0))
582
+ throw new ArgsError(`--days takes a positive number`, {
583
+ kind: "unexpected",
584
+ token: flags.days,
585
+ });
586
+ since = Date.now() - days * 86_400_000;
587
+ }
588
+ const home = env.HOME || homedir();
589
+ const out =
590
+ host === "codex"
591
+ ? codexUsageSince(env.CODEX_HOME || join(home, ".codex"), { since })
592
+ : {
593
+ host: "claude",
594
+ measured: true,
595
+ ...usageSince(join(home, ".claude", "projects"), { since }),
596
+ };
597
+ if (host === "claude" && out.files === 0) {
598
+ out.measured = false;
599
+ out.reason = `no transcripts under ${join(home, ".claude", "projects")}`;
600
+ }
601
+ if (flags.json) return `${JSON.stringify(out, null, 2)}\n`;
602
+ if (!out.measured) return `UNMEASURED: ${out.reason}\n`;
603
+ const t = out.totals;
604
+ return (
605
+ `${host} since ${out.since}: in ${t.input} + cached ${t.cacheRead} + written ${t.cacheCreation}, out ${t.output}, ${t.messages} turns, ~$${out.usd.toFixed(2)} (estimate)` +
606
+ (out.unpricedModels.length ? `\n unpriced: ${out.unpricedModels.join(", ")}` : "") +
607
+ "\n"
608
+ );
609
+ }
610
+
611
+ if (invokedDirectly(import.meta.url)) {
612
+ exitOnHelp(import.meta.url);
613
+ try {
614
+ process.stdout.write(cli(process.argv.slice(2), process.env));
615
+ } catch (e) {
616
+ if (!(e instanceof ArgsError)) throw e;
617
+ process.stderr.write(`session-usage: ${e.message}\n`);
618
+ process.exitCode = 2;
619
+ }
620
+ }
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * source-digest.mjs - one sha256 over the source a working tree holds right
4
+ * now, committed or not.
5
+ *
6
+ * Build and test evidence is recorded before Phase 4 commits anything, so the
7
+ * HEAD a gate records says nothing about an edit made after the build. This
8
+ * digest does: it covers every tracked file as it is on disk and every
9
+ * untracked file git does not ignore, so an edit, a new file or a deletion
10
+ * after the evidence changes it, and undoing the edit brings it back.
11
+ * Committing the same content leaves it unchanged, so a checkpoint commit does
12
+ * not age the evidence.
13
+ *
14
+ * How it stays cheap on a large repository:
15
+ * - unchanged tracked files are named by the blob id the index already holds
16
+ * (`git ls-files -s`); nothing is read for them;
17
+ * - only modified and untracked files are hashed, by `git hash-object
18
+ * --stdin-paths`, which streams each file and applies the same clean
19
+ * filters the index used, so an unmodified file and a re-saved one agree;
20
+ * - hashing stops at `maxFiles` files or `maxBytes` bytes; past the cap a
21
+ * file is named by its size and mtime, which still changes on an edit,
22
+ * and the result says `capped: true`;
23
+ * - every git call has `timeoutMs`; a call that fails or times out makes the
24
+ * digest null, which callers read as "cannot tell", never as a match.
25
+ *
26
+ * Ignore rules are git's own (`--exclude-standard`). The pipeline's own
27
+ * output inside a worktree is left out too, because it is written after the
28
+ * build it describes: untracked `*.log` files, `*.xcresult` bundles and the
29
+ * `.pipeline/`, `.multi-agent/` and `.claude/` directories.
30
+ *
31
+ * A submodule is named by the commit its checkout is on, plus `dirty` when
32
+ * its own tree has changes.
33
+ *
34
+ * CLI: source-digest.mjs [--repo <dir>] [--json]
35
+ * prints the digest (or the whole result with --json); exit 3 when <dir> is
36
+ * not in a git work tree or git could not answer.
37
+ *
38
+ * Zero runtime dependencies (ADR-0004).
39
+ *
40
+ * @module pipeline/lib/source-digest
41
+ */
42
+
43
+ import { spawnSync } from "node:child_process";
44
+ import { createHash } from "node:crypto";
45
+ import { lstatSync, readlinkSync } from "node:fs";
46
+ import { join } from "node:path";
47
+
48
+ import { invokedDirectly } from "./invoked-directly.mjs";
49
+ import { parseArgs } from "./args.mjs";
50
+
51
+ export const DIGEST_LIMITS = Object.freeze({
52
+ maxFiles: 5000,
53
+ maxBytes: 256 * 1024 * 1024,
54
+ timeoutMs: 20000,
55
+ });
56
+
57
+ const ARTEFACT = /(?:^|\/)(?:\.pipeline|\.multi-agent|\.claude)\/|\.log$|\.xcresult(?:\/|$)/;
58
+
59
+ /** Whether an untracked path is the pipeline's own output rather than source. */
60
+ export function isPipelineArtefact(path) {
61
+ return ARTEFACT.test(path);
62
+ }
63
+
64
+ function git(cwd, args, { timeoutMs, input } = {}) {
65
+ const r = spawnSync("git", ["-C", cwd, ...args], {
66
+ encoding: "utf8",
67
+ timeout: timeoutMs,
68
+ maxBuffer: 1024 * 1024 * 1024,
69
+ input,
70
+ });
71
+ if (r.status !== 0 || r.error) return null;
72
+ return r.stdout;
73
+ }
74
+
75
+ const nulList = (out) => (out ? out.split("\0").filter(Boolean) : []);
76
+
77
+ function statOf(path) {
78
+ try {
79
+ return lstatSync(path);
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ function submoduleToken(root, path, timeoutMs) {
86
+ const dir = join(root, path);
87
+ const head = git(dir, ["rev-parse", "HEAD"], { timeoutMs });
88
+ if (head === null) return "gitlink:absent";
89
+ const dirty = git(dir, ["status", "--porcelain", "--untracked-files=no"], { timeoutMs });
90
+ return `gitlink:${head.trim()}${dirty && dirty.trim() ? ":dirty" : ""}`;
91
+ }
92
+
93
+ /**
94
+ * The digest of the working tree `dir` is in, or null when it is not in one
95
+ * or git could not answer in time.
96
+ *
97
+ * @param {string} dir
98
+ * @param {{maxFiles?: number, maxBytes?: number, timeoutMs?: number}} [opts]
99
+ * @returns {null | {digest: string, root: string, files: number, hashed: number,
100
+ * statOnly: number, capped: boolean, newestEditMs: number, ms: number}}
101
+ */
102
+ export function sourceDigest(dir, opts = {}) {
103
+ const { maxFiles, maxBytes, timeoutMs } = { ...DIGEST_LIMITS, ...opts };
104
+ const started = Date.now();
105
+ const top = git(dir, ["rev-parse", "--show-toplevel"], { timeoutMs });
106
+ if (top === null) return null;
107
+ const root = top.trim();
108
+
109
+ const staged = git(root, ["ls-files", "-s", "-z"], { timeoutMs });
110
+ const modifiedOut = git(root, ["ls-files", "-m", "-z"], { timeoutMs });
111
+ const deletedOut = git(root, ["ls-files", "-d", "-z"], { timeoutMs });
112
+ const untrackedOut = git(root, ["ls-files", "-o", "--exclude-standard", "-z"], { timeoutMs });
113
+ if (staged === null || modifiedOut === null || deletedOut === null || untrackedOut === null) {
114
+ return null;
115
+ }
116
+
117
+ const tokens = new Map();
118
+ const gitlinks = new Set();
119
+ for (const rec of nulList(staged)) {
120
+ const tab = rec.indexOf("\t");
121
+ const [mode, sha, stage] = rec.slice(0, tab).split(" ");
122
+ const path = rec.slice(tab + 1);
123
+ if (stage !== "0" && tokens.has(path)) continue;
124
+ if (mode === "160000") gitlinks.add(path);
125
+ tokens.set(path, `${mode}:${sha}`);
126
+ }
127
+ const deleted = new Set(nulList(deletedOut));
128
+ const toHash = [];
129
+ for (const path of nulList(modifiedOut)) {
130
+ if (deleted.has(path)) continue;
131
+ if (gitlinks.has(path)) tokens.set(path, submoduleToken(root, path, timeoutMs));
132
+ else toHash.push(path);
133
+ }
134
+ for (const path of deleted) tokens.set(path, "deleted");
135
+ for (const path of nulList(untrackedOut)) {
136
+ if (!isPipelineArtefact(path)) toHash.push(path);
137
+ }
138
+
139
+ let hashedBytes = 0;
140
+ let newestEditMs = 0;
141
+ let capped = false;
142
+ const hashList = [];
143
+ for (const path of toHash) {
144
+ const st = statOf(join(root, path));
145
+ if (!st) {
146
+ tokens.set(path, "deleted");
147
+ continue;
148
+ }
149
+ newestEditMs = Math.max(newestEditMs, st.mtimeMs);
150
+ if (st.isSymbolicLink()) {
151
+ let target;
152
+ try {
153
+ target = readlinkSync(join(root, path));
154
+ } catch {
155
+ target = "?";
156
+ }
157
+ tokens.set(path, `link:${target}`);
158
+ continue;
159
+ }
160
+ if (!st.isFile()) {
161
+ tokens.set(path, `other:${st.mode}`);
162
+ continue;
163
+ }
164
+ const fits = hashList.length < maxFiles && hashedBytes + st.size <= maxBytes;
165
+ if (!fits || path.includes("\n")) {
166
+ if (!path.includes("\n")) capped = true;
167
+ tokens.set(path, `stat:${st.size}:${Math.trunc(st.mtimeMs)}`);
168
+ continue;
169
+ }
170
+ hashedBytes += st.size;
171
+ hashList.push(path);
172
+ }
173
+ if (hashList.length) {
174
+ const out = git(root, ["hash-object", "--stdin-paths"], {
175
+ timeoutMs,
176
+ input: `${hashList.join("\n")}\n`,
177
+ });
178
+ if (out === null) return null;
179
+ const shas = out.trim().split("\n");
180
+ if (shas.length !== hashList.length) return null;
181
+ hashList.forEach((path, i) => tokens.set(path, `blob:${shas[i]}`));
182
+ }
183
+
184
+ const hash = createHash("sha256");
185
+ let statOnly = 0;
186
+ for (const path of [...tokens.keys()].sort()) {
187
+ const token = tokens.get(path);
188
+ if (token.startsWith("stat:")) statOnly++;
189
+ hash.update(`${path}\0${token.replace(/^(?:100644|100755):/, "blob:")}\n`);
190
+ }
191
+ return {
192
+ digest: `sha256:${hash.digest("hex")}`,
193
+ root,
194
+ files: tokens.size,
195
+ hashed: hashList.length,
196
+ statOnly,
197
+ capped,
198
+ newestEditMs,
199
+ ms: Date.now() - started,
200
+ };
201
+ }
202
+
203
+ if (invokedDirectly(import.meta.url)) {
204
+ const { flags } = parseArgs(process.argv.slice(2), { booleans: ["json"] });
205
+ const r = sourceDigest(typeof flags.repo === "string" ? flags.repo : process.cwd());
206
+ if (!r) {
207
+ process.stderr.write("source-digest: not a git work tree, or git did not answer in time\n");
208
+ process.exit(3);
209
+ }
210
+ process.stdout.write(flags.json ? `${JSON.stringify(r)}\n` : `${r.digest}\n`);
211
+ }