@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.
- package/CHANGELOG.md +12 -0
- package/manifests/documentation.yaml +10 -0
- package/package.json +1 -1
- package/template_project/.claude/commands/ukit/handoff-fullstack.md +34 -12
- package/template_project/.claude/hooks/handoff-resume.sh +29 -53
- package/template_project/.claude/hooks/skill-router.sh +299 -23
- package/template_project/.claude/hooks/verification-guard.sh +8 -1
- package/template_project/.claude/settings.json +22 -0
- package/template_project/.claude/ukit/index/publication-intent.mjs +7 -2
- package/template_project/.claude/ukit/index/route-task.mjs +77 -18
- 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 +4 -2
- package/template_project/.claude/ukit/runtime/execution-ledger.mjs +30 -6
- 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/reinject-context.mjs +10 -0
- package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +126 -26
- package/template_project/.omp/hooks/pre/ukit-bridge.js +34 -1
|
@@ -201,9 +201,9 @@ const HOOK_DEADLINE_MS = Number.parseInt(process.env.UKIT_HOOK_DEADLINE_MS || ''
|
|
|
201
201
|
setTimeout(() => process.exit(0), HOOK_DEADLINE_MS).unref();
|
|
202
202
|
|
|
203
203
|
(async () => {
|
|
204
|
-
// BEGIN GENERATED SEMANTIC ENGINE sha256=
|
|
204
|
+
// BEGIN GENERATED SEMANTIC ENGINE sha256=436a0d9c586c1da4d418cfa8bfd377fa45471885fc5ff0ed471b0f6a7b342088
|
|
205
205
|
// Canonical task semantics; intent never grants authorization or proves completion.
|
|
206
|
-
const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:
|
|
206
|
+
const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:287d478b06a81ac1f9fcc1c53fd00217ab13bf6af53aca3bd662df0989e30b5e';
|
|
207
207
|
|
|
208
208
|
function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
|
|
209
209
|
return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
|
|
@@ -285,7 +285,8 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
|
|
|
285
285
|
}
|
|
286
286
|
for (const span of [...spans].reverse()) {
|
|
287
287
|
const approvalPending = span.condition && /\b(?:approv\w*|permission|authori[sz]\w*)\b/.test(span.condition);
|
|
288
|
-
|
|
288
|
+
const evidenceStatement = /^\s*git\s+commit\s*(?:\/|va)\s*github\s+release\s+khong\s+(?:duoc tinh la hoan thanh|phai\s+(?:la\s+)?(?:san pham\s+)?(?:hoan tat|hoan thanh))\s*[.!]?\s*$/.test(foldIntent(span.raw));
|
|
289
|
+
if (span.context === 'quotation' || span.context === 'description' || approvalPending || deferredSpans.has(span) || evidenceStatement) {
|
|
289
290
|
// Retain the prefix before a comma-introduced postfix repair condition.
|
|
290
291
|
// Leading conditions and otherwise consequences are masked in full.
|
|
291
292
|
const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|otherwise)\b/.test(foldIntent(span.raw))
|
|
@@ -412,9 +413,13 @@ function publicationScope(promptText = '') {
|
|
|
412
413
|
const bullet = /^\s*(?:[-*•]|\d+[.)])\s+/.test(line);
|
|
413
414
|
if (!bullet) prohibitionBlock = PUBLISH_ORDER_NEGATOR.test(line) && /:\s*$/.test(line);
|
|
414
415
|
for (const clause of line.split(/;|\.\s+|\bthen\b|\bbut\b|\binstead\b/)) {
|
|
416
|
+
// A temporary restriction pending prerequisites is not a task-wide prohibition.
|
|
417
|
+
// This classification does not authorize execution or establish those prerequisites.
|
|
415
418
|
let negated = bullet && prohibitionBlock;
|
|
416
419
|
for (const raw of clause.split(/,|\band\b|\bor\b|\bnor\b/)) {
|
|
417
420
|
const item = raw.replace(/^[\s*•-]+/, '').trim();
|
|
421
|
+
if (/\b(?:do not|don't|must not|not yet)\b[^,]*\b(?:publish|publication|release)\b[^,]*\b(?:while|until|before)\b/.test(item)
|
|
422
|
+
|| /\b(?:publish|publication|release)\b[^,]*\b(?:must not|not yet)\b[^,]*\b(?:until|before|while)\b/.test(item)) continue;
|
|
418
423
|
if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
|
|
419
424
|
else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
|
|
420
425
|
if (negated && /\b(?:release|publish|publication)\b/.test(item)) prohibited = true;
|
|
@@ -4112,16 +4117,64 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4112
4117
|
? null
|
|
4113
4118
|
: String(sessionCandidate).trim() || null;
|
|
4114
4119
|
|
|
4115
|
-
//
|
|
4116
|
-
//
|
|
4117
|
-
|
|
4118
|
-
async function
|
|
4120
|
+
// Compare the observed session route under the lock before ordinary writes.
|
|
4121
|
+
// Handoff writes use their separate authority-locked commit protocol.
|
|
4122
|
+
const sessionRoutePath = sessionId && path.join(projectRoot, '.ukit/storage/cache/route-state', `${sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`);
|
|
4123
|
+
async function readRouteVersion() {
|
|
4124
|
+
try {
|
|
4125
|
+
const bytes = await fsp.readFile(sessionRoutePath, 'utf8');
|
|
4126
|
+
const route = JSON.parse(bytes);
|
|
4127
|
+
if (!route || route.sessionId !== sessionId || !route.taskInstanceId) throw new Error('invalid session route');
|
|
4128
|
+
return bytes;
|
|
4129
|
+
} catch (error) {
|
|
4130
|
+
if (error.code === 'ENOENT') return null;
|
|
4131
|
+
throw new Error('existing session route unavailable');
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
let expectedRouteVersion;
|
|
4135
|
+
async function persistRouteState(text, recoveryOwner = null) {
|
|
4136
|
+
if (sessionId) {
|
|
4137
|
+
// The lock primitive ships beside this hook; resolve it from the hook's own install dir so a
|
|
4138
|
+
// workspace whose runtime copy is absent/partial still takes the same lock (never unlocked).
|
|
4139
|
+
const lockModule = path.join(process.env.HOOK_DIR || path.join(projectRoot, '.claude', 'hooks'), '..', 'ukit', 'runtime', 'async-lock.mjs');
|
|
4140
|
+
const { withAsyncLock } = await import(pathToFileURL(lockModule).href);
|
|
4141
|
+
const sidecar = path.join(projectRoot, '.ukit/storage/cache/route-state', `${sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`);
|
|
4142
|
+
const result = await withAsyncLock(sidecar, {}, async () => {
|
|
4143
|
+
if (recoveryOwner) {
|
|
4144
|
+
let route;
|
|
4145
|
+
let missing = false;
|
|
4146
|
+
try { route = JSON.parse(await fsp.readFile(sidecar, 'utf8')); }
|
|
4147
|
+
catch (error) { if (error.code !== 'ENOENT') throw new Error('existing session route unavailable'); missing = true; }
|
|
4148
|
+
if (!missing && (!route || !route.taskInstanceId || route.sessionId !== sessionId || route.taskInstanceId !== recoveryOwner.taskInstanceId || route.routeGeneration !== recoveryOwner.routeGeneration)) {
|
|
4149
|
+
throw new Error('recovery would overwrite another task route');
|
|
4150
|
+
}
|
|
4151
|
+
} else if (!handoffSkill && !handoffExpansion && await readRouteVersion() !== expectedRouteVersion) {
|
|
4152
|
+
throw new Error('session route changed before write');
|
|
4153
|
+
}
|
|
4154
|
+
const persisted = await persistRouteStateLocked(text);
|
|
4155
|
+
expectedRouteVersion = await readRouteVersion();
|
|
4156
|
+
return persisted;
|
|
4157
|
+
});
|
|
4158
|
+
if (!result.ok) throw new Error(`session route lock ${result.reason}`);
|
|
4159
|
+
return result.value;
|
|
4160
|
+
}
|
|
4161
|
+
return persistRouteStateLocked(text);
|
|
4162
|
+
}
|
|
4163
|
+
async function persistRouteStateLocked(text) {
|
|
4119
4164
|
const persisted = JSON.parse(text);
|
|
4120
4165
|
persisted.taskInstanceId = taskInstanceId;
|
|
4166
|
+
// The task identity is minted on a fresh owner prompt and retained only on
|
|
4167
|
+
// the router's continuation lineage. It is also the route generation.
|
|
4168
|
+
persisted.routeGeneration = taskInstanceId;
|
|
4121
4169
|
// Bounded audit metadata (short strings, additive): where this turn's task id and
|
|
4122
4170
|
// contract came from — 'system' marks a synthetic continuation that resumed the
|
|
4123
4171
|
// previous task instead of minting a fresh one. No consumer branches on these yet.
|
|
4124
4172
|
persisted.taskIdOrigin = continuingTask ? (systemOriginTurn ? 'system' : 'continue') : 'fresh';
|
|
4173
|
+
// A handoff binding follows only the same routed task; cached routes must
|
|
4174
|
+
// never carry a prior task's run identity into a fresh owner prompt.
|
|
4175
|
+
if (handoffRunId) persisted.handoffRunId = handoffRunId;
|
|
4176
|
+
else if (continuingTask && previous.handoffRunId) persisted.handoffRunId = previous.handoffRunId;
|
|
4177
|
+
else delete persisted.handoffRunId;
|
|
4125
4178
|
if (continuingTask && previous.routingContext?.lastExplicitUserPromptText) {
|
|
4126
4179
|
persisted.routingContext ||= {};
|
|
4127
4180
|
persisted.routingContext.lastExplicitUserPromptText = previous.routingContext.lastExplicitUserPromptText;
|
|
@@ -4290,30 +4343,67 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4290
4343
|
persisted.semanticProvenance = { engineVersion: analysis.engineVersion, actions: analysis.actions,
|
|
4291
4344
|
spans: analysis.spans.map(({ raw, ...span }) => span) };
|
|
4292
4345
|
}
|
|
4346
|
+
// Persistence revision prevents byte-identical ABA; it is not ownership authority.
|
|
4347
|
+
if (sessionId) persisted.routePersistenceRevision = crypto.randomUUID();
|
|
4293
4348
|
text = JSON.stringify(persisted);
|
|
4294
|
-
|
|
4295
|
-
|
|
4349
|
+
// Publication: pending marker -> shared write -> final sidecar (the commit point). We hold the sidecar
|
|
4350
|
+
// lock, so no other route writer can change either file in between: when the shared write fails and the
|
|
4351
|
+
// shared slot is provably unchanged, restore the previous committed sidecar instead of stranding a
|
|
4352
|
+
// pending marker that would make a still-valid previous route unreadable.
|
|
4353
|
+
const readOrNull = async (file) => { try { return await fsp.readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
|
|
4354
|
+
const priorSidecar = sessionId ? await readOrNull(sessionRoutePath) : null;
|
|
4355
|
+
const priorShared = sessionId ? await readOrNull(statePath) : null;
|
|
4356
|
+
if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true }));
|
|
4296
4357
|
try {
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
if (
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4358
|
+
await writeJsonFileAtomic(statePath, text);
|
|
4359
|
+
} catch (error) {
|
|
4360
|
+
if (sessionId) {
|
|
4361
|
+
let sharedNow;
|
|
4362
|
+
try { sharedNow = await readOrNull(statePath); } catch { sharedNow = undefined; }
|
|
4363
|
+
if (sharedNow !== undefined && sharedNow === priorShared) {
|
|
4364
|
+
try {
|
|
4365
|
+
if (priorSidecar === null) await fsp.rm(sessionRoutePath, { force: true });
|
|
4366
|
+
else await writeJsonFileAtomic(sessionRoutePath, priorSidecar);
|
|
4367
|
+
} catch { /* the pending marker stays: readers fail closed */ }
|
|
4305
4368
|
}
|
|
4306
4369
|
}
|
|
4307
|
-
|
|
4370
|
+
throw error;
|
|
4371
|
+
}
|
|
4372
|
+
// Read-back verification is only meaningful under the session sidecar lock; sessionless
|
|
4373
|
+
// routers share the slot unserialized, so a newer legitimate write is not a failed one.
|
|
4374
|
+
if (sessionId) {
|
|
4375
|
+
const readBack = await fsp.readFile(statePath, 'utf8');
|
|
4376
|
+
let foreign = false;
|
|
4377
|
+
if (readBack !== text) { try { foreign = String(JSON.parse(readBack)?.sessionId || '').trim() !== sessionId; } catch {} }
|
|
4378
|
+
// Another session may legitimately publish to the single shared slot right after our rename;
|
|
4379
|
+
// only a same-session mismatch (or unreadable bytes) means our own write did not land.
|
|
4380
|
+
if (readBack !== text && !foreign) throw new Error('shared route verification failed');
|
|
4381
|
+
}
|
|
4382
|
+
if (!sessionId) return persisted;
|
|
4383
|
+
const dir = path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state');
|
|
4384
|
+
const sidecar = path.join(dir, `${String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`);
|
|
4385
|
+
await writeJsonFileAtomic(sidecar, text);
|
|
4386
|
+
if (await fsp.readFile(sidecar, 'utf8') !== text) throw new Error('sidecar route verification failed');
|
|
4308
4387
|
return persisted;
|
|
4309
4388
|
}
|
|
4389
|
+
expectedRouteVersion = sessionId ? await readRouteVersion() : null;
|
|
4310
4390
|
const storedPrevious = await readJson(statePath, {});
|
|
4311
4391
|
// The shared slot may belong to another session; recover only our owned sidecar.
|
|
4312
|
-
const
|
|
4392
|
+
const sessionSidecarRead = sessionId
|
|
4313
4393
|
? await readJson(path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`), {})
|
|
4314
4394
|
: {};
|
|
4395
|
+
const sidecarPrevious = sessionId && String(storedPrevious?.sessionId || '').trim() !== sessionId ? sessionSidecarRead : {};
|
|
4396
|
+
// Only a COMMITTED publication is a previous route: a pending marker, or a shared document whose
|
|
4397
|
+
// revision the sidecar never confirmed, is an interrupted write and must not seed task continuity.
|
|
4398
|
+
// Legacy state without a persistence revision keeps its old meaning.
|
|
4399
|
+
const publishedPrevious = (state) => {
|
|
4400
|
+
if (!sessionId || String(state?.sessionId || '').trim() !== sessionId) return true;
|
|
4401
|
+
if (state.routePublicationIncomplete || sessionSidecarRead.routePublicationIncomplete) return false;
|
|
4402
|
+
if (!state.routePersistenceRevision) return true;
|
|
4403
|
+
return sessionSidecarRead.routePersistenceRevision === state.routePersistenceRevision;
|
|
4404
|
+
};
|
|
4315
4405
|
let previous = sessionId
|
|
4316
|
-
? [storedPrevious, sidecarPrevious].find((state) => String(state?.sessionId || '').trim() === sessionId) || {}
|
|
4406
|
+
? [storedPrevious, sidecarPrevious].find((state) => String(state?.sessionId || '').trim() === sessionId && publishedPrevious(state)) || {}
|
|
4317
4407
|
: storedPrevious;
|
|
4318
4408
|
const continuationPrompt = /^(?:continue|resume|keep going|go on|proceed|tiep tuc|lam tiep)(?:\s+(?:with\s+)?(?:the\s+|this\s+)?(?:previous\s+|last\s+|current\s+|same\s+)?(?:implementation\s+)?(?:task|work))?(?:\s+(?:thoi|di|đi|nhe|nao|nua|a|ha|please|pls|now|then))*\s*[.!]?$/i.test(
|
|
4319
4409
|
extractPrompt(payload).normalize('NFD').replace(/[̀-ͯ]/g, '').trim());
|
|
@@ -4543,11 +4633,197 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4543
4633
|
if (previous.routeSummary?.continuationState?.required === false) return false;
|
|
4544
4634
|
return true;
|
|
4545
4635
|
})();
|
|
4546
|
-
const
|
|
4547
|
-
|
|
4636
|
+
const handoffSkill = payload.tool_name === 'Skill'
|
|
4637
|
+
&& /^(?:ukit:)?handoff-fullstack$/.test(String(payload.tool_input?.skill || ''));
|
|
4638
|
+
const handoffExpansion = payload.hook_event_name === 'UserPromptExpansion'
|
|
4639
|
+
&& payload.expansion_type === 'slash_command'
|
|
4640
|
+
&& /^(?:ukit:)?handoff-fullstack$/.test(String(payload.command_name || ''));
|
|
4641
|
+
const continuingTask = Boolean(previous.taskInstanceId && (payload.tool_name || handoffExpansion || continuationPrompt || systemOriginTurn || guidanceTurn));
|
|
4642
|
+
let taskInstanceId = continuingTask
|
|
4548
4643
|
? previous.taskInstanceId
|
|
4549
4644
|
: `task-${crypto.randomBytes(16).toString("hex")}`;
|
|
4645
|
+
// OMP prompt text can contain an identical heading without a command
|
|
4646
|
+
// invocation, so it is not sufficient evidence for creating provenance.
|
|
4647
|
+
// The Skill registration exists solely for this invocation; other skills must
|
|
4648
|
+
// not reroute or overwrite the current task as if they were user prompts.
|
|
4649
|
+
if (payload.tool_name === 'Skill' && !handoffSkill) process.exit(0);
|
|
4650
|
+
let handoffRunId = continuingTask ? previous.handoffRunId : null;
|
|
4651
|
+
const denyHandoff = (reason) => {
|
|
4652
|
+
const message = `UKit handoff resume BLOCKED: ${reason}; cursor untouched.`;
|
|
4653
|
+
process.stdout.write(JSON.stringify(handoffExpansion
|
|
4654
|
+
? { decision: 'block', reason: message }
|
|
4655
|
+
: { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: message } }));
|
|
4656
|
+
process.exit(0);
|
|
4657
|
+
};
|
|
4658
|
+
async function denyCommittedHandoff(provenance, runId, error) {
|
|
4659
|
+
try {
|
|
4660
|
+
await provenance.withHandoffOwner({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration: taskInstanceId }, async () => {
|
|
4661
|
+
const ownership = await provenance.resolveHandoffApplicability({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration: taskInstanceId });
|
|
4662
|
+
if (ownership.status !== 'OWNED') throw new Error('authority unavailable');
|
|
4663
|
+
denyHandoff(`committed-but-unreconciled: ${String(error.message).slice(0, 100)}. RunId ${runId}, generation ${ownership.generation}. Run /ukit:handoff-fullstack --recover-run=${runId} --generation=${ownership.generation}`);
|
|
4664
|
+
});
|
|
4665
|
+
} catch {}
|
|
4666
|
+
denyHandoff(String(error.message).slice(0, 160));
|
|
4667
|
+
}
|
|
4668
|
+
if ((handoffSkill || handoffExpansion) && !sessionId) denyHandoff('missing session identity');
|
|
4669
|
+
if ((handoffSkill || handoffExpansion) && sessionId) {
|
|
4670
|
+
const provenance = await import(pathToFileURL(path.join(projectRoot, '.claude/ukit/runtime/handoff-provenance.mjs')).href);
|
|
4671
|
+
const args = String(handoffExpansion ? payload.command_args || '' : payload.tool_input?.args || '').trim();
|
|
4672
|
+
const resume = /^--resume-run=(handoff-[a-f0-9]{64})$/.exec(args);
|
|
4673
|
+
const recovery = /^--recover-run=(handoff-[a-f0-9]{64}) --generation=(0|[1-9][0-9]*)$/.exec(args);
|
|
4674
|
+
const adopt = /^--adopt-legacy-run=(handoff-[a-f0-9]{64})$/.exec(args);
|
|
4675
|
+
if (args.includes('--recover-run') || args.includes('--generation')) {
|
|
4676
|
+
if (!recovery || !Number.isSafeInteger(Number(recovery[2]))) denyHandoff('explicit recovery requires --recover-run=<RunId> --generation=<generation>');
|
|
4677
|
+
if (handoffSkill) {
|
|
4678
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4679
|
+
const owner = ownership.claim || ownership.binding;
|
|
4680
|
+
if (ownership.status !== 'OWNED' || ownership.generation !== Number(recovery[2])
|
|
4681
|
+
|| owner?.runId !== recovery[1] || owner?.taskInstanceId !== taskInstanceId) {
|
|
4682
|
+
denyHandoff('recovery requires a reconciled route for the committed owner');
|
|
4683
|
+
}
|
|
4684
|
+
process.exit(0);
|
|
4685
|
+
}
|
|
4686
|
+
try {
|
|
4687
|
+
await provenance.withHandoffRecovery({ projectRoot, sessionId, runId: recovery[1], generation: Number(recovery[2]) }, async owner => {
|
|
4688
|
+
const cursor = await fs.promises.readFile(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8');
|
|
4689
|
+
const ids = [...cursor.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
|
|
4690
|
+
if (ids.length !== 1 || ids[0][1] !== recovery[1]) throw new Error('target cursor identity mismatch');
|
|
4691
|
+
taskInstanceId = owner.taskInstanceId;
|
|
4692
|
+
if (owner.routeGeneration !== taskInstanceId) throw new Error('unsupported recovery route generation');
|
|
4693
|
+
handoffRunId = recovery[1];
|
|
4694
|
+
await persistRouteState(JSON.stringify({ sessionId, ts: Date.now(), source: 'skill-router-handoff-recovery' }), owner);
|
|
4695
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4696
|
+
if (ownership.status !== 'OWNED' || ownership.generation !== owner.generation) throw new Error('recovery route unavailable');
|
|
4697
|
+
});
|
|
4698
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptExpansion', additionalContext: `UKit handoff recovery RunId: ${handoffRunId}; generation ${recovery[2]}. Ownership is unchanged; pause remains unchanged.` } }));
|
|
4699
|
+
process.exit(0);
|
|
4700
|
+
} catch (error) { await denyCommittedHandoff(provenance, recovery[1], error); }
|
|
4701
|
+
}
|
|
4702
|
+
if (args.includes('--adopt-legacy-run') && !adopt) {
|
|
4703
|
+
denyHandoff('explicit legacy adoption requires exactly --adopt-legacy-run=<RunId>');
|
|
4704
|
+
}
|
|
4705
|
+
if (adopt && handoffSkill) {
|
|
4706
|
+
// The model-driven Skill path never adopts: it only confirms the owner's expansion already did.
|
|
4707
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4708
|
+
const owner = ownership.claim || ownership.binding;
|
|
4709
|
+
if (ownership.status !== 'OWNED' || owner?.runId !== adopt[1] || owner?.taskInstanceId !== taskInstanceId || owner?.routeGeneration !== taskInstanceId) {
|
|
4710
|
+
denyHandoff('legacy adoption requires the owner\'s explicit slash-command invocation');
|
|
4711
|
+
}
|
|
4712
|
+
handoffRunId = adopt[1];
|
|
4713
|
+
} else if (adopt) {
|
|
4714
|
+
// Explicit owner-invoked migration only: never reached from session start, Stop or an ordinary prompt.
|
|
4715
|
+
taskInstanceId = `task-${crypto.randomBytes(16).toString('hex')}`;
|
|
4716
|
+
try {
|
|
4717
|
+
await provenance.adoptLegacyHandoffRun({ projectRoot, sessionId, taskInstanceId, routeGeneration: taskInstanceId, runId: adopt[1] });
|
|
4718
|
+
} catch (error) {
|
|
4719
|
+
denyHandoff(`legacy adoption refused: ${String(error.message).slice(0, 120)}. An interrupted adoption by this session is finished by re-invoking --adopt-legacy-run=${adopt[1]}; once the cursor carries the RunId use --resume-run=${adopt[1]}`);
|
|
4720
|
+
}
|
|
4721
|
+
handoffRunId = adopt[1];
|
|
4722
|
+
}
|
|
4723
|
+
if (!adopt && args.includes('--resume-run') && !resume) {
|
|
4724
|
+
denyHandoff('an explicit user invocation with exactly --resume-run=<RunId> is required');
|
|
4725
|
+
}
|
|
4726
|
+
if (adopt) {
|
|
4727
|
+
// Identity is committed above; the shared route publication below binds the route to it.
|
|
4728
|
+
} else if (resume && handoffSkill) {
|
|
4729
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4730
|
+
if (ownership.status !== 'OWNED' || !ownership.claim || ownership.claim.runId !== resume[1]
|
|
4731
|
+
|| ownership.claim.taskInstanceId !== taskInstanceId || ownership.claim.routeGeneration !== taskInstanceId) {
|
|
4732
|
+
denyHandoff('resume requires an active claim from the current user invocation');
|
|
4733
|
+
}
|
|
4734
|
+
handoffRunId = resume[1];
|
|
4735
|
+
} else if (resume) {
|
|
4736
|
+
// A new explicit invocation is not a verified redelivery of the prior task.
|
|
4737
|
+
taskInstanceId = `task-${crypto.randomBytes(16).toString('hex')}`;
|
|
4738
|
+
try {
|
|
4739
|
+
const cursor = await fs.promises.readFile(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8');
|
|
4740
|
+
const ids = [...cursor.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
|
|
4741
|
+
if (ids.length !== 1 || ids[0][1] !== resume[1]) throw new Error('target cursor identity mismatch');
|
|
4742
|
+
const current = await provenance.resolveHandoffApplicability({ projectRoot, sessionId, taskInstanceId, runId: resume[1], routeGeneration: taskInstanceId });
|
|
4743
|
+
if (current.status === 'UNKNOWN') throw new Error('handoff authority unavailable');
|
|
4744
|
+
// Do not publish route identity until the ownership commit succeeds.
|
|
4745
|
+
// Without a verified redelivery identity, interruption may require a new
|
|
4746
|
+
// explicit transfer rather than treating session identity as a retry.
|
|
4747
|
+
await provenance.claimHandoffResume({ projectRoot, sessionId, taskInstanceId, runId: resume[1], routeGeneration: taskInstanceId });
|
|
4748
|
+
handoffRunId = resume[1];
|
|
4749
|
+
} catch (error) {
|
|
4750
|
+
await denyCommittedHandoff(provenance, resume[1], error);
|
|
4751
|
+
}
|
|
4752
|
+
} else {
|
|
4753
|
+
try {
|
|
4754
|
+
let cursor;
|
|
4755
|
+
try { cursor = await fs.promises.readFile(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8'); }
|
|
4756
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
4757
|
+
let ownsLiveCursor = false;
|
|
4758
|
+
if (cursor != null) {
|
|
4759
|
+
const phase = /^Phase:\s*(\S+)\s*$/im.exec(cursor)?.[1]?.toLowerCase();
|
|
4760
|
+
if (!phase || !['done', 'blocked'].includes(phase)) {
|
|
4761
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4762
|
+
const owner = ownership.claim || ownership.binding;
|
|
4763
|
+
if (ownership.status !== 'OWNED' || !continuingTask || !handoffRunId || owner?.taskInstanceId !== taskInstanceId
|
|
4764
|
+
|| owner?.routeGeneration !== taskInstanceId || owner?.runId !== handoffRunId) {
|
|
4765
|
+
if (handoffExpansion && ownership.status === 'UNKNOWN') {
|
|
4766
|
+
const ids = [...cursor.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
|
|
4767
|
+
if (ids.length === 1 && /^handoff-[a-f0-9]{64}$/.test(ids[0][1])) {
|
|
4768
|
+
try {
|
|
4769
|
+
const committed = await provenance.currentHandoffRecovery({ projectRoot, sessionId, runId: ids[0][1] });
|
|
4770
|
+
denyHandoff(`committed-but-unreconciled. RunId ${ids[0][1]}, generation ${committed.generation}. Run /ukit:handoff-fullstack --recover-run=${ids[0][1]} --generation=${committed.generation}`);
|
|
4771
|
+
} catch {}
|
|
4772
|
+
}
|
|
4773
|
+
}
|
|
4774
|
+
const legacy = await provenance.describeLegacyHandoffCursor({ runRoot: projectRoot });
|
|
4775
|
+
if (legacy) throw new Error(`live cursor has no RunId (legacy run). To adopt it as this session's run, invoke /ukit:handoff-fullstack --adopt-legacy-run=${legacy.runId}`);
|
|
4776
|
+
throw new Error('live cursor requires explicit --resume-run=<RunId>');
|
|
4777
|
+
}
|
|
4778
|
+
ownsLiveCursor = true;
|
|
4779
|
+
}
|
|
4780
|
+
}
|
|
4781
|
+
handoffRunId ||= `handoff-${crypto.createHash('sha256').update(`${sessionId}\0${taskInstanceId}`).digest('hex')}`;
|
|
4782
|
+
if (!ownsLiveCursor) await provenance.bindHandoffRun({ projectRoot, sessionId, taskInstanceId, runId: handoffRunId, routeGeneration: taskInstanceId });
|
|
4783
|
+
} catch (error) { denyHandoff(String(error.message).slice(0, 360)); }
|
|
4784
|
+
}
|
|
4785
|
+
}
|
|
4550
4786
|
const runtimeConfig = await loadRuntimeConfig(projectRoot);
|
|
4787
|
+
if (handoffSkill || handoffExpansion) {
|
|
4788
|
+
try {
|
|
4789
|
+
const provenance = await import(pathToFileURL(path.join(projectRoot, '.claude/ukit/runtime/handoff-provenance.mjs')).href);
|
|
4790
|
+
await provenance.withHandoffOwner({ projectRoot, sessionId, taskInstanceId, runId: handoffRunId, routeGeneration: taskInstanceId }, async () => {
|
|
4791
|
+
await persistRouteState(JSON.stringify({ ...previous, sessionId, ts: Date.now(), source: 'skill-router-handoff-start' }));
|
|
4792
|
+
if (handoffExpansion && handoffRunId) {
|
|
4793
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4794
|
+
const owner = ownership.claim || ownership.binding;
|
|
4795
|
+
if (ownership.status === 'OWNED' && owner?.taskInstanceId === taskInstanceId && owner?.runId === handoffRunId) {
|
|
4796
|
+
const cursorPath = path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md');
|
|
4797
|
+
const cursor = await fs.promises.readFile(cursorPath, 'utf8');
|
|
4798
|
+
const cursorIds = [...cursor.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
|
|
4799
|
+
if (cursorIds.length !== 1 || cursorIds[0][1] !== handoffRunId) throw new Error('cursor identity changed before pause lift');
|
|
4800
|
+
if (/^Paused:\s*yes\s*$/im.test(cursor)) {
|
|
4801
|
+
const next = cursor.replace(/^(Paused:\s*)yes(\s*)$/im, '$1no$2');
|
|
4802
|
+
if (await fs.promises.readFile(cursorPath, 'utf8') !== cursor) throw new Error('cursor changed before pause lift');
|
|
4803
|
+
const tmp = `${cursorPath}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
4804
|
+
try {
|
|
4805
|
+
await fs.promises.writeFile(tmp, next, { flag: 'wx' });
|
|
4806
|
+
await fs.promises.rename(tmp, cursorPath);
|
|
4807
|
+
} finally { await fs.promises.rm(tmp, { force: true }).catch(() => {}); }
|
|
4808
|
+
if (await fs.promises.readFile(cursorPath, 'utf8') !== next) throw new Error('pause lift verification failed');
|
|
4809
|
+
}
|
|
4810
|
+
}
|
|
4811
|
+
}
|
|
4812
|
+
});
|
|
4813
|
+
} catch (error) {
|
|
4814
|
+
const provenance = await import(pathToFileURL(path.join(projectRoot, '.claude/ukit/runtime/handoff-provenance.mjs')).href);
|
|
4815
|
+
await denyCommittedHandoff(provenance, handoffRunId, error);
|
|
4816
|
+
}
|
|
4817
|
+
if (handoffRunId) {
|
|
4818
|
+
process.stdout.write(JSON.stringify({
|
|
4819
|
+
hookSpecificOutput: {
|
|
4820
|
+
hookEventName: handoffExpansion ? 'UserPromptExpansion' : 'PreToolUse',
|
|
4821
|
+
additionalContext: `UKit handoff invocation RunId: ${handoffRunId}. Preserve this exact identity in RUN.md through every rewrite, cycle and resume.`,
|
|
4822
|
+
},
|
|
4823
|
+
}));
|
|
4824
|
+
}
|
|
4825
|
+
process.exit(0);
|
|
4826
|
+
}
|
|
4551
4827
|
// BL-013: the hook/bridge payload's transcript pointer (ukit-bridge.js:217,228
|
|
4552
4828
|
// forwards transcriptPath; Claude Code payloads carry transcript_path). The
|
|
4553
4829
|
// extractor reads a bounded tail of this file — never the whole transcript.
|
|
@@ -5118,7 +5394,7 @@ if [ -f "$THRESHOLD_SCRIPT" ]; then
|
|
|
5118
5394
|
# PostToolUse call used to pay a second full node spawn for that no-op, doubling the
|
|
5119
5395
|
# per-mutation hook latency. Tool payloads always carry tool_name; skip them.
|
|
5120
5396
|
case "$INPUT" in
|
|
5121
|
-
*'"tool_name"'*) ;;
|
|
5397
|
+
*'"tool_name"'*|*'"UserPromptExpansion"'*) ;;
|
|
5122
5398
|
*) printf '%s' "$INPUT" | CLAUDE_PROJECT_DIR="$PROJECT_ROOT" node "$THRESHOLD_SCRIPT" prompt 2>/dev/null || true ;;
|
|
5123
5399
|
esac
|
|
5124
5400
|
fi
|
|
@@ -384,7 +384,14 @@ if (!command) {
|
|
|
384
384
|
|
|
385
385
|
const statePath = process.env.STATE_FILE;
|
|
386
386
|
const progressPath = process.env.PROGRESS_FILE;
|
|
387
|
-
|
|
387
|
+
let state = await readJson(statePath, null);
|
|
388
|
+
// Advisory reader: a pending or unconfirmed route publication is an interrupted write, not a route.
|
|
389
|
+
if (state && state.sessionId) {
|
|
390
|
+
const owner = String(state.sessionId).trim().replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
|
|
391
|
+
const committed = await readJson(path.join(process.env.PROJECT_ROOT || '', '.ukit', 'storage', 'cache', 'route-state', `${owner}.json`), {});
|
|
392
|
+
if (state.routePublicationIncomplete || committed.routePublicationIncomplete
|
|
393
|
+
|| (state.routePersistenceRevision && committed.routePersistenceRevision !== state.routePersistenceRevision)) state = null;
|
|
394
|
+
}
|
|
388
395
|
const routeCache = await readJson(process.env.ROUTE_CACHE_FILE, null);
|
|
389
396
|
const recommendation = state?.verificationRecommendation ?? null;
|
|
390
397
|
const routeSummary = state?.routeSummary ?? null;
|
|
@@ -79,6 +79,16 @@
|
|
|
79
79
|
}
|
|
80
80
|
]
|
|
81
81
|
},
|
|
82
|
+
{
|
|
83
|
+
"matcher": "Skill",
|
|
84
|
+
"hooks": [
|
|
85
|
+
{
|
|
86
|
+
"type": "command",
|
|
87
|
+
"command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/skill-router.sh\":20",
|
|
88
|
+
"timeout": 30
|
|
89
|
+
}
|
|
90
|
+
]
|
|
91
|
+
},
|
|
82
92
|
{
|
|
83
93
|
"matcher": "MultiEdit|NotebookEdit|Agent|Task",
|
|
84
94
|
"hooks": [
|
|
@@ -164,6 +174,18 @@
|
|
|
164
174
|
]
|
|
165
175
|
}
|
|
166
176
|
],
|
|
177
|
+
"UserPromptExpansion": [
|
|
178
|
+
{
|
|
179
|
+
"matcher": "^(ukit:)?handoff-fullstack$",
|
|
180
|
+
"hooks": [
|
|
181
|
+
{
|
|
182
|
+
"type": "command",
|
|
183
|
+
"command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/skill-router.sh\":20",
|
|
184
|
+
"timeout": 30
|
|
185
|
+
}
|
|
186
|
+
]
|
|
187
|
+
}
|
|
188
|
+
],
|
|
167
189
|
"UserPromptSubmit": [
|
|
168
190
|
{
|
|
169
191
|
"hooks": [
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Canonical task semantics; intent never grants authorization or proves completion.
|
|
2
2
|
import crypto from 'node:crypto';
|
|
3
|
-
export const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:
|
|
3
|
+
export const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:287d478b06a81ac1f9fcc1c53fd00217ab13bf6af53aca3bd662df0989e30b5e';
|
|
4
4
|
|
|
5
5
|
export function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
|
|
6
6
|
return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
|
|
@@ -82,7 +82,8 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
|
|
|
82
82
|
}
|
|
83
83
|
for (const span of [...spans].reverse()) {
|
|
84
84
|
const approvalPending = span.condition && /\b(?:approv\w*|permission|authori[sz]\w*)\b/.test(span.condition);
|
|
85
|
-
|
|
85
|
+
const evidenceStatement = /^\s*git\s+commit\s*(?:\/|va)\s*github\s+release\s+khong\s+(?:duoc tinh la hoan thanh|phai\s+(?:la\s+)?(?:san pham\s+)?(?:hoan tat|hoan thanh))\s*[.!]?\s*$/.test(foldIntent(span.raw));
|
|
86
|
+
if (span.context === 'quotation' || span.context === 'description' || approvalPending || deferredSpans.has(span) || evidenceStatement) {
|
|
86
87
|
// Retain the prefix before a comma-introduced postfix repair condition.
|
|
87
88
|
// Leading conditions and otherwise consequences are masked in full.
|
|
88
89
|
const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|otherwise)\b/.test(foldIntent(span.raw))
|
|
@@ -209,9 +210,13 @@ export function publicationScope(promptText = '') {
|
|
|
209
210
|
const bullet = /^\s*(?:[-*•]|\d+[.)])\s+/.test(line);
|
|
210
211
|
if (!bullet) prohibitionBlock = PUBLISH_ORDER_NEGATOR.test(line) && /:\s*$/.test(line);
|
|
211
212
|
for (const clause of line.split(/;|\.\s+|\bthen\b|\bbut\b|\binstead\b/)) {
|
|
213
|
+
// A temporary restriction pending prerequisites is not a task-wide prohibition.
|
|
214
|
+
// This classification does not authorize execution or establish those prerequisites.
|
|
212
215
|
let negated = bullet && prohibitionBlock;
|
|
213
216
|
for (const raw of clause.split(/,|\band\b|\bor\b|\bnor\b/)) {
|
|
214
217
|
const item = raw.replace(/^[\s*•-]+/, '').trim();
|
|
218
|
+
if (/\b(?:do not|don't|must not|not yet)\b[^,]*\b(?:publish|publication|release)\b[^,]*\b(?:while|until|before)\b/.test(item)
|
|
219
|
+
|| /\b(?:publish|publication|release)\b[^,]*\b(?:must not|not yet)\b[^,]*\b(?:until|before|while)\b/.test(item)) continue;
|
|
215
220
|
if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
|
|
216
221
|
else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
|
|
217
222
|
if (negated && /\b(?:release|publish|publication)\b/.test(item)) prohibited = true;
|
|
@@ -1323,6 +1323,18 @@ async function main() {
|
|
|
1323
1323
|
const sharedStatePath = path.join(rootDir, '.claude', 'ukit', 'skill-router-state.json');
|
|
1324
1324
|
const routeCachePath = path.join(rootDir, '.claude', 'ukit', 'route-cache.json');
|
|
1325
1325
|
const routeAuditPath = path.join(rootDir, '.ukit', 'storage', 'cache', 'route-audit.json');
|
|
1326
|
+
const requestedSession = normalizeSessionId(readFlagValue(args, '--session-id'));
|
|
1327
|
+
const sessionRoutePath = requestedSession && path.join(rootDir, '.ukit', 'storage', 'cache', 'route-state', `${requestedSession.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`);
|
|
1328
|
+
let expectedRouteBytes = null;
|
|
1329
|
+
if (sessionRoutePath) {
|
|
1330
|
+
try {
|
|
1331
|
+
expectedRouteBytes = await fs.readFile(sessionRoutePath, 'utf8');
|
|
1332
|
+
const route = JSON.parse(expectedRouteBytes);
|
|
1333
|
+
if (!route || route.sessionId !== requestedSession || !route.taskInstanceId) throw new Error('invalid session route');
|
|
1334
|
+
} catch (error) {
|
|
1335
|
+
if (error.code !== 'ENOENT') throw new Error('existing session route unavailable');
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1326
1338
|
const persistedPreviousState = await readJson(sharedStatePath, {});
|
|
1327
1339
|
// BL-017 (SPEC FR-005): detached hook-path shadow pass — skill-router.sh
|
|
1328
1340
|
// spawns this fire-and-forget per emitted route. Self-deadline so a wedged
|
|
@@ -1343,9 +1355,20 @@ async function main() {
|
|
|
1343
1355
|
const sessionSidecar = previousStateOwnershipBlocked && sessionId
|
|
1344
1356
|
? await readJson(path.join(rootDir, '.ukit', 'storage', 'cache', 'route-state', `${sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`), {})
|
|
1345
1357
|
: {};
|
|
1346
|
-
const
|
|
1358
|
+
const candidatePreviousState = previousStateOwnershipBlocked
|
|
1347
1359
|
? (isRouteStateCompatible(sessionSidecar, sessionId) && sessionSidecar.sessionId === sessionId ? sessionSidecar : {})
|
|
1348
1360
|
: persistedPreviousState;
|
|
1361
|
+
// Only a committed publication seeds the previous route: a pending marker, or a shared document whose
|
|
1362
|
+
// revision the sidecar never confirmed, is an interrupted write. Legacy state without a revision is kept.
|
|
1363
|
+
const previousState = !sessionId || !isRouteStateCompatible(candidatePreviousState, sessionId)
|
|
1364
|
+
? candidatePreviousState
|
|
1365
|
+
: candidatePreviousState.routePublicationIncomplete ? {}
|
|
1366
|
+
: await (async () => {
|
|
1367
|
+
const committed = await readJson(path.join(rootDir, '.ukit', 'storage', 'cache', 'route-state', `${sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`), {});
|
|
1368
|
+
if (committed.routePublicationIncomplete) return {};
|
|
1369
|
+
if (!candidatePreviousState.routePersistenceRevision) return candidatePreviousState;
|
|
1370
|
+
return committed.routePersistenceRevision === candidatePreviousState.routePersistenceRevision ? candidatePreviousState : {};
|
|
1371
|
+
})();
|
|
1349
1372
|
const escalationConfig = await readMergedConfig(rootDir);
|
|
1350
1373
|
const targetFile = readFlagValue(args, '--target');
|
|
1351
1374
|
const taskType = readFlagValue(args, '--type');
|
|
@@ -1496,7 +1519,7 @@ async function main() {
|
|
|
1496
1519
|
}
|
|
1497
1520
|
const sharedState = carryGuidanceState({ ...reusableState, taskInstanceId, taskIdOrigin, source: 'task-route', ts: Date.now() });
|
|
1498
1521
|
if (canPersistRouteState) {
|
|
1499
|
-
try { await
|
|
1522
|
+
try { await requirePersistedRouteState(sharedStatePath, sharedState, { expectedRouteBytes }); }
|
|
1500
1523
|
catch (error) { console.error(`route-task: state persist degraded — ${error?.message ?? error}`); }
|
|
1501
1524
|
}
|
|
1502
1525
|
printRouteState(sharedState);
|
|
@@ -1597,7 +1620,7 @@ async function main() {
|
|
|
1597
1620
|
// Advisory persistence — an EACCES/ENOSPC under the lock must never lose
|
|
1598
1621
|
// the printed route; degrade to stderr and print anyway.
|
|
1599
1622
|
try {
|
|
1600
|
-
await
|
|
1623
|
+
await requirePersistedRouteState(sharedStatePath, sharedState, { expectedRouteBytes });
|
|
1601
1624
|
await appendRouteAuditEntry(routeAuditPath, buildRouteAuditEntry({
|
|
1602
1625
|
state: sharedState,
|
|
1603
1626
|
}));
|
|
@@ -1655,7 +1678,7 @@ async function main() {
|
|
|
1655
1678
|
// Advisory persistence — an EACCES/ENOSPC under the lock must never lose
|
|
1656
1679
|
// the printed route; degrade to stderr and print anyway.
|
|
1657
1680
|
try {
|
|
1658
|
-
await
|
|
1681
|
+
await requirePersistedRouteState(sharedStatePath, sharedState, { expectedRouteBytes });
|
|
1659
1682
|
await appendRouteAuditEntry(routeAuditPath, buildRouteAuditEntry({
|
|
1660
1683
|
route,
|
|
1661
1684
|
state: sharedState,
|
|
@@ -6399,21 +6422,57 @@ export async function writeJsonAtomic(filePath, value) {
|
|
|
6399
6422
|
// writer mid-flight. Fail-closed (CX-8): a busy lock skips the write — the next
|
|
6400
6423
|
// route recomputes and overwrites the whole document anyway, so a skipped
|
|
6401
6424
|
// overwrite loses nothing; an unlocked one can interleave with a live holder.
|
|
6402
|
-
export async function persistSharedRouteState(filePath, state) {
|
|
6403
|
-
const result = await withAsyncLock(filePath, {}, () => writeJsonAtomic(filePath, state));
|
|
6404
|
-
if (!result.ok) {
|
|
6405
|
-
console.error(`route-task: skill-router-state lock ${result.reason} after ${result.waitedMs}ms — state write skipped (fail-closed)`);
|
|
6406
|
-
}
|
|
6407
|
-
// Per-session sidecar (see skill-router.sh persistRouteState): survives a concurrent session
|
|
6408
|
-
// overwriting the shared single-slot file. Best-effort; keyed by the state's own owner.
|
|
6425
|
+
export async function persistSharedRouteState(filePath, state, { expectedRouteBytes } = {}) {
|
|
6409
6426
|
const owner = normalizeSessionId(state?.sessionId);
|
|
6410
|
-
|
|
6411
|
-
|
|
6412
|
-
|
|
6413
|
-
|
|
6414
|
-
|
|
6415
|
-
|
|
6416
|
-
|
|
6427
|
+
const root = path.resolve(path.dirname(filePath), '..', '..');
|
|
6428
|
+
const safe = owner?.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
|
|
6429
|
+
const sidecar = owner && path.join(root, '.ukit', 'storage', 'cache', 'route-state', `${safe}.json`);
|
|
6430
|
+
if (sidecar && expectedRouteBytes === undefined) return { ok: false, reason: 'missing-expected-version', waitedMs: 0 };
|
|
6431
|
+
const write = async () => {
|
|
6432
|
+
let current = null;
|
|
6433
|
+
if (sidecar) {
|
|
6434
|
+
try { current = await fs.readFile(sidecar, 'utf8'); }
|
|
6435
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
6436
|
+
if (current !== expectedRouteBytes) return { ok: false, reason: 'stale', waitedMs: 0 };
|
|
6437
|
+
}
|
|
6438
|
+
// This is a persistence revision, not handoff ownership or generation.
|
|
6439
|
+
// Stamp every publication so an A → B → A route cannot recreate its old bytes.
|
|
6440
|
+
const published = sidecar ? { ...state, routePersistenceRevision: crypto.randomUUID() } : state;
|
|
6441
|
+
if (sidecar) await writeJsonAtomic(sidecar, { sessionId: owner, taskInstanceId: state.taskInstanceId, routeGeneration: state.routeGeneration, routePersistenceRevision: published.routePersistenceRevision, routePublicationIncomplete: true });
|
|
6442
|
+
// The sidecar lock is held, so no other route writer can publish meanwhile. When the shared write
|
|
6443
|
+
// did not happen (lock busy/failed) and the shared slot is provably unchanged, restore the previous
|
|
6444
|
+
// committed sidecar instead of stranding a pending marker over a still-valid route.
|
|
6445
|
+
const readBytes = async (file) => { try { return await fs.readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
|
|
6446
|
+
const priorShared = sidecar ? await readBytes(filePath) : null;
|
|
6447
|
+
const rollback = async () => {
|
|
6448
|
+
if (!sidecar) return;
|
|
6449
|
+
try {
|
|
6450
|
+
if (await readBytes(filePath) !== priorShared) return;
|
|
6451
|
+
if (current === null) await fs.rm(sidecar, { force: true });
|
|
6452
|
+
else {
|
|
6453
|
+
// Byte-exact: other writers compare the sidecar by its exact bytes.
|
|
6454
|
+
const tempPath = `${sidecar}.tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
|
|
6455
|
+
try { await fs.writeFile(tempPath, current, 'utf8'); await fs.rename(tempPath, sidecar); }
|
|
6456
|
+
catch (error) { await fs.rm(tempPath, { force: true }).catch(() => {}); throw error; }
|
|
6457
|
+
}
|
|
6458
|
+
} catch { /* the pending marker stays: readers fail closed */ }
|
|
6459
|
+
};
|
|
6460
|
+
let result;
|
|
6461
|
+
try { result = await withAsyncLock(filePath, {}, () => writeJsonAtomic(filePath, published)); }
|
|
6462
|
+
catch (error) { await rollback(); throw error; }
|
|
6463
|
+
if (!result.ok) { await rollback(); return result; }
|
|
6464
|
+
if (sidecar) await writeJsonAtomic(sidecar, published);
|
|
6465
|
+
return result;
|
|
6466
|
+
};
|
|
6467
|
+
const locked = sidecar ? await withAsyncLock(sidecar, {}, write) : { ok: true, value: await write() };
|
|
6468
|
+
const result = locked.ok ? locked.value : locked;
|
|
6469
|
+
if (!result.ok) console.error(`route-task: route lock ${result.reason} after ${result.waitedMs}ms — state write skipped (fail-closed)`);
|
|
6470
|
+
return result;
|
|
6471
|
+
}
|
|
6472
|
+
|
|
6473
|
+
async function requirePersistedRouteState(filePath, state, options) {
|
|
6474
|
+
const result = await persistSharedRouteState(filePath, state, options);
|
|
6475
|
+
if (!result.ok) throw new Error(`route state not persisted: ${result.reason}`);
|
|
6417
6476
|
return result;
|
|
6418
6477
|
}
|
|
6419
6478
|
|
|
@@ -102,6 +102,7 @@ export function readSessionRouteTaskKey(projectRoot, sessionId) {
|
|
|
102
102
|
if (!state || typeof state !== 'object') return null;
|
|
103
103
|
const owner = state.session_id ?? state.sessionId;
|
|
104
104
|
if (String(owner ?? '').trim() !== id) return null;
|
|
105
|
+
if (state.routePublicationIncomplete === true) return null; // pending publication is not a task identity
|
|
105
106
|
const key = state.taskInstanceId;
|
|
106
107
|
return typeof key === 'string' && key.trim() ? key.trim().slice(0, 120) : null;
|
|
107
108
|
} catch {
|