@tech-leads-club/harness-toolkit 0.10.5 → 0.10.6

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 (46) hide show
  1. package/bin/tlc-cli.ts +13 -11
  2. package/dist/compact-before.mjs +79 -79
  3. package/dist/doctor.mjs +80 -80
  4. package/dist/init-project.mjs +82 -82
  5. package/dist/install-runtime.mjs +79 -79
  6. package/dist/lessons-cli.mjs +79 -79
  7. package/dist/obs-cli.mjs +84 -84
  8. package/dist/price-lookup.mjs +1 -1
  9. package/dist/prompt-submit.mjs +79 -79
  10. package/dist/refresh-model-prices.mjs +79 -79
  11. package/dist/response-after.mjs +79 -79
  12. package/dist/run.mjs +79 -79
  13. package/dist/session-end.mjs +84 -84
  14. package/dist/session-start.mjs +86 -86
  15. package/dist/shim.mjs +78 -78
  16. package/dist/ship-gate.mjs +79 -79
  17. package/dist/stop.mjs +85 -85
  18. package/dist/subagent-start.mjs +79 -79
  19. package/dist/subagent-stop.mjs +80 -80
  20. package/dist/support.mjs +83 -83
  21. package/dist/tlc-cli.mjs +97 -97
  22. package/dist/tool-after.mjs +79 -79
  23. package/dist/tool-before.mjs +81 -81
  24. package/dist/tool-failure.mjs +79 -79
  25. package/dist/uninstall-runtime.mjs +4 -4
  26. package/docs/log.md +4 -0
  27. package/package.json +1 -1
  28. package/src/core/core.facade.ts +8 -0
  29. package/src/core/gate/gate.lock.ts +8 -32
  30. package/src/core/handoff/handoff.service.ts +110 -27
  31. package/src/core/handoff/handoff.session-store.ts +200 -0
  32. package/src/core/handoff/handoff.store.ts +5 -20
  33. package/src/core/handoff/handoff.types.ts +42 -9
  34. package/src/core/presence/presence.service.ts +59 -13
  35. package/src/entrypoints/prompt-submit.ts +1 -1
  36. package/src/entrypoints/response-after.ts +4 -4
  37. package/src/entrypoints/session-end.ts +1 -1
  38. package/src/entrypoints/session-start.ts +5 -4
  39. package/src/entrypoints/ship-gate.ts +2 -2
  40. package/src/entrypoints/stop.ts +18 -18
  41. package/src/entrypoints/subagent-stop.ts +4 -3
  42. package/src/entrypoints/support.ts +5 -3
  43. package/src/entrypoints/tool-after.ts +1 -1
  44. package/src/entrypoints/tool-before.ts +1 -1
  45. package/src/platform/paths.ts +4 -0
  46. package/src/platform/process.ts +36 -0
@@ -3,13 +3,7 @@ import { join } from "node:path";
3
3
  import { updateJsonAtomic } from "../../platform/fs-atomic.ts";
4
4
  import { projectStateDir } from "../../platform/paths.ts";
5
5
  import { seal } from "../integrity/state-seal.ts";
6
- import {
7
- defaultHandoffFile,
8
- type HandoffFile,
9
- type HandoffProviderSlice,
10
- type HandoffShared,
11
- isHandoffFile,
12
- } from "./handoff.types.ts";
6
+ import { defaultHandoffFile, type HandoffFile, type HandoffShared, isHandoffFile } from "./handoff.types.ts";
13
7
 
