@ngockhoale/ukit 3.4.72 → 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;
@@ -50,17 +50,12 @@ const SERVICE_MUTATION = /^(?:docker(?:\s+compose)?|docker-compose)\s+(?:restart
50
50
  // Remote authority, not stale tracking refs: gate binds sha to clean live HEAD/tracking
51
51
  // remote. Native mutation success remains a separate requirement.
52
52
  const GIT_LS_REMOTE = /^git\s+ls-remote\s+(\S+)\s+(refs\/heads\/\S+)\s*$/;
53
- // Native GitHub repository postcondition: `gh repo view [repo] --json url,visibility` asks GitHub itself
54
- // (like ls-remote asks the Git remote). Strict: unmasked single command, BOTH JSON fields present, enum
55
- // visibility — the gate then binds the observed url to the gate-time Git remote URL
56
- // (ledger.gitAuthority.remoteUrl), so a masked/public/wrong-repo reply never completes publication.
53
+ // Native GitHub visibility needs both fields; the gate binds the observed URL to the live remote.
57
54
  const GH_REPO_VIEW = /^gh\s+repo\s+view(?:\s+(\S+))?\s+--json\s+([A-Za-z0-9_,]+)\s*$/;
58
55
  const GH_VISIBILITY = /^(?:PUBLIC|PRIVATE|INTERNAL)$/;
59
56
  const DRY_RUN = /(?:^|\s)(?:--dry-run|--check|--no-act|-n)(?:\s|=|$)/;
60
57
  const CURL = /^curl\s/;
61
- // A leading `cd <dir>;` / `cd <dir> &&` only selects the working directory: it prints nothing and the shell's
62
- // exit status is the next command's, so it must not turn an otherwise single, checked command into a "masked"
63
- // compound. Only ONE leading cd is dropped; any other `;`, `||`, pipe or extra segment still masks.
58
+ // Drop one leading cd; remaining separators still mask native exit attribution.
64
59
  const LEADING_CD = /^\s*cd\s+(?:"[^"\n$`\\]*"|'[^'\n]*'|[^\s;&|<>$`()]+)\s*(?:;|&&)\s*(?=\S)/;
