@juicesharp/rpiv-workflow 2.1.0 → 2.2.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.
- package/audit-ctx.ts +9 -1
- package/audit-rows.ts +10 -0
- package/audit.ts +22 -0
- package/chain-state.ts +15 -1
- package/death-scene.ts +232 -0
- package/docs/embedding.md +1 -1
- package/events.ts +2 -26
- package/execution-host.ts +9 -0
- package/failure-memos.ts +74 -0
- package/host.ts +12 -0
- package/internal.ts +1 -0
- package/loop-def.ts +8 -4
- package/loop-kinds.ts +4 -1
- package/loop-parallel.ts +107 -86
- package/loop.ts +16 -15
- package/messages.ts +26 -0
- package/package.json +5 -2
- package/registration.ts +5 -0
- package/routing.ts +0 -40
- package/runner/chain-advance.ts +3 -9
- package/runner/run-context.ts +13 -3
- package/runner/run-stage.ts +71 -2
- package/runner/runner.ts +15 -5
- package/sessions/bash-strikes.ts +182 -0
- package/sessions/extraction.ts +32 -25
- package/sessions/halt-routing.ts +5 -0
- package/sessions/sessions.ts +39 -1
- package/sessions/success-persist.ts +6 -0
- package/stage-identity.ts +43 -4
- package/state/state.ts +10 -0
- package/transcript.ts +30 -0
- package/types.ts +96 -6
- package/worktree-digest.ts +148 -0
package/state/state.ts
CHANGED
|
@@ -109,6 +109,16 @@ export interface WorkflowStage {
|
|
|
109
109
|
* JSONL alone, without depending on a transient `ctx.ui.notify` toast.
|
|
110
110
|
*/
|
|
111
111
|
errMsg?: string;
|
|
112
|
+
/**
|
|
113
|
+
* Strike-history observability — present ONLY on a `status: "completed"`
|
|
114
|
+
* row whose session recovered from one or more bash overruns: `count` is the
|
|
115
|
+
* strikes consumed, `reasons` lists each consumed strike's host reason. An
|
|
116
|
+
* ADDITIVE optional field (NOT a new row kind): absent ⇒ `JSON.stringify`
|
|
117
|
+
* drops it ⇒ byte-identical row to pre-feature; the resume fold's
|
|
118
|
+
* shape-filtered readers ignore it (like `errMsg`), so no
|
|
119
|
+
* `STATE_SCHEMA_VERSION` bump.
|
|
120
|
+
*/
|
|
121
|
+
bashTimeoutStrikes?: { count: number; reasons: string[] };
|
|
112
122
|
/**
|
|
113
123
|
* REQUIRED: the Pi session that backed this activation, or `null` as an
|
|
114
124
|
* explicit statement that no session was involved (script stages,
|
package/transcript.ts
CHANGED
|
@@ -114,6 +114,36 @@ export function lastAssistantStopReason(branch: BranchEntry[], offsetStart?: num
|
|
|
114
114
|
return undefined;
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
+
/**
|
|
118
|
+
* The concatenated `text` parts of the LAST assistant message in `branch`
|
|
119
|
+
* (reverse scan — the agent's final spoken turn is usually the actionable
|
|
120
|
+
* one), trimmed; `undefined` when the branch has no assistant message or its
|
|
121
|
+
* text parts are empty/absent. Pure — no I/O.
|
|
122
|
+
*
|
|
123
|
+
* Mirrors `lastAssistantStopReason` (`:106`) but joins the message's `text`
|
|
124
|
+
* parts instead of reading its stop reason. Used by the death-scene artifact
|
|
125
|
+
* writer (`death-scene.ts`) to capture the agent's final words at failure time.
|
|
126
|
+
* `offsetStart` — continue-policy stages pass the prior branch length so
|
|
127
|
+
* prior-stage entries don't leak into the result.
|
|
128
|
+
*/
|
|
129
|
+
export function lastAssistantText(branch: BranchEntry[], offsetStart?: number): string | undefined {
|
|
130
|
+
const start = Math.max(offsetStart ?? 0, 0);
|
|
131
|
+
for (let i = branch.length - 1; i >= start; i--) {
|
|
132
|
+
const entry = branch[i]!;
|
|
133
|
+
if (entry.type !== "message") continue;
|
|
134
|
+
if (entry.message?.role !== "assistant") continue;
|
|
135
|
+
const content = entry.message.content;
|
|
136
|
+
if (!Array.isArray(content)) return undefined;
|
|
137
|
+
const text = content
|
|
138
|
+
.filter((part) => part.type === "text" && typeof part.text === "string")
|
|
139
|
+
.map((part) => part.text!)
|
|
140
|
+
.join("\n")
|
|
141
|
+
.trim();
|
|
142
|
+
return text.length > 0 ? text : undefined;
|
|
143
|
+
}
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
|
|
117
147
|
// ---------------------------------------------------------------------------
|
|
118
148
|
// Shared collector building blocks
|
|
119
149
|
// ---------------------------------------------------------------------------
|
package/types.ts
CHANGED
|
@@ -30,6 +30,7 @@ import type { ModelSelection, WorkflowHost, WorkflowHostContext } from "./host.j
|
|
|
30
30
|
import type { Output } from "./output.js";
|
|
31
31
|
import type { SkillContractMap } from "./skill-contract.js";
|
|
32
32
|
import type { SessionRef } from "./state/index.js";
|
|
33
|
+
import type { BranchEntry } from "./transcript.js";
|
|
33
34
|
import type { RunTrigger } from "./triggers.js";
|
|
34
35
|
|
|
35
36
|
// Re-export the host port so runtime layers can pull `RunContext`,
|
|
@@ -95,6 +96,17 @@ export interface RunState {
|
|
|
95
96
|
*/
|
|
96
97
|
lastSession?: SessionRef;
|
|
97
98
|
|
|
99
|
+
/**
|
|
100
|
+
* Validation-retry gate memory — the digest captured the last time a
|
|
101
|
+
* schema-validated produces stage was dispatched, keyed with the stage name
|
|
102
|
+
* + `stagesCompleted` at capture. TRANSIENT: not persisted to JSONL (the
|
|
103
|
+
* resume fold reconstructs `RunState` from rows, not from a serialized
|
|
104
|
+
* blob), so operator resume starts with a fresh gate — matching the
|
|
105
|
+
* fresh-strike-budget policy. `undefined` until a qualifying stage is
|
|
106
|
+
* dispatched (the gate's no-regression short-circuit).
|
|
107
|
+
*/
|
|
108
|
+
lastGatedDispatch?: { stage: string; digest: string; stagesCompleted: number };
|
|
109
|
+
|
|
98
110
|
// ── Telemetry (post-hoc only; not consulted by chain advancement) ──
|
|
99
111
|
telemetry: {
|
|
100
112
|
/**
|
|
@@ -123,6 +135,18 @@ export interface RunState {
|
|
|
123
135
|
droppedFailureRows: string[];
|
|
124
136
|
};
|
|
125
137
|
|
|
138
|
+
// ── Failure memos (consumed by chain advancement — next prompt) ─────
|
|
139
|
+
/**
|
|
140
|
+
* Bounded log of stage/unit failures this run has already incurred,
|
|
141
|
+
* surfaced as an additive prompt suffix on every subsequently-built
|
|
142
|
+
* stage/unit session via `failureMemoSuffix`. Empty on a clean run ⇒ the
|
|
143
|
+
* suffix is `""` ⇒ byte-identical prompt. Capped at `MAX_FAILURE_MEMOS`
|
|
144
|
+
* (oldest dropped); each entry's `errMsg` is length-bounded. NOT telemetry:
|
|
145
|
+
* it is mutable bookkeeping the next agent's prompt reads, so it sits
|
|
146
|
+
* between the telemetry block and `termination`.
|
|
147
|
+
*/
|
|
148
|
+
failureMemos: FailureMemo[];
|
|
149
|
+
|
|
126
150
|
// ── Termination (set once at end-of-run) ───────────────────────────
|
|
127
151
|
/**
|
|
128
152
|
* How the run ended — `"running"` until the single end-of-run write via
|
|
@@ -156,6 +180,21 @@ export type RunTermination =
|
|
|
156
180
|
| { status: "aborted"; error: string }
|
|
157
181
|
| { status: "cancelled"; error: string };
|
|
158
182
|
|
|
183
|
+
/**
|
|
184
|
+
* One entry in `RunState.failureMemos` — a bounded record of a stage/unit
|
|
185
|
+
* failure this run has already incurred, surfaced to the next agent's prompt
|
|
186
|
+
* as an additive suffix so the run does not repeat a dead end. `stage` is the
|
|
187
|
+
* machine identity (a loop unit's parent, or the audit `stageName` for a
|
|
188
|
+
* non-unit failure); `unitId` is set only for a loop-unit failure (the unit's
|
|
189
|
+
* stable audit id). `ts` is an ISO-8601 timestamp.
|
|
190
|
+
*/
|
|
191
|
+
export interface FailureMemo {
|
|
192
|
+
stage: string;
|
|
193
|
+
unitId?: string;
|
|
194
|
+
errMsg: string;
|
|
195
|
+
ts: string;
|
|
196
|
+
}
|
|
197
|
+
|
|
159
198
|
// ---------------------------------------------------------------------------
|
|
160
199
|
// Public run envelope — options in, result out
|
|
161
200
|
// ---------------------------------------------------------------------------
|
|
@@ -204,6 +243,12 @@ export interface RunWorkflowOptions {
|
|
|
204
243
|
* at child-session creation. Undefined ⇒ host default for every stage.
|
|
205
244
|
*/
|
|
206
245
|
resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
|
|
246
|
+
/**
|
|
247
|
+
* Worktree-digest override for the validation-retry gate — threaded
|
|
248
|
+
* onto `RunContext.worktreeDigest` → every `StageSession.worktreeDigest`.
|
|
249
|
+
* Undefined ⇒ the built-in `computeWorktreeDigest` (git + artifacts).
|
|
250
|
+
*/
|
|
251
|
+
worktreeDigest?: (cwd: string) => string | undefined;
|
|
207
252
|
/**
|
|
208
253
|
* Human-readable alias for this run. Stored in the JSONL header and the
|
|
209
254
|
* sidecar names.json index. Rejected if already in use — the error
|
|
@@ -271,12 +316,10 @@ export interface RunContext {
|
|
|
271
316
|
runId: string;
|
|
272
317
|
workflow: Workflow;
|
|
273
318
|
/**
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
278
|
-
* (e.g. the lane-dock `visited/totalStages` progress bar); the numerator is
|
|
279
|
-
* the live stage index.
|
|
319
|
+
* Count of stages reachable from `workflow.start`, computed once at run
|
|
320
|
+
* start. The actual stage count is path-dependent (a predicate edge may
|
|
321
|
+
* short-circuit); surfaced as run metadata through the lifecycle
|
|
322
|
+
* `LifecycleContext.totalStages`.
|
|
280
323
|
*/
|
|
281
324
|
totalStages: number;
|
|
282
325
|
state: RunState;
|
|
@@ -331,6 +374,26 @@ export interface RunContext {
|
|
|
331
374
|
* creation (NOT via global mutation). Undefined ⇒ host default.
|
|
332
375
|
*/
|
|
333
376
|
resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
|
|
377
|
+
/**
|
|
378
|
+
* Host-injected reader that re-opens a persisted child-session JSONL and
|
|
379
|
+
* returns its branch (`SessionManager.open(file).getBranch()` on the rpiv-pi
|
|
380
|
+
* side, narrowed to `BranchEntry[]`). Consumed by the death-scene artifact
|
|
381
|
+
* writer at failure time (death-scene.ts) — the ONLY reader. Undefined for
|
|
382
|
+
* programmatic embedders / no provider, in which case the writer degrades
|
|
383
|
+
* silently (no artifact, no warning). Threaded provider → executor →
|
|
384
|
+
* `RunContext` → `SessionContext` → `AuditCtx` → `auditFor`.
|
|
385
|
+
*/
|
|
386
|
+
readSessionBranch?: (file: string) => BranchEntry[] | undefined;
|
|
387
|
+
/**
|
|
388
|
+
* Worktree-digest resolver injected by the embedder (tests / programmatic
|
|
389
|
+
* embedders that want to stub the filesystem). Threaded onto every
|
|
390
|
+
* `StageSession.worktreeDigest` and read by the validation-retry gate
|
|
391
|
+
* (`packages/rpiv-workflow/sessions/extraction.ts` mechanism-1 +
|
|
392
|
+
* `packages/rpiv-workflow/runner/run-stage.ts` mechanism-2) via
|
|
393
|
+
* `resolveDigest` (`worktree-digest.ts`). Undefined ⇒ the built-in
|
|
394
|
+
* `computeWorktreeDigest` (git + `.rpiv/artifacts/` recipe).
|
|
395
|
+
*/
|
|
396
|
+
worktreeDigest?: (cwd: string) => string | undefined;
|
|
334
397
|
maxBackwardJumps: number;
|
|
335
398
|
/**
|
|
336
399
|
* Run-wide safety cap on loop units — clamps the effective cap of EVERY
|
|
@@ -398,6 +461,15 @@ export interface SessionContext {
|
|
|
398
461
|
* output production; pre-output halts allocate at record time instead.
|
|
399
462
|
*/
|
|
400
463
|
allocatedStageNumber?: number;
|
|
464
|
+
/**
|
|
465
|
+
* Host-injected persisted-session branch reader, threaded from
|
|
466
|
+
* `RunContext.readSessionBranch`. Read by the death-scene artifact writer
|
|
467
|
+
* (`writeDeathSceneArtifact`) via `AuditCtx`; absent for programmatic
|
|
468
|
+
* embedders (the writer degrades silently). Travels FURTHER than
|
|
469
|
+
* `resolveModel` — into `SessionContext` → `AuditCtx` → `auditFor` —
|
|
470
|
+
* because the writer reads it from `AuditCtx` at failure time.
|
|
471
|
+
*/
|
|
472
|
+
readSessionBranch?: (file: string) => BranchEntry[] | undefined;
|
|
401
473
|
}
|
|
402
474
|
|
|
403
475
|
/**
|
|
@@ -438,6 +510,13 @@ export interface StageSession extends SessionContext {
|
|
|
438
510
|
* ⇒ host default.
|
|
439
511
|
*/
|
|
440
512
|
model?: ModelSelection;
|
|
513
|
+
/**
|
|
514
|
+
* Worktree-digest resolver threaded from `RunContext.worktreeDigest` — read
|
|
515
|
+
* by the validation-retry mechanism-1 gate in `packages/rpiv-workflow/sessions/extraction.ts`
|
|
516
|
+
* (`resolveDigest(s.worktreeDigest, s.cwd)`). Undefined ⇒ built-in git +
|
|
517
|
+
* artifacts recipe.
|
|
518
|
+
*/
|
|
519
|
+
worktreeDigest?: (cwd: string) => string | undefined;
|
|
441
520
|
/**
|
|
442
521
|
* Per-child cooperative-abort signal. Threaded from `RunContext.signal` (the
|
|
443
522
|
* fanout dispatcher narrows it to a per-generation controller) so
|
|
@@ -465,6 +544,17 @@ export interface StageSession extends SessionContext {
|
|
|
465
544
|
laneUnitIndex?: number;
|
|
466
545
|
/** Only set for continue stages — branch slice offset. */
|
|
467
546
|
branchOffset?: number;
|
|
547
|
+
/**
|
|
548
|
+
* Per-activation bash-overrun strike-ceiling override (testability) —
|
|
549
|
+
* `undefined` ⇒ the `BASH_TIMEOUT_STRIKES` module default. Pin to `0` in a
|
|
550
|
+
* watchdog-contract test to force immediate exhaustion; pin to `N` to drive
|
|
551
|
+
* a multi-strike recovery without mutating env. Now the SOLE strike surface
|
|
552
|
+
* on `StageSession`: the mutable accounting (used counter + reasons
|
|
553
|
+
* accumulator) lives in the private `StrikeBudget` value object held in
|
|
554
|
+
* `sessions/bash-strikes.ts`, keyed off this session (read once at first
|
|
555
|
+
* consume to resolve the budget's ceiling). Immutable per-activation.
|
|
556
|
+
*/
|
|
557
|
+
bashTimeoutStrikes?: number;
|
|
468
558
|
/**
|
|
469
559
|
* Present iff this session IS one loop unit. Pre-decorated at session
|
|
470
560
|
* construction by the driver (`stageName` carries the DISPLAY decoration;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worktree digest — fail-soft content fingerprint of `cwd`'s working tree.
|
|
3
|
+
*
|
|
4
|
+
* Used by the validation-retry gate to detect whether a stage's fix
|
|
5
|
+
* actually mutated anything observable between a failed validate and the retry
|
|
6
|
+
* (mechanism-1, captured around `askAgentToFix` in sessions/extraction.ts) or
|
|
7
|
+
* across a re-dispatch of an already-run `produces` stage (mechanism-2, at
|
|
8
|
+
* `runSingleStage` dispatch in runner/run-stage.ts). An UNCHANGED digest ⇒ the
|
|
9
|
+
* agent asked to fix changed nothing observable ⇒ the retry is skipped
|
|
10
|
+
* (fail fast) instead of re-running the same failing validation.
|
|
11
|
+
*
|
|
12
|
+
* Two components concatenated then hashed (a tracked-only digest
|
|
13
|
+
* misses a fix that touches ONLY a gitignored file under `.rpiv/artifacts/`,
|
|
14
|
+
* which `.gitignore` ignores, and would false-skip the gate):
|
|
15
|
+
* 1. the default git recipe — `git status --porcelain` + `git diff` (the same
|
|
16
|
+
* `execFileSync("git", [...], { stdio: ["ignore","pipe","ignore"] })`
|
|
17
|
+
* posture built-in-workflows.ts's `writeCommitBaseline` uses);
|
|
18
|
+
* 2. `hashArtifactsTree(cwd)` — a recursive walk of `<cwd>/.rpiv/artifacts/`
|
|
19
|
+
* hashing each file's relative path + contents so a gitignored-only
|
|
20
|
+
* artifact revision DOES change the digest.
|
|
21
|
+
*
|
|
22
|
+
* The whole `computeWorktreeDigest` is wrapped in try/catch → `undefined`
|
|
23
|
+
* (non-repo / git missing / unreadable tree), so BOTH gates degrade to
|
|
24
|
+
* "always proceed" on a missing signal — never skip on a missing signal.
|
|
25
|
+
*
|
|
26
|
+
* Leaf module: imports only `node:child_process` + `node:fs` + `node:crypto` +
|
|
27
|
+
* `node:path` (no back-edges), so the value-import DAG stays acyclic.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { execFileSync } from "node:child_process";
|
|
31
|
+
import { createHash } from "node:crypto";
|
|
32
|
+
import { type Dirent, readdirSync, readFileSync } from "node:fs";
|
|
33
|
+
import { join, relative } from "node:path";
|
|
34
|
+
|
|
35
|
+
/** Wall-clock ceiling per git subprocess. The digest runs SYNCHRONOUSLY on the
|
|
36
|
+
* validation-retry critical path and the bash watchdog cannot cover it (not a
|
|
37
|
+
* tool call, and `execFileSync` blocks the event loop) — so a wedged git (e.g.
|
|
38
|
+
* a contended `index.lock` from a concurrent commit) must be killed here. On
|
|
39
|
+
* expiry `execFileSync` throws → the digest degrades to `undefined` → both
|
|
40
|
+
* gates proceed, the documented missing-signal behavior. */
|
|
41
|
+
const GIT_DIGEST_TIMEOUT_MS = 10_000;
|
|
42
|
+
|
|
43
|
+
/** Subtree of `.rpiv/artifacts/` excluded from the digest: death-scene sidecars
|
|
44
|
+
* are FORENSIC output of failures, not a fix an agent applied. In a concurrent
|
|
45
|
+
* collect-all fanout a sibling unit's failure writes here mid-window; hashing
|
|
46
|
+
* it would flip another unit's unchanged-digest verdict and defeat the
|
|
47
|
+
* fail-fast gate with a spurious "tree changed". */
|
|
48
|
+
const DIGEST_EXCLUDED_ARTIFACT_DIRS: ReadonlySet<string> = new Set(["failures"]);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Walk `<cwd>/.rpiv/artifacts/` recursively, hashing each file's relative
|
|
52
|
+
* path + contents so a revision to ANY artifact (incl. a gitignored-only one)
|
|
53
|
+
* changes the digest. Absent / empty / unreadable tree contributes nothing
|
|
54
|
+
* (fail-soft) — the digest then equals the git-only digest. Symlinks are NOT
|
|
55
|
+
* followed (a `Dirent.isDirectory()` is false for a symlink-to-dir) so a
|
|
56
|
+
* looping symlink cannot recurse unboundedly; an unreadable / broken-link
|
|
57
|
+
* target contributes a stable `<unreadable>` token.
|
|
58
|
+
*/
|
|
59
|
+
function hashArtifactsTree(cwd: string): string {
|
|
60
|
+
const artifactsRoot = join(cwd, ".rpiv", "artifacts");
|
|
61
|
+
const entries = readdirRecursively(artifactsRoot, DIGEST_EXCLUDED_ARTIFACT_DIRS);
|
|
62
|
+
const hash = createHash("sha256");
|
|
63
|
+
for (const abs of entries.sort()) {
|
|
64
|
+
hash.update(relative(artifactsRoot, abs));
|
|
65
|
+
hash.update("\0");
|
|
66
|
+
try {
|
|
67
|
+
hash.update(readFileSync(abs));
|
|
68
|
+
} catch {
|
|
69
|
+
hash.update("<unreadable>");
|
|
70
|
+
}
|
|
71
|
+
hash.update("\0");
|
|
72
|
+
}
|
|
73
|
+
return hash.digest("hex");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Recursive `readdir` returning absolute file paths under `root` (symlinks not
|
|
77
|
+
* followed). `excludedTopDirs` names TOP-LEVEL subdirectories of `root` that are
|
|
78
|
+
* skipped entirely (deeper same-named dirs are not affected). */
|
|
79
|
+
function readdirRecursively(root: string, excludedTopDirs?: ReadonlySet<string>): string[] {
|
|
80
|
+
const out: string[] = [];
|
|
81
|
+
const walk = (dir: string, isRoot: boolean): void => {
|
|
82
|
+
let entries: Dirent[];
|
|
83
|
+
try {
|
|
84
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
85
|
+
} catch {
|
|
86
|
+
return; // absent / unreadable dir — contributes nothing
|
|
87
|
+
}
|
|
88
|
+
for (const entry of entries) {
|
|
89
|
+
const abs = join(dir, entry.name);
|
|
90
|
+
if (entry.isDirectory()) {
|
|
91
|
+
if (isRoot && excludedTopDirs?.has(entry.name)) continue;
|
|
92
|
+
walk(abs, false);
|
|
93
|
+
} else out.push(abs); // files + symlinks (target read fail-soft, below)
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
walk(root, true);
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Content fingerprint of `cwd`'s working tree — `git status --porcelain` +
|
|
102
|
+
* `git diff` concatenated with `hashArtifactsTree(cwd)`, then SHA-256 hashed.
|
|
103
|
+
* Mirrors built-in-workflows.ts's `writeCommitBaseline` git posture
|
|
104
|
+
* (`execFileSync` with stderr ignored so a non-repo cwd degrades silently).
|
|
105
|
+
*
|
|
106
|
+
* Returns `undefined` on ANY failure (non-repo / git missing / unreadable
|
|
107
|
+
* tree) so callers degrade to "proceed" rather than "skip" — a missing digest
|
|
108
|
+
* is NEVER a signal to gate.
|
|
109
|
+
*/
|
|
110
|
+
export function computeWorktreeDigest(cwd: string): string | undefined {
|
|
111
|
+
try {
|
|
112
|
+
const status = execFileSync("git", ["status", "--porcelain"], {
|
|
113
|
+
cwd,
|
|
114
|
+
encoding: "utf-8",
|
|
115
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
116
|
+
timeout: GIT_DIGEST_TIMEOUT_MS,
|
|
117
|
+
});
|
|
118
|
+
// `diff HEAD` (not bare `diff`) so STAGED content changes the digest too — a fix
|
|
119
|
+
// that edits-and-stages leaves the porcelain status line and the unstaged diff
|
|
120
|
+
// both unchanged between two different staged states. In a repo with no commits
|
|
121
|
+
// yet, `HEAD` is unresolvable and the throw degrades to `undefined` (proceed).
|
|
122
|
+
const diff = execFileSync("git", ["diff", "HEAD"], {
|
|
123
|
+
cwd,
|
|
124
|
+
encoding: "utf-8",
|
|
125
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
126
|
+
timeout: GIT_DIGEST_TIMEOUT_MS,
|
|
127
|
+
});
|
|
128
|
+
const artifacts = hashArtifactsTree(cwd);
|
|
129
|
+
return createHash("sha256").update(status).update("\0").update(diff).update("\0").update(artifacts).digest("hex");
|
|
130
|
+
} catch {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Resolve the digest for a session — the per-session override (`s.worktreeDigest`,
|
|
137
|
+
* injected by tests / programmatic embedders) wins WHENEVER PRESENT, including
|
|
138
|
+
* when it returns `undefined` (an override simulating a non-repo must not fall
|
|
139
|
+
* through to the real computation). No override ⇒ the default
|
|
140
|
+
* `computeWorktreeDigest`. Exposed so the two gate sites share one
|
|
141
|
+
* override-vs-default resolution instead of re-spelling it.
|
|
142
|
+
*/
|
|
143
|
+
export function resolveDigest(
|
|
144
|
+
computer: ((cwd: string) => string | undefined) | undefined,
|
|
145
|
+
cwd: string,
|
|
146
|
+
): string | undefined {
|
|
147
|
+
return computer ? computer(cwd) : computeWorktreeDigest(cwd);
|
|
148
|
+
}
|