14
8
  export function handoffPath(root: string): string {
15
9
  return join(projectStateDir(root), "handoff.json");
@@ -33,25 +27,16 @@ export function readHandoffFile(root: string): HandoffFile {
33
27
  return defaultHandoffFile();
34
28
  }
35
29
 
36
- export type HandoffPatch = {
37
- shared?: Partial<HandoffShared>;
38
- slice?: Partial<HandoffProviderSlice>;
39
- };
40
-
41
- export function patchHandoff(root: string, provider: string, patch: HandoffPatch): Promise<HandoffFile> {
30
+ /** why shared only: the turn-scoped continuity slice moved to its own per-session file
31
+ * ([/decisions/ad-122.md](/decisions/ad-122.md)) — nothing here is provider- or session-specific any more. */
32
+ export function patchHandoffShared(root: string, patch: Partial<HandoffShared>): Promise<HandoffFile> {
42
33
  return updateJsonAtomic<HandoffFile>(
43
34
  handoffPath(root),
44
35
  (current) => {
45
36
  const base = current && isHandoffFile(current) ? current : defaultHandoffFile();
46
- const now = new Date().toISOString();
47
- const ownSlice = base.by_provider[provider] ?? { updated_at: now };
48
37
  return {
49
38
  schema: base.schema,
50
- shared: { ...base.shared, ...patch.shared, updated_at: now },
51
- by_provider: {
52
- ...base.by_provider,
53
- [provider]: { ...ownSlice, ...patch.slice, updated_at: now },
54
- },
39
+ shared: { ...base.shared, ...patch, updated_at: new Date().toISOString() },
55
40
  };
56
41
  },
57
42
  { lockPath: handoffLockPath(root), afterWrite: seal },
@@ -15,7 +15,6 @@ export type HandoffShared = {
15
15
 
16
16
  export type HandoffProviderSlice = {
17
17
  updated_at: string;
18
- session_key?: string;
19
18
  session_narrative?: string;
20
19
  completed?: string[];
21
20
  last_ship_claim_at?: string;
@@ -46,12 +45,13 @@ export type HandoffProviderSlice = {
46
45
  machine_state?: Record<string, unknown>;
47
46
  };
48
47
 
49
- export const HANDOFF_SCHEMA = "harness.handoff.v2" as const;
48
+ export const HANDOFF_SCHEMA = "harness.handoff.v3" as const;
50
49
 
50
+ /** The project-wide facts every session shares — no turn-scoped continuity here (moved to per-session files,
51
+ * [/decisions/ad-122.md](/decisions/ad-122.md)). */
51
52
  export type HandoffFile = {
52
53
  schema: typeof HANDOFF_SCHEMA;
53
54
  shared: HandoffShared;
54
- by_provider: Record<string, HandoffProviderSlice>;
55
55
  };
56
56
 
57
57
  export type ForeignSlice = {
@@ -68,7 +68,6 @@ export function defaultHandoffFile(mode: OperatorMode = "solo"): HandoffFile {
68
68
  return {
69
69
  schema: HANDOFF_SCHEMA,
70
70
  shared: { mode, updated_at: new Date().toISOString() },
71
- by_provider: {},
72
71
  };
73
72
  }
74
73
 
@@ -78,10 +77,44 @@ export function isHandoffFile(value: unknown): value is HandoffFile {
78
77
  }
79
78
  const candidate = value as Partial<HandoffFile>;
80
79
  return (
81
- candidate.schema === HANDOFF_SCHEMA &&
82
- typeof candidate.shared === "object" &&
83
- candidate.shared !== null &&
84
- typeof candidate.by_provider === "object" &&
85
- candidate.by_provider !== null
80
+ candidate.schema === HANDOFF_SCHEMA && typeof candidate.shared === "object" && candidate.shared !== null
81
+ );
82
+ }
83
+
84
+ export const HANDOFF_SESSION_SCHEMA = "harness.handoff-session.v1" as const;
85
+
86
+ /** which session last wrote this continuity file, and when — liveness itself is decided elsewhere, against
87
+ * presence's own heartbeat, not against anything stored here ([/decisions/ad-122.md](/decisions/ad-122.md)). */
88
+ type HandoffSessionOwner = {
89
+ session_key: string;
90
+ provider: string;
91
+ updated_at: string;
92
+ };
93
+
94
+ export type HandoffSessionFile = {
95
+ schema: typeof HANDOFF_SESSION_SCHEMA;
96
+ owner: HandoffSessionOwner;
97
+ slice: HandoffProviderSlice;
98
+ };
99
+
100
+ export function isHandoffSessionFile(value: unknown): value is HandoffSessionFile {
101
+ if (typeof value !== "object" || value === null) {
102
+ return false;
103
+ }
104
+ const candidate = value as Partial<HandoffSessionFile>;
105
+ if (candidate.schema !== HANDOFF_SESSION_SCHEMA) {
106
+ return false;
107
+ }
108
+ const owner = candidate.owner;
109
+ if (typeof owner !== "object" || owner === null) {
110
+ return false;
111
+ }
112
+ const o = owner as Partial<HandoffSessionOwner>;
113
+ return (
114
+ typeof o.session_key === "string" &&
115
+ typeof o.provider === "string" &&
116
+ typeof o.updated_at === "string" &&
117
+ typeof candidate.slice === "object" &&
118
+ candidate.slice !== null
86
119
  );
87
120
  }
@@ -8,7 +8,17 @@ import {
8
8
  } from "./presence.store.ts";
9
9
  import type { PresenceRecord } from "./presence.types.ts";
10
10
 
11
- const STALE_MS = 10 * 60 * 1000;
11
+ /** how long a file-edit claim (`checkCollision`'s `recent_files`) survives without a fresh touch — unrelated
12
+ * to whether the session's own conversation is still open, see `CONVERSATION_STALE_MS`. */
13
+ const CLAIM_STALE_MS = 10 * 60 * 1000;
14
+
15
+ /** why longer than the claim window: a conversation can sit quiet — reading long output, thinking — for well
16
+ * past ten minutes without being over, and both `isSessionLive` and `sweepStale` must agree on that same
17
+ * question so a record is never physically deleted while a reader would still call it live
18
+ * ([/decisions/ad-122.md](/decisions/ad-122.md)), matching this codebase's own precedent for the same class of
19
+ * stale-but-alive tolerance (`GATE_LOCK_STALE_MS`, `src/core/gate/gate.lock.ts`). */
20
+ const CONVERSATION_STALE_MS = 30 * 60 * 1000;
21
+
12
22
  const RECENT_FILES_MAX = 20;
13
23
 
14
24
  export function register(
@@ -29,20 +39,29 @@ export function register(
29
39
  return record;
30
40
  }
31
41
 
42
+ /**
43
+ * why self-healing: `sweepStale` deletes a record once it looks quiet, but quiet is not the same fact as over —
44
+ * a session whose next event arrives after that deletion is not a new session, and treating its own heartbeat
45
+ * as a no-op would leave it misdiagnosed as a dead predecessor by every other reader, permanently, since nothing
46
+ * else ever re-creates the file. This event is itself proof the conversation is still going, so it is always
47
+ * enough to (re)establish presence, register() or not ([/decisions/ad-122.md](/decisions/ad-122.md)).
48
+ */
32
49
  export function heartbeat(
33
50
  root: string,
34
51
  args: { provider: string; session: string; file?: string; now?: Date },
35
- ): PresenceRecord | null {
52
+ ): PresenceRecord {
36
53
  const existing = readPresenceRecord(root, args.provider, args.session);
37
- if (!existing) {
38
- return null;
39
- }
54
+ const now = (args.now ?? new Date()).toISOString();
40
55
  const recent_files = args.file
41
- ? [...existing.recent_files.filter((f) => f !== args.file), args.file].slice(-RECENT_FILES_MAX)
42
- : existing.recent_files;
56
+ ? [...(existing?.recent_files.filter((f) => f !== args.file) ?? []), args.file].slice(-RECENT_FILES_MAX)
57
+ : (existing?.recent_files ?? []);
43
58
  const next: PresenceRecord = {
44
- ...existing,
45
- heartbeat_at: (args.now ?? new Date()).toISOString(),
59
+ provider: args.provider,
60
+ session: args.session,
61
+ pid: process.pid,
62
+ branch: existing?.branch ?? "unknown",
63
+ started_at: existing?.started_at ?? now,
64
+ heartbeat_at: now,
46
65
  recent_files,
47
66
  };
48
67
  writePresenceRecord(root, next);
@@ -54,8 +73,8 @@ function heartbeatAgeMs(record: PresenceRecord, now: number): number {
54
73
  return Number.isNaN(at) ? Number.POSITIVE_INFINITY : now - at;
55
74
  }
56
75
 
57
- function isStale(record: PresenceRecord, now: number): boolean {
58
- return heartbeatAgeMs(record, now) >= STALE_MS;
76
+ function isStale(record: PresenceRecord, now: number, staleMs: number): boolean {
77
+ return heartbeatAgeMs(record, now) >= staleMs;
59
78
  }
60
79
 
61
80
  function elapsedLabel(record: PresenceRecord, now: number): string {
@@ -74,7 +93,7 @@ export function checkCollision(
74
93
  if (presenceSessionKey(record.provider, record.session) === ownSessionKey) {
75
94
  continue;
76
95
  }
77
- if (isStale(record, nowMs)) {
96
+ if (isStale(record, nowMs, CLAIM_STALE_MS)) {
78
97
  continue;
79
98
  }
80
99
  if (!record.recent_files.includes(file)) {
@@ -104,7 +123,7 @@ export function checkCollision(
104
123
  export function sweepStale(root: string, now: Date = new Date()): number {
105
124
  let swept = 0;
106
125
  for (const record of listPresenceRecords(root)) {
107
- if (isStale(record, now.getTime())) {
126
+ if (isStale(record, now.getTime(), CONVERSATION_STALE_MS)) {
108
127
  deletePresenceRecord(root, record.provider, record.session);
109
128
  swept += 1;
110
129
  }
@@ -116,4 +135,31 @@ export function release(root: string, provider: string, session: string): void {
116
135
  deletePresenceRecord(root, provider, session);
117
136
  }
118
137
 
138
+ /**
139
+ * why the session key, not the raw session id: every caller outside this module already carries the prefixed
140
+ * form (`${provider}-${id}`) — every inbound mapper produces it that way — and asking each one to also derive
141
+ * the bare id is the duplication a shared helper exists to remove.
142
+ */
143
+ function sessionIdFromSessionKey(provider: string, sessionKey: string): string {
144
+ const prefix = `${provider}-`;
145
+ return sessionKey.startsWith(prefix) ? sessionKey.slice(prefix.length) : sessionKey;
146
+ }
147
+
148
+ /**
149
+ * why heartbeat and not a process check: this harness's hook processes are one-shot — every entrypoint calls
150
+ * `process.exit` at the end of the single event it handled ([/decisions/ad-122.md](/decisions/ad-122.md)) — so
151
+ * no pid outlives the event that recorded it, and a pid-liveness check answers "dead" for every session,
152
+ * including one still very much in conversation. A heartbeat refreshed on every recognized event, regardless of
153
+ * which process handled it, is the one signal that survives the process boundary.
154
+ */
155
+ export function isSessionLive(
156
+ root: string,
157
+ provider: string,
158
+ sessionKey: string,
159
+ now: Date = new Date(),
160
+ ): boolean {
161
+ const record = readPresenceRecord(root, provider, sessionIdFromSessionKey(provider, sessionKey));
162
+ return record !== null && !isStale(record, now.getTime(), CONVERSATION_STALE_MS);
163
+ }
164
+
119
165
  export { listPresenceRecords, presenceSessionKey, readPresenceRecord };
@@ -16,7 +16,7 @@ export const promptSubmitHandler: Handler = async (event: HarnessEvent, ctx: Han
16
16
  // whole untouched file read as "added this turn" ([/decisions/ad-117.md](/decisions/ad-117.md)).
17
17
  const sha = await currentGitSha(shaScopeRoot(event));
18
18
  if (sha) {
19
- await coreFacade.handoff.patchHandoff(event.projectDir, event.provider, {
19
+ await coreFacade.handoff.patchHandoff(event.projectDir, event.provider, event.sessionKey, {
20
20
  slice: { turn_base_sha: sha },
21
21
  });
22
22
  }
@@ -13,7 +13,7 @@ export const responseAfterHandler: Handler = async (
13
13
  const plan = coreFacade.plan.detectPlan(text);
14
14
  const deviations = coreFacade.plan.detectDeviations(text);
15
15
  if (plan) {
16
- await coreFacade.handoff.patchHandoff(event.projectDir, event.provider, {
16
+ await coreFacade.handoff.patchHandoff(event.projectDir, event.provider, event.sessionKey, {
17
17
  slice: {
18
18
  plan_paths: plan.paths,
19
19
  plan_at: ctx.now.toISOString(),
@@ -25,11 +25,11 @@ export const responseAfterHandler: Handler = async (
25
25
  if (deviations.length > 0) {
26
26
  // why: a deviation can be justified in a later message than the one that declared the plan, so they
27
27
  // accumulate for the plan's window instead of replacing what was already accepted.
28
- const handoff = coreFacade.handoff.readHandoff(event.projectDir, event.provider);
28
+ const handoff = coreFacade.handoff.readHandoff(event.projectDir, event.provider, event.sessionKey);
29
29
  const known = handoff.plan_deviations ?? [];
30
30
  const fresh = deviations.filter((deviation) => !known.some((seen) => seen.path === deviation.path));
31
31
  if (fresh.length > 0) {
32
- await coreFacade.handoff.patchHandoff(event.projectDir, event.provider, {
32
+ await coreFacade.handoff.patchHandoff(event.projectDir, event.provider, event.sessionKey, {
33
33
  slice: { plan_deviations: [...known, ...fresh] },
34
34
  });
35
35
  }
@@ -38,7 +38,7 @@ export const responseAfterHandler: Handler = async (
38
38
 
39
39
  const claim = coreFacade.ship.detectShipClaim(text);
40
40
  if (claim) {
41
- await coreFacade.handoff.patchHandoff(event.projectDir, event.provider, {
41
+ await coreFacade.handoff.patchHandoff(event.projectDir, event.provider, event.sessionKey, {
42
42
  slice: {
43
43
  last_ship_claim_at: ctx.now.toISOString(),
44
44
  last_ship_claim_snippet: claim.snippet,
@@ -12,7 +12,7 @@ export const sessionEndHandler: Handler = async (
12
12
  const root = event.projectDir;
13
13
  const session = sessionIdFromKey(event);
14
14
 
15
- await coreFacade.handoff.patchHandoff(root, event.provider, {
15
+ await coreFacade.handoff.patchHandoff(root, event.provider, event.sessionKey, {
16
16
  slice: {
17
17
  next_action: "Session ended. Run `tlc harness handoff` before resuming.",
18
18
  },
@@ -43,7 +43,9 @@ export const sessionStartHandler: Handler = async (
43
43
  branch: branch ?? "unknown",
44
44
  });
45
45
 
46
- await coreFacade.handoff.patchHandoff(root, event.provider, {
46
+ coreFacade.handoff.pruneDeadHandoffSessions(root);
47
+
48
+ await coreFacade.handoff.patchHandoff(root, event.provider, event.sessionKey, {
47
49
  shared: {
48
50
  mode: policy.mode,
49
51
  project_name: policy.projectName,
@@ -51,7 +53,6 @@ export const sessionStartHandler: Handler = async (
51
53
  git_sha: sha ?? undefined,
52
54
  },
53
55
  slice: {
54
- session_key: event.sessionKey,
55
56
  // why: names the command, not the file. The path is on the policy surface, so an instruction pointing at it
56
57
  // asked for something the floor then refused ([/decisions/ad-047.md](/decisions/ad-047.md)).
57
58
  next_action: "Run `tlc harness handoff` if resuming; otherwise start from the user request.",
@@ -63,10 +64,10 @@ export const sessionStartHandler: Handler = async (
63
64
  * did not make is text placed in front of every later turn. Withholding is the answer, not refusing the turn
64
65
  * ([/decisions/ad-078.md](/decisions/ad-078.md)).
65
66
  */
66
- const handoffSeal = coreFacade.handoff.handoffInjectable(root);
67
+ const handoffSeal = coreFacade.handoff.handoffInjectable(root, event.sessionKey);
67
68
  const lessonSeal = coreFacade.lesson.projectLessonsInjectable(root);
68
69
  const handoff = handoffSeal.ok
69
- ? coreFacade.handoff.readHandoff(root, event.provider)
70
+ ? coreFacade.handoff.readHandoff(root, event.provider, event.sessionKey)
70
71
  : ({} as ReturnType<typeof coreFacade.handoff.readHandoff>);
71
72
  const foreign = handoffSeal.ok ? coreFacade.handoff.readForeignSlices(root, event.provider) : [];
72
73
 
@@ -49,10 +49,10 @@ export async function shipGateVerdict(event: HarnessEvent, ctx: HandlerContext):
49
49
  const provider = event.provider;
50
50
  const sessionKey = event.sessionKey;
51
51
  const session = sessionIdFromKey(event);
52
- const scope = await computeTurnScope(root, provider, policy);
52
+ const scope = await computeTurnScope(root, provider, sessionKey, policy);
53
53
  const shaRoot = shaScopeRoot(event);
54
54
 
55
- const commentHits = await pendingCommentViolations(root, provider, policy);
55
+ const commentHits = await pendingCommentViolations(root, provider, sessionKey, policy);
56
56
  if (commentHits.length > 0) {
57
57
  return {
58
58
  kind: "deny",
@@ -179,7 +179,7 @@ async function creditPendingLessons(args: {
179
179
  return;
180
180
  }
181
181
  await coreFacade.lesson.creditLessons(args.root, pending.ids, args.passed ? "helped" : "neutral");
182
- await coreFacade.handoff.patchHandoff(args.root, args.provider, {
182
+ await coreFacade.handoff.patchHandoff(args.root, args.provider, args.sessionKey, {
183
183
  slice: { pending_lesson_credit: undefined },
184
184
  });
185
185
  }
@@ -282,7 +282,7 @@ async function failGate(args: {
282
282
  ? "config"
283
283
  : coreFacade.turn.classifyGateFailure(args.gate);
284
284
  const freshGaps = coreFacade.gate.gapsFromArtifact({ artifact: args.artifact, category });
285
- const handoff = coreFacade.handoff.readHandoff(args.root, args.provider);
285
+ const handoff = coreFacade.handoff.readHandoff(args.root, args.provider, args.sessionKey);
286
286
  const gaps = intel.progressiveContext
287
287
  ? coreFacade.turn.mergeGaps(handoff.previous_gaps, freshGaps)
288
288
  : freshGaps;
@@ -300,7 +300,7 @@ async function failGate(args: {
300
300
  })
301
301
  : null;
302
302
 
303
- await coreFacade.handoff.patchHandoff(args.root, args.provider, {
303
+ await coreFacade.handoff.patchHandoff(args.root, args.provider, args.sessionKey, {
304
304
  slice: {
305
305
  last_gate_result: "fail",
306
306
  last_fingerprint: fingerprint,
@@ -348,7 +348,7 @@ async function failGate(args: {
348
348
  // the thing that grades them ([/decisions/ad-039.md](/decisions/ad-039.md)).
349
349
  if (selected.usedIds.length > 0) {
350
350
  await coreFacade.lesson.markGradeable(args.root, selected.usedIds);
351
- await coreFacade.handoff.patchHandoff(args.root, args.provider, {
351
+ await coreFacade.handoff.patchHandoff(args.root, args.provider, args.sessionKey, {
352
352
  slice: {
353
353
  pending_lesson_credit: {
354
354
  gate: args.gate,
@@ -475,9 +475,9 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
475
475
  * risk — a decision taken from planted text. Withholding here means deciding from the file's absence, which is
476
476
  * the same answer a first turn gets ([/decisions/ad-080.md](/decisions/ad-080.md)).
477
477
  */
478
- const stopSeal = coreFacade.handoff.handoffInjectable(root);
478
+ const stopSeal = coreFacade.handoff.handoffInjectable(root, sessionKey);
479
479
  const handoff = stopSeal.ok
480
- ? coreFacade.handoff.readHandoff(root, provider)
480
+ ? coreFacade.handoff.readHandoff(root, provider, sessionKey)
481
481
  : ({} as ReturnType<typeof coreFacade.handoff.readHandoff>);
482
482
  // hazard: read before the file list, because the list is diffed against it. A turn that commits moves `HEAD`
483
483
  // past its own changes, and every gate below then saw an empty diff and skipped — the comment gate in a repo
@@ -506,7 +506,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
506
506
  // stop is still visible when the gate it belongs to runs below.
507
507
  const pendingCredit = handoff.pending_lesson_credit;
508
508
 
509
- await coreFacade.handoff.patchHandoff(root, provider, {
509
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
510
510
  slice: { last_stop_status: status, last_changed_files: changedFiles, last_gate_result: "skipped" },
511
511
  });
512
512
 
@@ -515,7 +515,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
515
515
 
516
516
  if (skipVerify || status !== "completed" || cap.capReached) {
517
517
  if (cap.capReached) {
518
- await coreFacade.handoff.patchHandoff(root, provider, {
518
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
519
519
  slice: {
520
520
  blockers: `Grind cap hit (${maxLoops} stop loops). Fix manually or pause gates.`,
521
521
  next_action: "Inspect failures, fix root cause, then continue.",
@@ -543,7 +543,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
543
543
  //
544
544
  // invariant: this rail records what it saw and never writes a field it reads. `next_action` is not one of
545
545
  // them, and the follow-up text carries the instruction anyway.
546
- await coreFacade.handoff.patchHandoff(root, provider, {
546
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
547
547
  slice: {
548
548
  last_failure_category: "agent-quality",
549
549
  next_action: "Attempt the work, or proceed under a stated assumption.",
@@ -557,7 +557,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
557
557
  (typeof event.contextUsagePercent === "number" && event.contextUsagePercent >= 85);
558
558
 
559
559
  if (intel.budgetContinue && unfinishedWork && budgetPressure) {
560
- await coreFacade.handoff.patchHandoff(root, provider, {
560
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
561
561
  slice: {
562
562
  last_failure_category: "budget",
563
563
  next_action: coreFacade.turn.suggestionFor("budget", "budget"),
@@ -686,7 +686,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
686
686
  turnBase,
687
687
  );
688
688
  if (hits.length > 0) {
689
- await coreFacade.handoff.patchHandoff(root, provider, {
689
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
690
690
  slice: {
691
691
  last_gate_result: "fail",
692
692
  blockers: `This turn added ${hits.length} undeclared comment line(s).`,
@@ -721,7 +721,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
721
721
  },
722
722
  });
723
723
  if (outcome.findings.length > 0) {
724
- await coreFacade.handoff.patchHandoff(root, provider, {
724
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
725
725
  slice: {
726
726
  last_gate_result: "fail",
727
727
  blockers: `This turn changed the dependency graph in ${outcome.findings.length} way(s) that outlive it.`,
@@ -757,7 +757,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
757
757
  );
758
758
  const hits = coreFacade.duplication.findDuplications(added, scan.index, policy.duplication.minRun);
759
759
  if (hits.length > 0) {
760
- await coreFacade.handoff.patchHandoff(root, provider, {
760
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
761
761
  slice: {
762
762
  last_gate_result: "fail",
763
763
  blockers: `This turn added ${hits.length} run(s) the project already has.`,
@@ -824,7 +824,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
824
824
  changedFiles,
825
825
  });
826
826
  if (planDecision.kind !== "abstain") {
827
- await coreFacade.handoff.patchHandoff(root, provider, {
827
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
828
828
  slice: {
829
829
  last_gate_result: "fail",
830
830
  last_failure_category: "policy",
@@ -845,7 +845,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
845
845
  changedFilesCount: changedFiles.length,
846
846
  });
847
847
  if (emptyDiffDecision.kind !== "abstain") {
848
- await coreFacade.handoff.patchHandoff(root, provider, {
848
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
849
849
  slice: {
850
850
  last_gate_result: "fail",
851
851
  blockers: "Structured ship claim with empty diff.",
@@ -875,7 +875,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
875
875
  evidenceNotBeforeMs: coreFacade.ship.newestChangeMs(root, changedFiles),
876
876
  });
877
877
  if (shipEvidenceDecision.kind !== "abstain") {
878
- await coreFacade.handoff.patchHandoff(root, provider, {
878
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
879
879
  slice: {
880
880
  last_gate_result: "fail",
881
881
  blockers: "HARNESS_SHIP_CLAIM without recent production evidence on runtime changes.",
@@ -922,7 +922,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
922
922
  if (stopRules.decision.kind !== "abstain") {
923
923
  if (stopRules.decision.kind !== "context") {
924
924
  const worst = coreFacade.rules.strictest(stopRules.outcomes);
925
- await coreFacade.handoff.patchHandoff(root, provider, {
925
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
926
926
  slice: {
927
927
  last_gate_result: "fail",
928
928
  last_failure_category: "policy",
@@ -960,7 +960,7 @@ export const stopHandler: Handler = async (event: HarnessEvent, ctx: HandlerCont
960
960
  * a `why` kind, so `tlc harness why` answers it after the fact.
961
961
  */
962
962
  const holders = [...new Set(deferred)];
963
- await coreFacade.handoff.patchHandoff(root, provider, {
963
+ await coreFacade.handoff.patchHandoff(root, provider, sessionKey, {
964
964
  slice: {
965
965
  last_gate_result: holders.length > 0 ? "skipped" : "pass",
966
966
  blockers: undefined,
@@ -14,9 +14,10 @@ export const subagentStopHandler: Handler = async (
14
14
  // rule asks for. It cannot change the decision below ([/decisions/ad-100.md](/decisions/ad-100.md)).
15
15
  await observeForRules(event, ctx);
16
16
 
17
- const handoff = coreFacade.handoff.readHandoff(event.projectDir, event.provider);
18
- // why: `blockers` is per-project, and every Task subagent shares the parent's session_id
19
- // (anthropics/claude-code#7881), so this cannot tell its own subagent apart from another. A "budget"
17
+ const handoff = coreFacade.handoff.readHandoff(event.projectDir, event.provider, event.sessionKey);
18
+ // why: `blockers` is per-session ([/decisions/ad-122.md](/decisions/ad-122.md)), and every Task subagent
19
+ // shares the parent's session_id (anthropics/claude-code#7881), so this cannot tell its own subagent apart
20
+ // from another. A "budget"
20
21
  // category means the session's turn budget ran out, not that the tree is broken — unlike a gate
21
22
  // failure, it is not valid evidence here ([/decisions/ad-073.md](/decisions/ad-073.md)).
22
23
  const isBudgetBlocker = handoff.last_failure_category === "budget";
@@ -98,10 +98,11 @@ export type TurnScope = {
98
98
  export async function computeTurnScope(
99
99
  root: string,
100
100
  provider: string,
101
+ sessionKey: string,
101
102
  policy: Pick<Policy, "codePaths">,
102
103
  ): Promise<TurnScope> {
103
- const seal = coreFacade.handoff.handoffInjectable(root);
104
- const handoff = seal.ok ? coreFacade.handoff.readHandoff(root, provider) : undefined;
104
+ const seal = coreFacade.handoff.handoffInjectable(root, sessionKey);
105
+ const handoff = seal.ok ? coreFacade.handoff.readHandoff(root, provider, sessionKey) : undefined;
105
106
  const turnBase = handoff?.turn_base_sha ?? "HEAD";
106
107
  const changedFiles = await listChangedRepoFiles(root, turnBase);
107
108
  const codeTargets = filterCodeTargets(changedFiles, policy.codePaths);
@@ -128,12 +129,13 @@ export async function computeTurnScope(
128
129
  export async function pendingCommentViolations(
129
130
  root: string,
130
131
  provider: string,
132
+ sessionKey: string,
131
133
  policy: Pick<Policy, "comments" | "codePaths">,
132
134
  ): Promise<CommentFinding[]> {
133
135
  if (!policy.comments.enabled || policy.comments.onViolation !== "followup") {
134
136
  return [];
135
137
  }
136
- const scope = await computeTurnScope(root, provider, policy);
138
+ const scope = await computeTurnScope(root, provider, sessionKey, policy);
137
139
  if (scope.commentTargets.length === 0) {
138
140
  return [];
139
141
  }
@@ -68,7 +68,7 @@ async function commentEditAdvisory(event: HarnessEvent, ctx: HandlerContext): Pr
68
68
  if (targets.length === 0) {
69
69
  return null;
70
70
  }
71
- const handoff = coreFacade.handoff.readHandoff(event.projectDir, event.provider);
71
+ const handoff = coreFacade.handoff.readHandoff(event.projectDir, event.provider, event.sessionKey);
72
72
  const hits = await coreFacade.commentPolicy.scanAddedComments(
73
73
  event.projectDir,
74
74
  targets,
@@ -26,7 +26,7 @@ async function commentGateBeforeCommit(event: HarnessEvent, ctx: HandlerContext)
26
26
  if (!coreFacade.rules.triggerMatches({ kind: "commit" }, context)) {
27
27
  return { kind: "abstain" };
28
28
  }
29
- const hits = await pendingCommentViolations(event.projectDir, event.provider, ctx.policy);
29
+ const hits = await pendingCommentViolations(event.projectDir, event.provider, event.sessionKey, ctx.policy);
30
30
  if (hits.length === 0) {
31
31
  return { kind: "abstain" };
32
32
  }
@@ -128,6 +128,10 @@ export function bootDir(root: string): string {
128
128
  return join(projectStateDir(root), "boot");
129
129
  }
130
130
 
131
+ export function handoffSessionsDir(root: string): string {
132
+ return join(projectStateDir(root), "handoff-sessions");
133
+ }
134
+
131
135
  // why: inside the state directory on purpose — the baseline that proves the policy was not switched off
132
136
  // inherits the same protection as the policy itself.
133
137
  export function policyBaselineDir(root: string): string {
@@ -1,7 +1,43 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { hostname } from "node:os";
2
3
 
3
4
  const TIMEOUT_EXIT_CODE = 124;
4
5
 
6
+ /** Asks the OS whether a pid exists. Injected so the ESRCH and EPERM branches are testable on every platform. */
7
+ export type ProcessProbe = (pid: number) => void;
8
+
9
+ const defaultProbe: ProcessProbe = (pid) => {
10
+ process.kill(pid, 0);
11
+ };
12
+
13
+ /**
14
+ * Whether the process that recorded `pid`/`host` is still running, right now, on this machine.
15
+ *
16
+ * why: a pid means nothing on another host, so a mismatch answers "alive" rather than guessing.
17
+ * `process.kill(pid, 0)` sends no signal, it only asks whether the process exists; `ESRCH` is the one answer
18
+ * that proves it does not. Extracted from `gate.lock.ts`'s original `isLockOwnerGone`, its only consumer — a
19
+ * pid outlives one long-running gate command's own duration ([/decisions/ad-122.md](/decisions/ad-122.md)).
20
+ */
21
+ export function isProcessAlive(
22
+ pid: number,
23
+ host: string,
24
+ thisHost: string = hostname(),
25
+ probe: ProcessProbe = defaultProbe,
26
+ ): boolean {
27
+ if (host !== thisHost) {
28
+ return true;
29
+ }
30
+ if (!Number.isInteger(pid) || pid <= 0) {
31
+ return true;
32
+ }
33
+ try {
34
+ probe(pid);
35
+ return true;
36
+ } catch (error) {
37
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
38
+ }
39
+ }
40
+
5
41
  export async function readStdinText(): Promise<string> {
6
42
  const chunks: Buffer[] = [];
7
43
  for await (const chunk of process.stdin) {