65
60
  export function stripLeadingCd(command) {
66
61
  return typeof command === 'string' ? command.replace(LEADING_CD, '') : command;
@@ -154,7 +149,10 @@ export function bashOperationReceipt(rawCommand, response, transportSuccess, goa
154
149
  const wholeTree = kind !== 'status' || !/\s--\s|\s--porcelain=\S*\s+\S|(?:--porcelain|-s|--short)\s+[^\s-]/.test(seg);
155
150
  if (!wholeTree || (wanted && kind !== wanted)) continue;
156
151
  role = 'state';
157
- proven = kind === 'status' ? hasOutputField && text === '' : true;
152
+ const historyOnly = required.length > 0 && required.every((verb) => ['commit', 'push', 'tag'].includes(verb));
153
+ const untrackedOnly = /^git\s+status\s+--porcelain\s*$/.test(seg)
154
+ && text.split('\n').every((line) => !line || line.startsWith('?? '));
155
+ proven = kind === 'status' ? hasOutputField && (text === '' || (historyOnly && untrackedOnly)) : true;
158
156
  } else if (GIT_VERB.test(seg) && role !== 'state') {
159
157
  role = 'mutation';
160
158
  target = seg.match(GIT_VERB)[1];
@@ -177,15 +175,10 @@ export function bashOperationReceipt(rawCommand, response, transportSuccess, goa
177
175
  }
178
176
  }
179
177
  if (!role) return null;
180
- // A git STATE observation is attributable only when it is one unmasked, transport-successful command: in a
181
- // compound/masked chain the stdout of its parts is mixed, so it can neither prove nor refute the state and
182
- // must not overwrite earlier authoritative evidence. (A standalone dirty status still records as failed.)
178
+ // Mixed/masked stdout cannot prove or refute state; standalone dirty status still fails.
183
179
  if (domain === 'git-integrity' && role === 'state'
184
180
  && (masked || real.filter((seg) => seg && !/^cd\s+\S+$/.test(seg)).length !== 1)) return null;
185
- // A failed `gh repo view` (nonzero exit / unparseable JSON) IS an observation: it records as a FAILED
186
- // state receipt (no github field) so it invalidates any earlier PRIVATE proof until a fresh successful
187
- // view lands — the postcondition must hold at the LATEST check, not at some earlier one. Other git
188
- // state commands keep the rule that a transport failure is unattributable and records nothing.
181
+ // Failed GitHub views invalidate prior visibility; other failed Git transports mint no state proof.
189
182
  if (domain === 'git-integrity' && role === 'state' && transportSuccess !== true && !ghObserved) return null;
190
183
  const ok = transportSuccess === true && !masked && Boolean(scope) && (role === 'mutation' || proven);
191
184
  return { kind: 'operation', success: ok, transportSuccess: transportSuccess === true, harness,
@@ -212,7 +205,8 @@ export function releaseReceipt(rawCommand, response, transportSuccess) {
212
205
  const ok = transportSuccess === true && !masked;
213
206
  if (NPM_PUBLISH.test(seg)) {
214
207
  if (DRY_RUN.test(seg.replace(/'[^']*'|"[^"]*"/g, '""'))) return null;
215
- 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] } : {}) };
216
210
  }
217
211
  const view = seg.match(NPM_VIEW);
218
212
  if (view) {
@@ -230,7 +224,8 @@ export function releaseOperationReceipt(command, response, transportSuccess, { s
230
224
  const ok = found.success === true && Boolean(scope);
231
225
  const base = { kind: 'operation', success: ok, transportSuccess: transportSuccess === true, harness };
232
226
  if (found.type === 'publish') {
233
- 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 } };
234
229
  }
235
230
  const state = ok && `published:${found.package}@${found.version}`.length <= 200
236
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() },
@@ -3780,15 +3793,17 @@ function gitAuthority(cwd) {
3780
3793
  const remote = gitOutput(['config', `branch.${branch}.remote`], cwd);
3781
3794
  const remoteUrl = remote ? gitOutput(['config', `remote.${remote}.url`], cwd) : null;
3782
3795
  // gitOutput conflates empty output with failure; cleanliness needs an explicit successful status read.
3783
- let clean = false;
3796
+ let clean = false; let trackedClean = false;
3784
3797
  try {
3785
- clean = execFileSync('git', ['status', '--porcelain'], {
3798
+ const status = execFileSync('git', ['status', '--porcelain'], {
3786
3799
  cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000,
3787
- }).trim() === '';
3800
+ });
3801
+ clean = status.trim() === '';
3802
+ trackedClean = status.split('\n').every((line) => !line || line.startsWith('?? '));
3788
3803
  } catch { /* an unreadable working tree is not clean */ }
3789
3804
  // Annotated tags are peeled by --points-at; this state corroborates successful native tag execution.
3790
3805
  const tagsAtHead = (gitOutput(['tag', '--points-at', 'HEAD'], cwd) || '').split('\n').map((t) => t.trim()).filter(Boolean).slice(0, 16);
3791
- return { head, branch, remote, remoteUrl, tagsAtHead, clean };
3806
+ return { head, branch, remote, remoteUrl, tagsAtHead, clean, trackedClean };
3792
3807
  }
3793
3808
  function withGitAuthority(ledger, cwd) {
3794
3809
  const gitAuth = ledger && Object.keys(ledger).length ? gitAuthority(cwd) : null;
@@ -3883,7 +3898,14 @@ function releasePublicationMissing(state, ledger, cwd) {
3883
3898
  && proof.success === true && proof.operation.complete === true)
3884
3899
  .sort((a, b) => b.sequence - a.sequence)[0];
3885
3900
  const wanted = `published:${pkg.name}@${pkg.version}`;
3886
- 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';
3887
3909
  const tagCommit = gitOutput(['rev-parse', '--verify', '--quiet', `v${pkg.version}^{commit}`], cwd);
3888
3910
  const head = gitOutput(['rev-parse', 'HEAD'], cwd);
3889
3911
  // A repository that tags its releases (any v<semver> tag exists) must have tagged THIS version: without the
@@ -4373,7 +4395,7 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
4373
4395
  const instruction = publicationPending
4374
4396
  ? prerequisites.length > 0
4375
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.`
4376
- : '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.'
4377
4399
  : operationalTask
4378
4400
  ? 'Inspect native mutation receipts and verify the requested operational state; do not fabricate source edits or source-test evidence.'
4379
4401
  : recoveryInstruction(missingEvidence, effectiveLedger, routeSummary, { cwd });
@@ -4743,6 +4765,10 @@ async function runEvaluateStop() {
4743
4765
 
4744
4766
  const state = await readRouteState(projectRoot, payload);
4745
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
+ }
4746
4772
 
4747
4773
  // A session ledger with activity proves this session was routed and accumulating evidence.
4748
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,
@@ -49,10 +49,7 @@ export function foldOperationEvidence(bank = {}, receipt, ledger) {
49
49
  if (receipt.toolUseId && (seen.includes(receipt.toolUseId) || Object.values(bank).some((entry) =>
50
50
  [entry?.mutation, entry?.state].some((proof) => proof?.toolUseId === receipt.toolUseId)))) return bank;
51
51
  if (receipt.toolUseId && (!bounded(receipt.toolUseId) || seen.length >= 256)) return { ...bank, overflow: true };
52
- // A remote-parity observation (git ls-remote) must survive the clean-tree status check that normally follows
53
- // it: both are `state` receipts under one key, so the later status used to overwrite the remote proof. The
54
- // proof is stamped with the sequence it was observed at and carried over only while no mutation (failed or
55
- // not) of this domain/scope was recorded after it; the gate still compares its sha to live HEAD.
52
+ // Carry remote parity across successful state checks only until the next mutation; gate checks live HEAD.
56
53
  const lastMutation = Object.values(bank).reduce((max, entry) => {
57
54
  const m = entry?.mutation;
58
55
  return m?.operation?.domain === op.domain && m.operation.scope === op.scope && Number.isSafeInteger(m.sequence) ? Math.max(max, m.sequence) : max;
@@ -127,15 +124,15 @@ export function operationEvidenceStatus(goal, ledger = {}) {
127
124
  if (goal.visibility === 'PRIVATE' && !(validGithubView(op?.github)
128
125
  && op.github.visibility === 'PRIVATE' && githubRepository(auth?.remoteUrl) !== null
129
126
  && githubRepository(op.github.url) === githubRepository(auth.remoteUrl))) return incomplete;
130
- if (goal.domain === 'git-integrity' && executed && validRemoteSync(op.remoteSync) && auth && auth.clean === true
127
+ // Commit/push prove committed history; an explicit clean goal still owns the whole tree.
128
+ const cleanEnough = auth?.clean === true || (auth?.trackedClean === true && !requiredTargets.includes('clean'));
129
+ if (goal.domain === 'git-integrity' && executed && validRemoteSync(op.remoteSync) && cleanEnough
131
130
  && requiredTargets.every((t) => t === 'commit' || t === 'push' || t === 'clean' || (t === 'tag' && Array.isArray(auth.tagsAtHead) && auth.tagsAtHead.length > 0))
132
131
  && attempts.every((r) => (Number.isSafeInteger(op.remoteSync.observedSequence) ? op.remoteSync.observedSequence : observation.sequence) > r.sequence)
133
132
  && op.remoteSync.sha === auth.head && op.remoteSync.ref === `refs/heads/${auth.branch}`
134
133
  && op.remoteSync.remote === auth.remote) return { complete: true, operationProof: 'remote-parity' };
135
- // Push promises remote publication. No local check or missing gate-time authority can discharge it.
134
+ // Push needs remote proof; divergent observations cannot fall back to local checks.
136
135
  if (goal.domain === 'git-integrity' && requiredTargets.includes('push')) return incomplete;
137
- // A remote observation that disagrees with live local truth is divergence, not a verified state: it can never
138
- // be discharged by the fallback below just because a push command exited 0.
139
136
  if (goal.domain === 'git-integrity' && validRemoteSync(op.remoteSync) && auth
140
137
  && (op.remoteSync.sha !== auth.head || op.remoteSync.ref !== `refs/heads/${auth.branch}`
141
138
  || (auth.remote && op.remoteSync.remote !== auth.remote))) return incomplete;
@@ -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