@ngockhoale/ukit 3.4.73 → 3.4.74

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.
@@ -1489,7 +1489,14 @@ async function runCli() {
1489
1489
  })();
1490
1490
 
1491
1491
  if (mode === 'prompt') {
1492
- const routeState = await readJson(path.join(projectRoot, '.claude', 'ukit', 'skill-router-state.json'), {});
1492
+ let routeState = await readJson(path.join(projectRoot, '.claude', 'ukit', 'skill-router-state.json'), {});
1493
+ // Advisory reader: a pending or unconfirmed route publication is an interrupted write, not a route.
1494
+ if (routeState?.sessionId) {
1495
+ const owner = String(routeState.sessionId).trim().replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
1496
+ const committed = await readJson(path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${owner}.json`), {});
1497
+ if (routeState.routePublicationIncomplete || committed.routePublicationIncomplete
1498
+ || (routeState.routePersistenceRevision && committed.routePersistenceRevision !== routeState.routePersistenceRevision)) routeState = {};
1499
+ }
1493
1500
  const promptText = extractPrompt(payload);
1494
1501
  if (!promptText.trim()) {
1495
1502
  return;
@@ -205,7 +205,8 @@ export function releaseReceipt(rawCommand, response, transportSuccess) {
205
205
  const ok = transportSuccess === true && !masked;
206
206
  if (NPM_PUBLISH.test(seg)) {
207
207
  if (DRY_RUN.test(seg.replace(/'[^']*'|"[^"]*"/g, '""'))) return null;
208
- return { type: 'publish', success: ok };
208
+ const published = responseText(response).match(/(?:^|\n)\+\s+((?:@[^\s/]+\/)?[^\s@]+)@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)\s*(?:\n|$)/);
209
+ return { type: 'publish', success: ok, ...(published ? { package: published[1], version: published[2] } : {}) };
209
210
  }
210
211
  const view = seg.match(NPM_VIEW);
211
212
  if (view) {
@@ -223,7 +224,8 @@ export function releaseOperationReceipt(command, response, transportSuccess, { s
223
224
  const ok = found.success === true && Boolean(scope);
224
225
  const base = { kind: 'operation', success: ok, transportSuccess: transportSuccess === true, harness };
225
226
  if (found.type === 'publish') {
226
- return { ...base, operation: { domain: 'release', role: 'mutation', scope, target: 'npm-publish' } };
227
+ const state = found.package && found.version ? `published:${found.package}@${found.version}` : 'unproven';
228
+ return { ...base, operation: { domain: 'release', role: 'mutation', scope, target: 'npm-publish', state } };
227
229
  }
228
230
  const state = ok && `published:${found.package}@${found.version}`.length <= 200
229
231
  ? `published:${found.package}@${found.version}` : 'unproven';
@@ -315,7 +315,16 @@ export async function readRouteState(projectRoot, payload = {}) {
315
315
  // The shared file is single-slot: with no shared file there is still a per-session record.
316
316
  return sessionId ? readSessionRouteState(projectRoot, sessionId) : state;
317
317
  }
318
- if (stateSessionId === sessionId) return state;
318
+ if (stateSessionId === sessionId) {
319
+ const sidecar = await readSessionRouteState(projectRoot, sessionId);
320
+ // A pending marker means a publication was in flight and never committed, whether or not the shared
321
+ // document carries a revision. A legacy shared document (no revision) otherwise has no metadata to check.
322
+ if (sidecar?.routePublicationIncomplete) return { sessionId, routePublicationIncomplete: true };
323
+ if (state.routePersistenceRevision && (!sidecar || sidecar.routePersistenceRevision !== state.routePersistenceRevision)) {
324
+ return { sessionId, routePublicationIncomplete: true };
325
+ }
326
+ return state;
327
+ }
319
328
  // Shared file missing an owner or owned by another session (a concurrent session routed
320
329
  // after this one): recover this session's own record instead of declaring the route lost.
321
330
  return readSessionRouteState(projectRoot, sessionId);
@@ -331,7 +340,9 @@ export async function readSessionRouteState(projectRoot, sessionId) {
331
340
  path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${safeSegment(id)}.json`),
332
341
  null,
333
342
  );
334
- return state && explicitSessionId(state) === id ? state : null;
343
+ if (!state || explicitSessionId(state) !== id) return null;
344
+ if (state.routePublicationIncomplete === true) return { sessionId: id, routePublicationIncomplete: true };
345
+ return state;
335
346
  }
