@ngockhoale/ukit 3.4.73 → 3.4.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/manifests/documentation.yaml +10 -0
- package/manifests/platform.full.yaml +15 -0
- package/package.json +4 -1
- package/template_project/.claude/commands/ukit/handoff-fullstack.md +34 -12
- package/template_project/.claude/hooks/completion-gate.sh +10 -1
- package/template_project/.claude/hooks/handoff-resume.sh +38 -53
- package/template_project/.claude/hooks/owner-stop-gate.mjs +41 -0
- package/template_project/.claude/hooks/skill-router.sh +473 -36
- package/template_project/.claude/hooks/verification-guard.sh +8 -1
- package/template_project/.claude/settings.json +33 -1
- package/template_project/.claude/ukit/index/publication-intent.mjs +128 -13
- package/template_project/.claude/ukit/index/route-task.mjs +124 -26
- package/template_project/.claude/ukit/runtime/block-breaker.mjs +1 -0
- package/template_project/.claude/ukit/runtime/compact-threshold.mjs +8 -1
- package/template_project/.claude/ukit/runtime/cron-operation-adapter.mjs +14 -5
- package/template_project/.claude/ukit/runtime/execution-ledger.mjs +399 -35
- package/template_project/.claude/ukit/runtime/handoff-intent.mjs +5 -0
- package/template_project/.claude/ukit/runtime/handoff-provenance.mjs +277 -0
- package/template_project/.claude/ukit/runtime/loop-state.mjs +23 -4
- package/template_project/.claude/ukit/runtime/operation-evidence.mjs +9 -0
- package/template_project/.claude/ukit/runtime/reinject-context.mjs +10 -0
- package/template_project/.claude/ukit/runtime/resumable-run.mjs +33 -11
- package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +284 -58
- package/template_project/.omp/hooks/pre/ukit-bridge.js +171 -3
- package/scripts/dev/worktree-preflight.mjs +0 -166
- package/scripts/measure-decision-gateway.mjs +0 -306
- package/scripts/probe/codex-capability-probe.mjs +0 -169
|
@@ -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 =
|
|
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 =
|
|
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,
|
|
@@ -20,6 +20,8 @@ export function compactOperation(operation) {
|
|
|
20
20
|
|| operation.presentTargets.length > 256 || !operation.presentTargets.every(bounded)))) return { invalid: true };
|
|
21
21
|
return { domain: operation.domain, scope: operation.scope, role: operation.role, target: operation.target,
|
|
22
22
|
...(operation.state !== undefined ? { state: operation.state } : {}),
|
|
23
|
+
...(bounded(operation.candidate) ? { candidate: operation.candidate } : {}),
|
|
24
|
+
...(bounded(operation.integrity) ? { integrity: operation.integrity, ...(bounded(operation.integrityFor) ? { integrityFor: operation.integrityFor } : {}) } : {}),
|
|
23
25
|
...(operation.presentTargets !== undefined ? { presentTargets: operation.presentTargets === null ? null : [...operation.presentTargets] } : {}),
|
|
24
26
|
complete: operation.complete === true, ...(validRemoteSync(operation.remoteSync) ? { remoteSync: { ...operation.remoteSync } } : {}),
|
|
25
27
|
...(validGithubView(operation.github) ? { github: { ...operation.github } } : {}) };
|
|
@@ -65,11 +67,18 @@ export function foldOperationEvidence(bank = {}, receipt, ledger) {
|
|
|
65
67
|
: (op.role === 'state' && op.domain === 'git-integrity' && receipt.success === true && op.complete === true
|
|
66
68
|
&& validGithubView(priorGithub) && Number.isSafeInteger(priorGithub.observedSequence)
|
|
67
69
|
&& priorGithub.observedSequence > lastMutation) ? { ...priorGithub } : null;
|
|
70
|
+
const own = bounded(op.integrity) && (op.role === 'mutation' || bounded(op.integrityFor));
|
|
71
|
+
const kept = !own && op.role === 'state' && op.complete === true && prior.state?.sequence > lastMutation
|
|
72
|
+
&& op.state === `published:${prior.state.operation.integrityFor}`;
|
|
73
|
+
const src = own ? op : kept ? prior.state.operation : {};
|
|
74
|
+
const { integrity, integrityFor } = src;
|
|
68
75
|
const proof = { success: receipt.success === true, exitStatusUnproven: receipt.exitStatusUnproven === true, sequence: receipt.sequence,
|
|
69
76
|
toolUseId: receipt.toolUseId, taskInstanceId: receipt.taskInstanceId,
|
|
70
77
|
sessionKey: receipt.sessionKey, operation: {
|
|
71
78
|
domain: op.domain, scope: op.scope, role: op.role, target: op.target,
|
|
72
79
|
...(op.state !== undefined ? { state: op.state } : {}),
|
|
80
|
+
...(bounded(op.candidate) ? { candidate: op.candidate } : {}),
|
|
81
|
+
...(integrity ? { integrity, ...(integrityFor ? { integrityFor } : {}) } : {}),
|
|
73
82
|
...(op.presentTargets !== undefined ? { presentTargets: [...op.presentTargets] } : {}),
|
|
74
83
|
complete: op.complete === true,
|
|
75
84
|
...(remoteSync ? { remoteSync } : {}),
|
|
@@ -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
|
|
|
@@ -788,8 +788,18 @@ async function realDirectoryOrAbsent(target) {
|
|
|
788
788
|
}
|
|
789
789
|
}
|
|
790
790
|
|
|
791
|
+
function snapshotDeclaredSuccessors(fileCell) {
|
|
792
|
+
const m = String(fileCell ?? '').match(/(?:→|->)\s*(.*)$/s);
|
|
793
|
+
if (!m) return [];
|
|
794
|
+
const id = 'TASK-[A-Za-z0-9._-]*[A-Za-z0-9]';
|
|
795
|
+
const list = m[1].trim().replace(/[.;]+$/, '');
|
|
796
|
+
if (!new RegExp(`^${id}(?:\\s*,\\s*${id})*$`, 'i').test(list)) return [];
|
|
797
|
+
return [...new Set(list.split(',').map((x) => x.trim().toLowerCase()))];
|
|
798
|
+
}
|
|
799
|
+
|
|
791
800
|
function parseArchiveSnapshotStatuses(text) {
|
|
792
801
|
const map = new Map();
|
|
802
|
+
const successors = new Map();
|
|
793
803
|
for (const line of String(text).split('\n')) {
|
|
794
804
|
const row = line.trim();
|
|
795
805
|
if (!/^\|\s*TASK-/i.test(row)) continue;
|
|
@@ -798,25 +808,37 @@ function parseArchiveSnapshotStatuses(text) {
|
|
|
798
808
|
const key = cells[0].toLowerCase();
|
|
799
809
|
if (map.has(key)) return null;
|
|
800
810
|
map.set(key, cells[4].toLowerCase());
|
|
811
|
+
successors.set(key, snapshotDeclaredSuccessors(cells[7]));
|
|
801
812
|
}
|
|
813
|
+
Object.defineProperty(map, 'successors', { value: successors, enumerable: false });
|
|
802
814
|
return map;
|
|
803
815
|
}
|
|
804
816
|
|
|
805
|
-
// Terminal-success under the snapshot: done, or grounded cancellation resolved by a terminal successor.
|
|
806
817
|
function snapshotTaskTerminal(key, statuses, seen = new Set()) {
|
|
807
818
|
if (seen.has(key)) return false;
|
|
808
819
|
seen.add(key);
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
820
|
+
try {
|
|
821
|
+
const st = statuses.get(key);
|
|
822
|
+
if (st === 'done') return true;
|
|
823
|
+
if (st !== 'cancelled_superseded') return false;
|
|
824
|
+
const root = key.replace(/-r\d+$/, '');
|
|
825
|
+
const currentRepair = BigInt(key.match(/-r(\d+)$/)?.[1] ?? '0');
|
|
826
|
+
for (const [other, ost] of statuses) {
|
|
827
|
+
if (!other.startsWith(`${root}-r`) || !/^\d+$/.test(other.slice(root.length + 2))) continue;
|
|
828
|
+
if (BigInt(other.slice(root.length + 2)) <= currentRepair) continue;
|
|
829
|
+
if (ost === 'done' || (ost === 'cancelled_superseded' && snapshotTaskTerminal(other, statuses, seen))) return true;
|
|
830
|
+
}
|
|
831
|
+
const declared = statuses.successors?.get(key) || [];
|
|
832
|
+
return declared.length > 0
|
|
833
|
+
&& declared.every((s) => s !== key && statuses.has(s) && snapshotTaskTerminal(s, statuses, seen));
|
|
834
|
+
} finally {
|
|
835
|
+
seen.delete(key);
|
|
818
836
|
}
|
|
819
|
-
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
export function archiveSnapshotTaskTerminal(snapshotText, taskId) {
|
|
840
|
+
const statuses = parseArchiveSnapshotStatuses(snapshotText);
|
|
841
|
+
return statuses !== null && snapshotTaskTerminal(goalKey(taskId), statuses);
|
|
820
842
|
}
|
|
821
843
|
|
|
822
844
|
async function claimCycleFinalized(projectRoot, cycle, taskId) {
|