336
347
 
337
348
  export async function readExecutionLedger(projectRoot, payload = {}) {
@@ -906,11 +917,13 @@ async function backgroundCompletionFor({ projectRoot, payload, toolInput, toolRe
906
917
  try { mtime = fsSync.statSync(file).mtimeMs; } catch { return { rejected: 'output-file-missing' }; }
907
918
  if (mtime + 2000 < launch.ts) return { rejected: 'output-predates-launch' };
908
919
  const exitCode = Number(footer[1]);
909
- const success = exitCode === 0;
920
+ const masked = Boolean(maskedVerificationStage(launch.command));
921
+ const success = exitCode === 0 && !masked;
910
922
  const lv = launch.verdict || {};
911
- const kind = success ? (isTestGateCommand(launch.command) ? 'test-verified' : 'check-only') : 'failed';
923
+ const kind = masked ? 'unproven' : success ? (isTestGateCommand(launch.command) ? 'test-verified' : 'check-only') : 'failed';
912
924
  return {
913
925
  kind: 'verification', command: launch.command, success, exitCode, backgroundCompletion: id,
926
+ ...(masked ? { exitStatusUnproven: true } : {}),
914
927
  ...(launch.scope ? { scope: launch.scope } : {}),
915
928
  ...(launch.workspaceFp ? { workspaceFp: launch.workspaceFp } : {}),
916
929
  verdict: { ...lv, kind, evidence: launch.command, verifier: lv.verifier || 'self', ts: new Date().toISOString() },
@@ -3885,7 +3898,14 @@ function releasePublicationMissing(state, ledger, cwd) {
3885
3898
  && proof.success === true && proof.operation.complete === true)
3886
3899
  .sort((a, b) => b.sequence - a.sequence)[0];
3887
3900
  const wanted = `published:${pkg.name}@${pkg.version}`;
3888
- if (view?.operation?.state !== wanted) return 'release-publication';
3901
+ const mutation = release.map((entry) => entry.mutation).filter((proof) => proof?.operation?.domain === 'release'
3902
+ && proof.operation.target === 'npm-publish' && proof.taskInstanceId === ledger.taskInstanceId
3903
+ && proof.sessionKey === ledger.sessionKey).sort((a, b) => b.sequence - a.sequence)[0];
3904
+ if (view?.operation?.state !== wanted || view.taskInstanceId !== ledger.taskInstanceId
3905
+ || view.sessionKey !== ledger.sessionKey || !view.toolUseId || view.exitStatusUnproven
3906
+ || !mutation?.success || mutation.exitStatusUnproven || !mutation.toolUseId || mutation.operation.state !== wanted
3907
+ || !Number.isSafeInteger(mutation.sequence) || !Number.isSafeInteger(view.sequence)
3908
+ || view.sequence <= mutation.sequence || view.operation.scope !== mutation.operation.scope) return 'release-publication';
3889
3909
  const tagCommit = gitOutput(['rev-parse', '--verify', '--quiet', `v${pkg.version}^{commit}`], cwd);
3890
3910
  const head = gitOutput(['rev-parse', 'HEAD'], cwd);
3891
3911
  // A repository that tags its releases (any v<semver> tag exists) must have tagged THIS version: without the
@@ -4375,7 +4395,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4375
4395
  const instruction = publicationPending
4376
4396
  ? prerequisites.length > 0
4377
4397
  ? `Complete the permitted prerequisites first (${prerequisites.join(', ')}). ${recoveryInstruction(prerequisites, effectiveLedger, routeSummary, { cwd })} Do not publish before mandatory verification and separate execution authorization are established.`
4378
- : 'Publication remains unproven. Accepted evidence: a Bash result of exactly `npm view <package> version` (optionally --prefer-online) with successful native exit and the current package version, owned by this task. Rejected as unproven: the same command behind a pipeline, masked exit, stale or foreign-task receipt. Inspect existing owned registry/tag evidence first; never republish a served version or move its tag. Missing evidence does not authorize execution: publication requires the owner permission and mandatory release prerequisites. If either is unavailable, report BLOCKED with provenance; do not retry the same blocker.'
4398
+ : 'Publication remains unproven. A task-owned successful native publish receipt and a subsequent matching registry observation are required; registry state alone does not prove execution. Masked, stale or foreign-task receipts are not proof. Inspect existing evidence first; never republish a served version or move its tag. Missing evidence does not authorize execution: publication requires owner permission and mandatory release prerequisites. If provenance or authorization is unavailable, report BLOCKED; do not retry the same blocker.'
4379
4399
  : operationalTask
4380
4400
  ? 'Inspect native mutation receipts and verify the requested operational state; do not fabricate source edits or source-test evidence.'
4381
4401
  : recoveryInstruction(missingEvidence, effectiveLedger, routeSummary, { cwd });
@@ -4745,6 +4765,10 @@ async function runEvaluateStop() {
4745
4765
 
4746
4766
  const state = await readRouteState(projectRoot, payload);
4747
4767
  const ledger = await readExecutionLedger(projectRoot, payload) || {};
4768
+ if (state?.routePublicationIncomplete) {
4769
+ process.stdout.write(`${JSON.stringify({ decision: 'block', reason: 'UKit route publication incomplete: shared state and session route do not match; completion is unproven.' })}\n`);
4770
+ return;
4771
+ }
4748
4772
 
4749
4773
  // A session ledger with activity proves this session was routed and accumulating evidence.
4750
4774
  // If the route state is now missing or unreadable (router crashed/timed out before
@@ -327,6 +327,11 @@ async function scanBack(handle, hi, lo, loIsBoundary, deadline) {
327
327
  const lineBuf = region.subarray(i + 1, end);
328
328
  if (lineBuf.length) {
329
329
  const line = lineBuf.toString('utf8');
330
+ // A non-empty line that is not even shaped like a JSON object (garbage, or a
331
+ // record cut off before its evidence marker) can hide an intent the marker
332
+ // prefilter below would never see. It is UNDETERMINED, never "no intent".
333
+ const shaped = line.trim();
334
+ if (shaped && !(shaped.startsWith('{') && shaped.endsWith('}'))) return { status: 'torn', reached, lastNL };
330
335
  // Cheap prefilter — skip JSON.parse for lines that cannot be evidence.
331
336
  if (EVIDENCE_MARKERS.some((m) => line.includes(m))) {
332
337
  // This is the NEWEST line carrying intent evidence. A host append can be
@@ -0,0 +1,277 @@
1
+ // Durable task-to-run ownership. A transcript intent alone is never a binding.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import { withAsyncLock } from './async-lock.mjs';
6
+
7
+ export function provenancePath(projectRoot, runId) {
8
+ const run = String(runId || '').trim();
9
+ const key = run && crypto.createHash('sha256').update(run).digest('hex');
10
+ return key ? path.join(projectRoot, '.ukit', 'storage', 'runs', 'handoff-provenance', `${key}.json`) : null;
11
+ }
12
+
13
+ export function authorityPath(projectRoot, runId) {
14
+ const file = provenancePath(projectRoot, runId);
15
+ return file ? `${file}.authority` : null;
16
+ }
17
+
18
+ function identity(value) {
19
+ return { sessionId: String(value.sessionId), taskInstanceId: String(value.taskInstanceId), routeGeneration: String(value.routeGeneration) };
20
+ }
21
+
22
+ function identityKey(value) { return JSON.stringify(identity(value)); }
23
+ function validIdentity(value) {
24
+ return value && ['sessionId', 'taskInstanceId', 'routeGeneration'].every(key => typeof value[key] === 'string' && value[key].length > 0);
25
+ }
26
+
27
+ async function locked(file, callback) {
28
+ const result = await withAsyncLock(file, {}, callback);
29
+ if (!result.ok) throw new Error('handoff authority lock unavailable');
30
+ return result.value;
31
+ }
32
+
33
+ // This protocol requires an fsync-able directory and atomic same-directory
34
+ // replacement. Failure is closed; remote filesystems and hardware may still
35
+ // offer weaker guarantees than local POSIX filesystems.
36
+ async function syncDirectory(dir) {
37
+ const handle = await fs.open(dir, 'r');
38
+ try { await handle.sync(); } finally { await handle.close(); }
39
+ }
40
+ async function writeSynced(file, bytes) {
41
+ const handle = await fs.open(file, 'wx', 0o600);
42
+ try { await handle.writeFile(bytes); await handle.sync(); } finally { await handle.close(); }
43
+ }
44
+ async function commitAuthority(file, record) {
45
+ const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
46
+ try {
47
+ await writeSynced(tmp, `${JSON.stringify(record)}\n`);
48
+ // Refuse unsupported directory sync before committing, rather than silently
49
+ // claiming durability on platforms that cannot provide it.
50
+ await syncDirectory(path.dirname(file));
51
+ await fs.rename(tmp, file); // sole ownership transfer commit point
52
+ await syncDirectory(path.dirname(file));
53
+ } finally { await fs.rm(tmp, { force: true }).catch(() => {}); }
54
+ }
55
+
56
+ async function readAuthority(projectRoot, runId) {
57
+ const bindingFile = provenancePath(projectRoot, runId);
58
+ for (const suffix of ['.transferred', '.active']) {
59
+ try { await fs.access(`${bindingFile}${suffix}`); throw new Error('active resume claim missing or legacy state ambiguous'); }
60
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
61
+ }
62
+ const bytes = await fs.readFile(bindingFile);
63
+ const binding = JSON.parse(bytes);
64
+ if (binding.version !== 2 || binding.runId !== runId || !validIdentity(binding)) throw new Error('handoff binding invalid');
65
+ const record = JSON.parse(await fs.readFile(authorityPath(projectRoot, runId), 'utf8'));
66
+ const bindingHash = crypto.createHash('sha256').update(bytes).digest('hex');
67
+ if (record.version !== 1 || record.runId !== runId || record.bindingHash !== bindingHash
68
+ || !Number.isSafeInteger(record.generation) || record.generation < 0 || !validIdentity(record.owner)
69
+ || !Array.isArray(record.history) || record.history.length !== record.generation + 1
70
+ || record.history.some(item => !validIdentity(item))
71
+ || new Set(record.history.map(identityKey)).size !== record.history.length
72
+ || identityKey(record.history[0]) !== identityKey(binding)
73
+ || identityKey(record.history[record.history.length - 1]) !== identityKey(record.owner)) throw new Error('handoff authority invalid');
74
+ return { binding, record };
75
+ }
76
+
77
+ // Only a newly created binding may initialize authority. A missing authority on
78
+ // an existing binding is ambiguous, and is never reconstructed from the binding.
79
+ export async function bindHandoffRun({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration, cycle = null }) {
80
+ if (!projectRoot || !sessionId || !taskInstanceId || !runId || !routeGeneration) throw new Error('handoff provenance requires project, session, task, run and route generation');
81
+ const file = provenancePath(projectRoot, runId);
82
+ const authority = authorityPath(projectRoot, runId);
83
+ const binding = { version: 2, sessionId: String(sessionId), taskInstanceId: String(taskInstanceId), runId: String(runId), routeGeneration: String(routeGeneration), cycle: cycle == null ? null : String(cycle) };
84
+ await fs.mkdir(path.dirname(file), { recursive: true });
85
+ return locked(authority, () => bindWhileLocked({ projectRoot, runId, binding }));
86
+ }
87
+
88
+ async function bindWhileLocked({ projectRoot, runId, binding }) {
89
+ const file = provenancePath(projectRoot, runId);
90
+ const authority = authorityPath(projectRoot, runId);
91
+ {
92
+ try {
93
+ await fs.access(file);
94
+ } catch (error) {
95
+ if (error.code !== 'ENOENT') throw error;
96
+ // An authority (including corrupt or unreadable data) without its binding
97
+ // may be a previously committed transfer, never a fresh run.
98
+ for (const candidate of [authority, `${file}.transferred`, `${file}.active`]) {
99
+ try { await fs.lstat(candidate); throw new Error('handoff state exists without binding'); }
100
+ catch (stateError) { if (stateError.code !== 'ENOENT') throw stateError; }
101
+ }
102
+ }
103
+ const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
104
+ try {
105
+ await writeSynced(tmp, `${JSON.stringify(binding)}\n`);
106
+ try { await fs.link(tmp, file); }
107
+ catch (error) {
108
+ if (error.code !== 'EEXIST') throw error;
109
+ const existing = JSON.parse(await fs.readFile(file, 'utf8'));
110
+ if (JSON.stringify(existing) !== JSON.stringify(binding)) throw new Error('handoff provenance conflict');
111
+ const current = await readAuthority(projectRoot, runId);
112
+ if (identityKey(current.record.owner) !== identityKey(binding)) throw new Error('handoff binding no longer owns run');
113
+ return existing;
114
+ }
115
+ await syncDirectory(path.dirname(file));
116
+ const bytes = await fs.readFile(file);
117
+ const owner = identity(binding);
118
+ await commitAuthority(authority, { version: 1, runId, bindingHash: crypto.createHash('sha256').update(bytes).digest('hex'), generation: 0, owner, history: [owner] });
119
+ return binding;
120
+ } finally {
121
+ await fs.rm(tmp, { force: true }).catch(() => {});
122
+ // A crash or failure after binding creation deliberately leaves an
123
+ // unowned, ambiguous binding; never recreate authority on retry.
124
+ }
125
+ }
126
+ }
127
+
128
+ // Legacy claim paths remain readable for diagnostics only, never as authority.
129
+ export function resumeClaimPath(projectRoot, { runId, sessionId, taskInstanceId, routeGeneration }) {
130
+ const key = crypto.createHash('sha256').update(JSON.stringify([runId, sessionId, taskInstanceId, routeGeneration])).digest('hex');
131
+ return path.join(projectRoot, '.ukit/storage/runs/handoff-resume-claims', `${key}.json`);
132
+ }
133
+
134
+ export async function currentHandoffRecovery({ projectRoot, sessionId, runId }) {
135
+ if (!projectRoot || !sessionId || !runId) throw new Error('recovery requires complete identity');
136
+ return locked(authorityPath(projectRoot, runId), async () => {
137
+ const { record } = await readAuthority(projectRoot, runId);
138
+ if (record.owner.sessionId !== sessionId) throw new Error('recovery authority mismatch');
139
+ return { ...record.owner, generation: record.generation };
140
+ });
141
+ }
142
+
143
+ export async function withHandoffRecovery({ projectRoot, sessionId, runId, generation }, callback) {
144
+ if (!projectRoot || !sessionId || !runId || !Number.isSafeInteger(generation) || generation < 0) throw new Error('recovery requires complete identity');
145
+ return locked(authorityPath(projectRoot, runId), async () => {
146
+ const { record } = await readAuthority(projectRoot, runId);
147
+ if (record.owner.sessionId !== sessionId || record.generation !== generation) throw new Error('recovery authority mismatch');
148
+ return callback({ ...record.owner, generation: record.generation });
149
+ });
150
+ }
151
+
152
+ export async function withHandoffOwner({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration }, callback) {
153
+ return locked(authorityPath(projectRoot, runId), async () => {
154
+ const { record } = await readAuthority(projectRoot, runId);
155
+ if (identityKey(record.owner) !== identityKey({ sessionId, taskInstanceId, routeGeneration })) throw new Error('handoff owner changed');
156
+ return callback();
157
+ });
158
+ }
159
+
160
+ export async function claimHandoffResume({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration }) {
161
+ if (!projectRoot || !sessionId || !taskInstanceId || !runId || !routeGeneration) throw new Error('resume claim requires complete identity');
162
+ return locked(authorityPath(projectRoot, runId), () => claimWhileLocked({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration }));
163
+ }
164
+
165
+ async function claimWhileLocked({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration }) {
166
+ const { record } = await readAuthority(projectRoot, runId);
167
+ const owner = identity({ sessionId, taskInstanceId, routeGeneration });
168
+ const key = identityKey(owner);
169
+ if (key === identityKey(record.owner)) return { version: 1, runId, ...owner, bindingHash: record.bindingHash, generation: record.generation };
170
+ if (record.history.some(item => identityKey(item) === key)) throw new Error('historical handoff generation cannot be replayed');
171
+ if (!Number.isSafeInteger(record.generation + 1)) throw new Error('handoff generation exhausted');
172
+ const next = { ...record, generation: record.generation + 1, owner, history: [...record.history, owner] };
173
+ await commitAuthority(authorityPath(projectRoot, runId), next);
174
+ return { version: 1, runId, ...owner, bindingHash: record.bindingHash, generation: next.generation };
175
+ }
176
+
177
+ // A legacy run is a live cursor with no RunId line (written before ownership authority existed).
178
+ // Its identity is the digest of the exact cursor bytes, so the owner names the snapshot they mean and
179
+ // any later change to the cursor makes the identity stale instead of silently adopting different state.
180
+ export function legacyHandoffRunId(cursorBytes) {
181
+ return `handoff-${crypto.createHash('sha256').update(cursorBytes).digest('hex')}`;
182
+ }
183
+
184
+ export async function describeLegacyHandoffCursor({ runRoot }) {
185
+ let bytes;
186
+ try { bytes = await fs.readFile(path.join(runRoot, 'docs/AI_HANDOFF/RUN.md')); } catch { return null; }
187
+ const text = bytes.toString('utf8');
188
+ if ([...text.matchAll(/^RunId:\s*(\S+)\s*$/gim)].length) return null;
189
+ const phase = /^Phase:\s*(\S+)\s*$/im.exec(text)?.[1]?.toLowerCase();
190
+ if (phase === 'done' || !/^Command:/m.test(text)) return null;
191
+ return { runId: legacyHandoffRunId(bytes) };
192
+ }
193
+
194
+ async function stampLegacyCursor({ cursorFile, snapshot, runId }) {
195
+ const current = await fs.readFile(cursorFile);
196
+ if (!current.equals(snapshot)) throw new Error('legacy cursor changed before RunId stamp');
197
+ const text = snapshot.toString('utf8');
198
+ const line = /^Command:[^\r\n]*(\r?\n)/m.exec(text);
199
+ if (!line) throw new Error('legacy cursor has no Command line');
200
+ const at = line.index + line[0].length;
201
+ const next = `${text.slice(0, at)}RunId: ${runId}${line[1]}${text.slice(at)}`;
202
+ const mode = (await fs.stat(cursorFile)).mode & 0o777;
203
+ const tmp = `${cursorFile}.${process.pid}.${crypto.randomUUID()}.tmp`;
204
+ try {
205
+ await writeSynced(tmp, next);
206
+ await fs.chmod(tmp, mode);
207
+ if (!(await fs.readFile(cursorFile)).equals(snapshot)) throw new Error('legacy cursor changed before RunId stamp');
208
+ await fs.rename(tmp, cursorFile);
209
+ await syncDirectory(path.dirname(cursorFile));
210
+ } finally { await fs.rm(tmp, { force: true }).catch(() => {}); }
211
+ if ((await fs.readFile(cursorFile, 'utf8')) !== next) throw new Error('legacy cursor stamp verification failed');
212
+ }
213
+
214
+ // Owner-invoked adoption of a legacy cursor. Never called from session start, Stop or any model-driven path.
215
+ // Authority is created by the same bindHandoffRun protocol (no second authority); the cursor stamp comes
216
+ // after the commit point. A crash in between leaves an owned run whose cursor is still the unstamped
217
+ // snapshot: only the same session may re-invoke, which finishes the stamp (re-claiming if its task changed).
218
+ export async function adoptLegacyHandoffRun({ projectRoot, runRoot = projectRoot, sessionId, taskInstanceId, routeGeneration, runId }) {
219
+ if (!projectRoot || !sessionId || !taskInstanceId || !routeGeneration || !/^handoff-[a-f0-9]{64}$/.test(String(runId))) throw new Error('legacy adoption requires complete identity');
220
+ const cursorFile = path.join(runRoot, 'docs/AI_HANDOFF/RUN.md');
221
+ const file = provenancePath(projectRoot, runId);
222
+ const authority = authorityPath(projectRoot, runId);
223
+ await fs.mkdir(path.dirname(file), { recursive: true });
224
+ return locked(authority, async () => {
225
+ const snapshot = await fs.readFile(cursorFile);
226
+ const text = snapshot.toString('utf8');
227
+ if (legacyHandoffRunId(snapshot) !== runId) throw new Error('legacy cursor changed since the run was identified');
228
+ if ([...text.matchAll(/^RunId:\s*(\S+)\s*$/gim)].length) throw new Error('cursor already carries a RunId; this is not a legacy run');
229
+ if (/^Phase:\s*done\s*$/im.test(text)) throw new Error('a completed run cannot be adopted');
230
+ if (!/^Command:/m.test(text)) throw new Error('legacy cursor has no Command line');
231
+ let present = false;
232
+ for (const candidate of [file, authority, `${file}.transferred`, `${file}.active`]) {
233
+ try { await fs.lstat(candidate); present = true; } catch (error) { if (error.code !== 'ENOENT') throw error; }
234
+ }
235
+ if (!present) {
236
+ await bindWhileLocked({ projectRoot, runId, binding: { version: 2, sessionId: String(sessionId), taskInstanceId: String(taskInstanceId), runId, routeGeneration: String(routeGeneration), cycle: null } });
237
+ } else {
238
+ // Interrupted adoption by this same session, or an owned/ambiguous run: only the former may continue.
239
+ let record;
240
+ try { ({ record } = await readAuthority(projectRoot, runId)); } catch { throw new Error('run has ambiguous or invalid ownership state; adoption refused'); }
241
+ if (record.owner.sessionId !== String(sessionId)) throw new Error('run already has another owner; adoption refused');
242
+ await claimWhileLocked({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration });
243
+ }
244
+ await stampLegacyCursor({ cursorFile, snapshot, runId });
245
+ return { runId, ...(await readAuthority(projectRoot, runId)).record.owner };
246
+ });
247
+ }
248
+
249
+ export async function resolveCursorApplicability({ projectRoot, runRoot = projectRoot, sessionId }) {
250
+ if (!projectRoot) return { status: 'UNKNOWN', reason: 'missing project or session identity' };
251
+ let text;
252
+ try { text = await fs.readFile(path.join(runRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8'); }
253
+ catch (error) { return { status: 'UNKNOWN', reason: error.code === 'ENOENT' ? 'run cursor absent' : 'run cursor unreadable' }; }
254
+ if (!sessionId) return { status: 'UNKNOWN', reason: 'missing project or session identity' };
255
+ const safeSession = String(sessionId).trim().replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
256
+ let route;
257
+ try { route = JSON.parse(await fs.readFile(path.join(projectRoot, '.ukit/storage/cache/route-state', `${safeSession}.json`), 'utf8')); }
258
+ catch { return { status: 'UNKNOWN', reason: 'route identity unavailable' }; }
259
+ if (route?.routePublicationIncomplete || route?.sessionId !== sessionId || !route.taskInstanceId || !route.routeGeneration) return { status: 'UNKNOWN', reason: 'route identity unavailable or foreign' };
260
+ const ids = [...text.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
261
+ if (ids.length !== 1) return { status: 'UNKNOWN', reason: 'run cursor identity unavailable' };
262
+ const runId = ids[0][1];
263
+ const applicability = await resolveHandoffApplicability({ projectRoot, sessionId, taskInstanceId: route.taskInstanceId, routeGeneration: route.routeGeneration, runId });
264
+ if (route.handoffRunId !== runId) return applicability.status === 'NOT_OWNED' ? applicability : { status: 'UNKNOWN', reason: 'route and cursor run identity not reconciled' };
265
+ return applicability;
266
+ }
267
+
268
+ export async function resolveHandoffApplicability({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration, cycle = null }) {
269
+ if (!projectRoot || !sessionId || !taskInstanceId || !runId || !routeGeneration) return { status: 'UNKNOWN', reason: 'missing task, run or route identity' };
270
+ try {
271
+ const { binding, record } = await readAuthority(projectRoot, runId);
272
+ if (cycle != null && binding.cycle !== String(cycle)) return { status: 'NOT_OWNED', reason: 'cycle differs' };
273
+ if (identityKey(record.owner) !== identityKey({ sessionId, taskInstanceId, routeGeneration })) return { status: 'NOT_OWNED', reason: 'another generation owns the run' };
274
+ const claim = record.generation ? { version: 1, runId, ...record.owner, bindingHash: record.bindingHash, generation: record.generation } : undefined;
275
+ return { status: 'OWNED', binding, ...(claim ? { claim } : {}), generation: record.generation };
276
+ } catch { return { status: 'UNKNOWN', reason: 'handoff authority or binding unavailable or invalid' }; }
277
+ }
@@ -34,6 +34,25 @@ export async function loadLoopConfig(root) {
34
34
  }
35
35
 
36
36
  // Task-relevant evidence only: RUN.md cursor, banked ledger evidence, trusted prompt.
37
+ // The shared route slot is single-owner and published in two steps. Pending, mismatched-revision
38
+ // or foreign-session state yields {} (mode UNKNOWN => no early release, no prompt in the
39
+ // fingerprint). An ownerless legacy state (no sessionId, no revision) keeps its old meaning.
40
+ async function coherentRoutingContext(root, sessionId) {
41
+ const id = String(sessionId || '').trim();
42
+ const state = await readJson(path.join(root, '.claude', 'ukit', 'skill-router-state.json'), {});
43
+ if (state.routePublicationIncomplete) return {};
44
+ const owner = String(state.sessionId || '').trim();
45
+ if (owner && id && owner !== id) return {};
46
+ if (state.routePersistenceRevision && !id) return {};
47
+ if (id) {
48
+ const safe = id.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
49
+ const sidecar = await readJson(cache(root, path.join('route-state', `${safe}.json`)), {});
50
+ if (sidecar.routePublicationIncomplete) return {};
51
+ if (state.routePersistenceRevision && sidecar.routePersistenceRevision !== state.routePersistenceRevision) return {};
52
+ }
53
+ return state.routingContext || {};
54
+ }
55
+
37
56
  export async function progressFingerprint(root, runRoot = root, payload = {}) {
38
57
  let cur = 'no-run';
39
58
  try {
@@ -46,13 +65,13 @@ export async function progressFingerprint(root, runRoot = root, payload = {}) {
46
65
  : payload.transcript_path ? `transcript-${crypto.createHash('sha256').update(String(payload.transcript_path)).digest('hex').slice(0, 20)}` : 'default';
47
66
  const led = await readJson(cache(root, path.join('exec-ledger', `${id || 'default'}.json`)), {});
48
67
  const bank = (f) => Object.keys(led[f] && typeof led[f] === 'object' ? led[f] : {}).sort();
49
- const rc = (await readJson(path.join(root, '.claude', 'ukit', 'skill-router-state.json'), {})).routingContext || {};
68
+ const rc = await coherentRoutingContext(root, payload.session_id);
50
69
  return sha(JSON.stringify([cur, bank('bankedWrites'), bank('bankedVerifications'), rc.lastExplicitUserPromptText || '', rc.mutationOrder, rc.planOnly]));
51
70
  }
52
71
 
53
72
  // Mode: router-stamped routingContext only.
54
- export async function trustedTaskMode(root) {
55
- const rc = (await readJson(path.join(root, '.claude', 'ukit', 'skill-router-state.json'), {})).routingContext || {};
73
+ export async function trustedTaskMode(root, payload = {}) {
74
+ const rc = await coherentRoutingContext(root, payload?.session_id);
56
75
  if (rc.planOnly === true) return 'REPORT_ONLY';
57
76
  if (rc.mutationOrder === false) return 'READ_ONLY';
58
77
  return rc.mutationOrder === true ? 'IMPLEMENTATION' : null;
@@ -115,7 +134,7 @@ export async function applyLoopBreak({ merged, projectRoot, runRoot, payload, se
115
134
  if (merged.decision !== 'block' || merged.policyOwner === 'fail-closed') return merged;
116
135
  const cfg = await loadLoopConfig(projectRoot);
117
136
  if (!cfg.enabled) return merged;
118
- const mode = await trustedTaskMode(projectRoot);
137
+ const mode = await trustedTaskMode(projectRoot, payload);
119
138
  const res = await recordBlock({
120
139
  projectRoot, sessionId: sessionKey, reasonCode: reasonCodeFor(merged.policyOwner, merged.reason), cause: merged.policyOwner || 'unknown',
121
140
  fingerprint: await progressFingerprint(projectRoot, runRoot, payload), taskExecutionMode: mode,
@@ -409,6 +409,16 @@ async function loadFreshRouteState(projectRoot, sessionId) {
409
409
  }
410
410
  return {};
411
411
  }
412
+ // Advisory hints only, but a pending or unconfirmed publication is an interrupted write, not a route.
413
+ if (ownerId && (state.routePublicationIncomplete || state.routePersistenceRevision)) {
414
+ const safe = ownerId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
415
+ const sidecar = await readJson(path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${safe}.json`), {});
416
+ if (state.routePublicationIncomplete || sidecar.routePublicationIncomplete || sidecar.routePersistenceRevision !== state.routePersistenceRevision) return {};
417
+ } else if (ownerId) {
418
+ const safe = ownerId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
419
+ const sidecar = await readJson(path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${safe}.json`), {});
420
+ if (sidecar.routePublicationIncomplete) return {};
421
+ }
412
422
  return state;
413
423
  }
414
424