@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
|
@@ -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=f574f585962b045968832191d0a086cb6625965b80b751a893e663fba12b085d
|
|
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:d2c70fa8c68d50f31917ee7befd16f6df36a441a2aae79a0de879f5b0a09edf1';
|
|
207
207
|
|
|
208
208
|
function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
|
|
209
209
|
return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
|
|
@@ -213,7 +213,7 @@ function semanticContractIdentity({ promptText = '', targetFile = '', taskInstan
|
|
|
213
213
|
const semanticContractShape = (contract) => JSON.stringify([
|
|
214
214
|
contract?.taskKind, contract?.publication === true, contract?.operationGoal ?? null,
|
|
215
215
|
contract?.configurationScope ?? null, contract?.releasePolicy ?? null, contract?.conditionalObligations ?? null,
|
|
216
|
-
contract?.reportArtifact ?? null, contract?.verificationOnly === true, contract?.statusReport === true,
|
|
216
|
+
contract?.reportArtifact ?? null, contract?.verificationOnly === true, contract?.statusReport === true, contract?.stateVerification === true, contract?.stateAction === true, contract?.stateConditionalStop === true, (contract?.stateTargets || []).join(','),
|
|
217
217
|
[...(contract?.completionEvidence || [])].sort(),
|
|
218
218
|
]);
|
|
219
219
|
function compareSemanticContracts({ stored, fresh, previousIdentity, identity }) {
|
|
@@ -248,7 +248,7 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
|
|
|
248
248
|
const quoted = Boolean(marker || fence || /^\s*>/.test(raw));
|
|
249
249
|
const context = quoted ? 'quotation' : description && bullet ? 'description' : 'instruction';
|
|
250
250
|
const polarity = /\b(?:do not|don't|never|must not|no|khong|chua)\b|đừng/i.test(raw) || /\b(?:prohibited|forbidden|banned)\b/.test(text) ? 'prohibited' : 'affirmative';
|
|
251
|
-
const condition = text.match(/\b(?:if|neu|only if|only when)\b[^,;.\n]*/)?.[0] || null;
|
|
251
|
+
const condition = text.match(/\b(?:if|neu|only if|only when|only after|only once)\b[^,;.\n]*/)?.[0] || null;
|
|
252
252
|
spans.push({ start: offset + part.index, end: offset + part.index + raw.length, raw,
|
|
253
253
|
context, polarity, condition, activation: condition ? 'pending' : context !== 'instruction' || polarity === 'prohibited' ? 'inactive' : 'eligible' });
|
|
254
254
|
}
|
|
@@ -268,10 +268,23 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
|
|
|
268
268
|
const nativeReleasePolicy = classifySemanticText({ promptText: original, targetFile }).releasePolicy;
|
|
269
269
|
const deferredSpans = new Set(spans.filter(span => span.context === 'instruction'
|
|
270
270
|
&& span.polarity === 'affirmative' && span.condition
|
|
271
|
-
&& /^(?:[-*+•\d.)\s]*)(?:if|neu|only if|only when)\b/.test(foldIntent(span.raw))
|
|
271
|
+
&& /^(?:[-*+•\d.)\s]*)(?:if|neu|only if|only when|only after|only once)\b/.test(foldIntent(span.raw))
|
|
272
272
|
&& !nativeReleasePolicy && !VERIFICATION_GOAL.test(foldIntent(original))
|
|
273
273
|
&& !defectRepairBranches(foldIntent(span.raw)).length
|
|
274
274
|
&& ordersPublicationText(foldIntent(span.raw).replace(/^[^,]*,\s*/, ''))));
|
|
275
|
+
spans.forEach((span, index) => {
|
|
276
|
+
const folded = foldIntent(span.raw);
|
|
277
|
+
const verb = folded.match(CONDITIONAL_RUNTIME_VERB);
|
|
278
|
+
const cond = span.condition ? folded.indexOf(span.condition) : -1;
|
|
279
|
+
if (!verb || cond < 0 || span.context !== 'instruction' || span.polarity !== 'affirmative' || nativeReleasePolicy
|
|
280
|
+
|| CONDITIONAL_RUNTIME_EXCLUDED.test(folded)) return;
|
|
281
|
+
const governed = verb.index >= cond || /^(?:only\s+(?:if|when)|unless)\b/.test(span.condition);
|
|
282
|
+
if (!NEED_OR_FAILURE_CONDITION.test(span.condition)) return;
|
|
283
|
+
const leadsVerification = VERIFICATION_LEAD.test(folded.slice(0, cond)) && cond > 0
|
|
284
|
+
|| spans.slice(0, index).some(prior => prior.context === 'instruction' && prior.polarity === 'affirmative'
|
|
285
|
+
&& !prior.condition && VERIFICATION_LEAD.test(foldIntent(prior.raw)));
|
|
286
|
+
if (governed && leadsVerification) deferredSpans.add(span);
|
|
287
|
+
});
|
|
275
288
|
// An explicit alternative links both consequences. Keep the unconditional
|
|
276
289
|
// review prefix, but do not require a repair before its review has found one.
|
|
277
290
|
const alternatives = spans.filter(span => span.condition?.startsWith('otherwise:'));
|
|
@@ -285,10 +298,11 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
|
|
|
285
298
|
}
|
|
286
299
|
for (const span of [...spans].reverse()) {
|
|
287
300
|
const approvalPending = span.condition && /\b(?:approv\w*|permission|authori[sz]\w*)\b/.test(span.condition);
|
|
288
|
-
|
|
301
|
+
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));
|
|
302
|
+
if (span.context === 'quotation' || span.context === 'description' || approvalPending || deferredSpans.has(span) || evidenceStatement) {
|
|
289
303
|
// Retain the prefix before a comma-introduced postfix repair condition.
|
|
290
304
|
// Leading conditions and otherwise consequences are masked in full.
|
|
291
|
-
const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|otherwise)\b/.test(foldIntent(span.raw))
|
|
305
|
+
const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|only after|only once|otherwise)\b/.test(foldIntent(span.raw))
|
|
292
306
|
? span.raw.match(/^[^,]*,/)?.[0] || '' : '';
|
|
293
307
|
const masked = prefix + span.raw.slice(prefix.length).replace(/[^\r\n]/g, ' ');
|
|
294
308
|
semanticInput = semanticInput.slice(0, span.start) + masked + semanticInput.slice(span.end);
|
|
@@ -329,6 +343,12 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
|
|
|
329
343
|
}
|
|
330
344
|
return { engineVersion: SEMANTIC_ENGINE_VERSION, identity: { taskInstanceId, sessionId }, original, spans, actions, semantic };
|
|
331
345
|
}
|
|
346
|
+
const NEED_OR_FAILURE_CONDITION = /\b(?:needed|necessary|required|requires?|broken|fails?|failed|failing|failure|down|unhealthy|stale|missing|wrong|errors?|crash\w*|unavailable|not\s+(?:working|healthy|running|live|ok)|neu\s+(?:can|loi|hong|that bai|thieu|sai|chet)|khi\s+can|loi)\b|^unless\s+(?:healthy|ok|working|running|live)\b/;
|
|
347
|
+
const CONDITIONAL_RUNTIME_VERB = /\b(?:redeploy|deploy|restart|khoi dong lai|trien khai)\b/;
|
|
348
|
+
const CONDITIONAL_RUNTIME_EXCLUDED = /\b(?:publish|phat hanh|commit|push|tag|git|implement|fix|edit|modify|sua)\b/;
|
|
349
|
+
const VERIFICATION_LEAD = /^[-*+\u2022>\d.)\s]*(?:(?:please|hay|vui long|now|also|first)\s+)*(?:verify|check|confirm|validate|inspect|kiem tra|xac nhan)\b/;
|
|
350
|
+
const PAST_RELEASE_SOURCE = 'release(?:\\s+\\S+)?\\s+(?:(?:(?:was|were|is|are|has been|have been|had been|just been)(?:\\s+already)?|already)\\s+(?:published|shipped|released|on npm|live|deployed|out)|da\\s+(?:publish|phat hanh|release|deploy))\\b';
|
|
351
|
+
const PAST_RELEASE_ITEM = new RegExp(`^(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}`);
|
|
332
352
|
const PUBLISH_ORDER_NEGATOR = /\b(?:do not|don't|dont|never|without|not yet|no|not|avoid|skip|exclud\w*|forbid\w*|prohibit\w*|khong|chua)\b|--dry-run/;
|
|
333
353
|
const PUBLISH_ORDER_IMPERATIVE = /^(?:please\s+|just\s+|now\s+|also\s+)*(?:run|do|execute|perform|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/;
|
|
334
354
|
const PUBLISH_ORDER_HEADER = /prohibit|forbidden|out of scope|non-goal|scope control/;
|
|
@@ -412,9 +432,13 @@ function publicationScope(promptText = '') {
|
|
|
412
432
|
const bullet = /^\s*(?:[-*•]|\d+[.)])\s+/.test(line);
|
|
413
433
|
if (!bullet) prohibitionBlock = PUBLISH_ORDER_NEGATOR.test(line) && /:\s*$/.test(line);
|
|
414
434
|
for (const clause of line.split(/;|\.\s+|\bthen\b|\bbut\b|\binstead\b/)) {
|
|
435
|
+
// A temporary restriction pending prerequisites is not a task-wide prohibition.
|
|
436
|
+
// This classification does not authorize execution or establish those prerequisites.
|
|
415
437
|
let negated = bullet && prohibitionBlock;
|
|
416
438
|
for (const raw of clause.split(/,|\band\b|\bor\b|\bnor\b/)) {
|
|
417
439
|
const item = raw.replace(/^[\s*•-]+/, '').trim();
|
|
440
|
+
if (/\b(?:do not|don't|must not|not yet)\b[^,]*\b(?:publish|publication|release)\b[^,]*\b(?:while|until|before)\b/.test(item)
|
|
441
|
+
|| /\b(?:publish|publication|release)\b[^,]*\b(?:must not|not yet)\b[^,]*\b(?:until|before|while)\b/.test(item)) continue;
|
|
418
442
|
if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
|
|
419
443
|
else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
|
|
420
444
|
if (negated && /\b(?:release|publish|publication)\b/.test(item)) prohibited = true;
|
|
@@ -447,7 +471,7 @@ function ordersPublicationText(promptText = '') {
|
|
|
447
471
|
else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
|
|
448
472
|
const commandItem = item.replace(/^(?:please|just|now|also|then)\s+/, '');
|
|
449
473
|
const publication = /\bnpm\s+publish\b/.test(commandItem) && /^(?:npm\s+publish|run|do|execute|perform|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/.test(commandItem);
|
|
450
|
-
const releaseOrder = /^(?:please\s+|just\s+|now\s+|also\s+)*(?:release|ship|publish)\s+(?!instructions?\b|obligations?\b|policies\b|boundary\b|safety\b|progress\b|candidate\s+review\b|readiness\b|verifier\b|verification\b|evidence\b|policy\b|intent\b|notes\b|terminology\b)\S/.test(item);
|
|
474
|
+
const releaseOrder = !PAST_RELEASE_ITEM.test(item) && /^(?:please\s+|just\s+|now\s+|also\s+)*(?:release|ship|publish)\s+(?!instructions?\b|obligations?\b|policies\b|boundary\b|safety\b|progress\b|candidate\s+review\b|readiness\b|verifier\b|verification\b|evidence\b|policy\b|intent\b|notes\b|terminology\b)\S/.test(item);
|
|
451
475
|
const politeItem = item.replace(/^(?:(?:please|just|now|also|then|vui long|hay)\s+)+/, '');
|
|
452
476
|
const viPublish = /^(?:(?:su dung|phat hanh bang)\s+`?npm\s+publish\b|(?:dua|phat hanh|xuat ban|deploy|day)\b(?:[^.;\n]|\.(?=\d)){0,60}\b(?:len|to|vao)\s+npm\b)/.test(politeItem);
|
|
453
477
|
if (!negated && (releaseOrder || viPublish || (publication && (
|
|
@@ -461,7 +485,7 @@ function ordersPublicationText(promptText = '') {
|
|
|
461
485
|
return ordered;
|
|
462
486
|
}
|
|
463
487
|
|
|
464
|
-
const NOT_A_SERVICE = new Set(['it', 'this', 'that', 'them', 'the', 'all', 'everything', 'service', 'services', 'again', 'now', 'to', 'and', 'then']);
|
|
488
|
+
const NOT_A_SERVICE = new Set(['only', 'if', 'unless', 'needed', 'necessary', 'unneeded', 'neu', 'khi', 'can', 'thiet', 'lai', 'len', 'vao', 'tren', 'di', 'nhe', 'nua', 'it', 'this', 'that', 'them', 'the', 'all', 'everything', 'service', 'services', 'again', 'now', 'to', 'and', 'then']);
|
|
465
489
|
function nativeOperationGoal(domain, actionable, text) {
|
|
466
490
|
const goal = { domain, target: null, desiredState: 'verified', completionSemantics: 'execute-and-verify', requiredTargets: [] };
|
|
467
491
|
const clauses = actionable.join(' . ');
|
|
@@ -513,6 +537,7 @@ function neutralizeNonOrders(text) {
|
|
|
513
537
|
return source.replace(noVerbList(), ' ')
|
|
514
538
|
.replace(/\brelease-(?:publication|verification)\b|\brelease\s+(?:instructions?|authorization|obligations?|policies|readiness)\b/g, 'publication topic')
|
|
515
539
|
.replace(/\brelease\s+(?:safety|verification\s+plan)\b/g, 'publication topic')
|
|
540
|
+
.replace(new RegExp(`(^|[\\n.;]\\s*)(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}[^.;\\n]*`, 'g'), '$1publication topic')
|
|
516
541
|
.replace(/^[ \t]*[-*+•][ \t]*owner\s+yeu\s+cau\b[^\n]*/gm, ' ')
|
|
517
542
|
.replace(/^([ \t]*[-*+•][ \t]*)release\s+progress\s+reporter(?=[ \t]*(?:,|$))/gm, '$1progress reporter')
|
|
518
543
|
.replace(/^[ \t]*(?:[-*+\u2022]|\d+[.)])[ \t]*(?:negative|positive)\s+controls?\b[^\n]*(?:\n(?![ \t]*(?:[-*+\u2022]|\d+[.)])|[ \t]*\n)[^\n]*)*/gm, ' ')
|
|
@@ -523,6 +548,8 @@ function neutralizeNonOrders(text) {
|
|
|
523
548
|
.replace(/\b(?:uu tien|prefer(?:red)?)\s+(?:a\s+|an\s+)?(?:configuration|config|cau hinh)\s+(?:change|changes|update|thay doi)\b/g, ' ')
|
|
524
549
|
.replace(/\b(?:neu\s+(?:chi\s+)?(?:phai|can|thieu|khong du|bang chung chua du)(?![^.;\n]*\b(?:restart|deploy|xoa|delete|remove|cancel)\b)|if\s+(?:needed|necessary|required|evidence is insufficient))\b[^.;\n]*/g, ' ')
|
|
525
550
|
.replace(/[^.;\n]*\b(?:nao|gi|sao|the nao|bao nhieu)\b[^.;\n]*\?/g, ' ')
|
|
551
|
+
.replace(/\b(?:truoc khi|before)\s+(?:quay lai|tro lai|returning|going back|you (?:go|return)|we (?:go|return))\b[^.;\n]*/g, ' ')
|
|
552
|
+
.replace(/\b(?:cua|do|tu)\s+chinh\b|\bchinh\s+(?:cac|nhung|phien|no|minh|toi|ban than)\b/g, ' ')
|
|
526
553
|
.replace(/\bchinh\s+(?:xac|sach)\b|\b(?:phuong an|cach|de xuat|ban)\s+(?:sua|fix)\b|\b(?:diem|cho|muc|phan)\s+(?:phai|can|nen)\s+(?:sua|fix)\b/g, ' ')
|
|
527
554
|
.replace(/\bwrite\s*\/\s*verification\b|\bverification\s*\/\s*write\b|\bwrite\s+(?:or|and)\s+verification\b/g, ' ')
|
|
528
555
|
.replace(/\bwrite\s+permission\b/g, 'permission')
|
|
@@ -570,6 +597,13 @@ function declaredReadOnly(promptText, releasePolicy) {
|
|
|
570
597
|
|
|
571
598
|
const VERIFY_LEAD = /^(?:[-*+•>\d.)\s]*)(?:(?:please|hay|vui long|now|also|first|then)\s+)*(?:(?:keep|continue|tiep tuc)\s+)?(?:verify|re-?run|confirm|xac nhan|validate|double-?check|wait(?:ing)?|monitor|watch|cho(?=\s+(?:dung\s+)?(?:job|verifier|build|test|suite|gate|ci|run|task|ket qua|xong|output)\b))\b/;
|
|
572
599
|
const CHANGE_LEAD = /^(?:[-*+•>\d.)\s]*)(?:(?:please|hay|vui long|now|also|first|then)\s+)*(?:make|rebuild|redo|rewrite|restore|revert|correct|clean|patch|resolve|ensure|run(?!(?=[^.]*\b(?:tests?|suite|gate|checks?|lint|typecheck|pilot|smoke|e2e|verif\w*|vitest|jest|audit)\b)))\b/;
|
|
600
|
+
const BANS_TEST_RUNS = /\b(?:do not|don't|never|khong|dung)\s+(?:run|execute|chay)\s+(?:(?:any|more|additional|extra|them)\s+)*(?:tests?|checks?|verifications?)\b(?:\s+on\s+\w+)?/g;
|
|
601
|
+
const OWN_TARGET = /\b(?:yarn|npm|npx|pnpm|vitest|jest|pytest|node)\s+\S|\b(?:staging|ci|job|build|release(?!\s+notes?)|published|integration|e2e)\b/;
|
|
602
|
+
const bansTestRuns = (promptText) => {
|
|
603
|
+
const plain = String(promptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
|
|
604
|
+
const bans = plain.match(BANS_TEST_RUNS);
|
|
605
|
+
return !!bans && !bans.some((ban) => /\bon\s+\w+$/.test(ban)) && !OWN_TARGET.test(plain.replace(BANS_TEST_RUNS, ' '));
|
|
606
|
+
};
|
|
573
607
|
function isVerificationOnlyRequest(promptText) {
|
|
574
608
|
const plain = String(promptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase()
|
|
575
609
|
.replace(/```[\s\S]*?```/g, ' ').replace(/^[ \t]*>.*$/gm, ' ');
|
|
@@ -593,6 +627,27 @@ function neutralizeBannedLists(text) {
|
|
|
593
627
|
});
|
|
594
628
|
}
|
|
595
629
|
|
|
630
|
+
const OWNER_CONTROL_HOOK_TEXT = /^\s*(?:UKit completion gate:|UKit handoff|\[ukit[-\w]*\]|<system-reminder|<task-notification)/i;
|
|
631
|
+
const OWNER_STOP_EN = /^(?:please\s+)?(?:stop|halt|pause|cancel|abort)(?:\s+(?:all|everything|execution|executing|work|working|now|immediately|here|this|the|current|session|run|task|tasks|handoff|processing))*$/;
|
|
632
|
+
const OWNER_STOP_VI = /^(?:(?:tam\s+)?(?:dừng|ngừng)|(?:tạm\s+)?(?:dừng|ngừng)|hủy|huỷ|tam\s+dung|tam\s+ngung|ngung|dung\s+(?:lai|thuc\s+thi|ngay)|huy)(?:\s+(?:thực\s+thi|thuc\s+thi|phiên\s+này|phien\s+nay|phiên|phien|lại|lai|ngay|ngay\s+lập\s+tức|tất\s+cả|tat\s+ca|mọi\s+thứ|moi\s+thu|việc|viec|công\s+việc|cong\s+viec|run|handoff|session|task))*$/;
|
|
633
|
+
const OWNER_CONTROL_TASK_WORD = /\b(?:fix|implement|add|update|edit|write|create|deploy|redeploy|publish|commit|refactor|rewrite|install|sua|sửa|them|thêm|chay|chạy|cap nhat|cập nhật)\b|[\w-]+\/[\w.-]+/;
|
|
634
|
+
const OWNER_CONTROL_TASK_LEAD = /^(?:(?:and\s+)?then|also|afterwards?|after that|next|now|sau do|sau đó|roi|rồi|va|và)\b|^(?:please\s+)?(?:fix|implement|add|update|edit|write|create|run|deploy|redeploy|publish|commit|push|refactor|rewrite|install|build|sua|sửa|them|thêm|chay|chạy|trien khai|triển khai|cap nhat|cập nhật)\b/;
|
|
635
|
+
function classifyOwnerControl(promptText = '') {
|
|
636
|
+
const raw = String(promptText ?? '').normalize('NFC').trim();
|
|
637
|
+
if (!raw || OWNER_CONTROL_HOOK_TEXT.test(raw)) return { kind: null };
|
|
638
|
+
const stripped = raw.replace(/^[\s*#_-]+/, '');
|
|
639
|
+
if (/^[>"'`\u201c\u2018]/.test(stripped)) return { kind: null };
|
|
640
|
+
const sentences = stripped.split(/[.!?\n]/);
|
|
641
|
+
const [lead, ...rest] = sentences[0].split(/[:;]/);
|
|
642
|
+
const first = lead.trim().toLowerCase().replace(/\s+/g, ' ');
|
|
643
|
+
if (!first || first.length > 80) return { kind: null };
|
|
644
|
+
if (OWNER_CONTROL_TASK_WORD.test(rest.join(' ').toLowerCase())) return { kind: null };
|
|
645
|
+
if (!OWNER_STOP_EN.test(first) && !OWNER_STOP_VI.test(first)) return { kind: null };
|
|
646
|
+
const next = (sentences.slice(1).find((part) => part.trim()) || '').trim().toLowerCase();
|
|
647
|
+
if (OWNER_CONTROL_TASK_LEAD.test(next)) return { kind: null };
|
|
648
|
+
return { kind: 'stop' };
|
|
649
|
+
}
|
|
650
|
+
|
|
596
651
|
function classifyTaskSemantics(input = {}) {
|
|
597
652
|
return analyzeTaskIntent(input).semantic;
|
|
598
653
|
}
|
|
@@ -607,7 +662,7 @@ const collapseInspectionSentences = (text) => text.replace(INSPECTION_SENTENCE,
|
|
|
607
662
|
|
|
608
663
|
function actionableClauses(promptText) {
|
|
609
664
|
const text = neutralizeBannedLists(neutralizeNonOrders(collapseInspectionSentences(String(promptText).normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[đĐ]/g, 'd').toLowerCase())));
|
|
610
|
-
const clauses = text.split(/\s*(?:[;\n,]|\.(?:\s+|$)|\band\b|\bthen\b|\bva\b)\s*/);
|
|
665
|
+
const clauses = text.split(/\s*(?:[;\n,]|\.(?:\s+|$)|\band\b|\bthen\b|\bva\b|\broi\b(?=\s+(?:redeploy|deploy|restart|khoi dong lai|trien khai)\b))\s*/);
|
|
611
666
|
const actionable = clauses.map((clause) => clause.split(/\bwithout\b/)[0]).filter((clause) => !/\b(?:do not|don't|never|khong)\b|^[\s*+•>\d.)-]*(?:(?:vui long|xin|hay|please)\s+)*dung\b/.test(clause)
|
|
612
667
|
&& !/^[\s*+•>\d.)-]*(?:(?:please|just|hay|vui long|now|also)\s+)*(?:audit|inspect|review|analyze|analyse|explain|read|kiem tra|phan tich)\b/.test(clause)
|
|
613
668
|
// A fragment led by a subordinator continues the previous clause's predicate ("…, including source
|
|
@@ -622,7 +677,66 @@ function ordersAdditiveChange(promptText = '') {
|
|
|
622
677
|
return actionableClauses(publicationScope(promptText).text).actionable.some((clause) => ADDITIVE_ORDER_LEAD.test(clause));
|
|
623
678
|
}
|
|
624
679
|
|
|
625
|
-
|
|
680
|
+
const STATE_OBJECT = /\b(?:shells?|jobs?|process(?:es)?|pids?|agents?|subagents?|wakeups?|tien trinh|tac vu nen|background (?:tasks?|work)|crons?)\b/;
|
|
681
|
+
const STATE_LEAD = /\b(?:check|inspect|list|stop|cancel|kill|terminate|revoke|reclaim|kiem tra|liet ke|xac dinh|huy|thu hoi|ket thuc)\b/;
|
|
682
|
+
const STATE_ACTION = /\b(?:stop|cancel|kill|terminate|revoke|reclaim|dung|huy|thu hoi|ket thuc)\b/;
|
|
683
|
+
function statePlain(promptText) {
|
|
684
|
+
return String(promptText).normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[\u0111\u0110]/g, 'd').toLowerCase()
|
|
685
|
+
.replace(/```[\s\S]*?```/g, ' ').replace(/^[ \t]*>.*$/gm, ' ');
|
|
686
|
+
}
|
|
687
|
+
function isStateOperationRequest(promptText = '') {
|
|
688
|
+
const plain = statePlain(promptText);
|
|
689
|
+
if (!/\b(?:running|still|live|background|wakeups?|pids?|hung|stuck|orphan\w*|leftover|reclaim|chay|nen|treo|con sot|\d+\s+(?:shells?|jobs?|agents?|subagents?|process(?:es)?)|(?:job|task|shell|agent)\s+(?:id\s+)?[a-z0-9]*\d[a-z0-9]{5,})\b/.test(plain)) return false;
|
|
690
|
+
return plain.split(/[;!?\n]+|[.:](?=\s|$)/).some((clause) => {
|
|
691
|
+
const lead = clause.match(STATE_LEAD);
|
|
692
|
+
if (!lead) return false;
|
|
693
|
+
const after = clause.slice(lead.index + lead[0].length);
|
|
694
|
+
const near = after.match(/^(?:\s+[\p{L}\p{N}_-]+){0,5}?\s+/u);
|
|
695
|
+
const window = after.split(/\s+/).slice(0, 7).join(' ');
|
|
696
|
+
return near !== null && STATE_OBJECT.test(window);
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function stateOperationShape(promptText = '') {
|
|
701
|
+
const plain = statePlain(promptText);
|
|
702
|
+
const unquoted = plain.replace(/`[^`\n]*`|"[^"\n]*"|\u201c[^\u201d\n]*\u201d/g, ' ');
|
|
703
|
+
const targets = [...new Set((unquoted.match(/(?<![\w-])[a-z]*\d[a-z0-9]{7,}\b/g) || []).filter((id) => /[a-z]/.test(id)))].slice(0, 8);
|
|
704
|
+
let conditional = false;
|
|
705
|
+
let gated = false;
|
|
706
|
+
const action = plain.split(/[;!?\n]+|[.:](?=\s|$)|,\s*/).some((raw) => {
|
|
707
|
+
const clause = raw.replace(/^[\s*\-\d.)]+/, '').trim();
|
|
708
|
+
if (!clause) return false;
|
|
709
|
+
const conditionLead = /^(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause);
|
|
710
|
+
if (!conditionLead && /\b(?:khong|do not|don't|never|not)\b/.test(clause)) return false;
|
|
711
|
+
if (/\b(?:cho phep|allow(?:ed|s)?|permit(?:ted)?|authori[sz]ed?|you may|may stop|duoc phep)\b/.test(clause)) { gated = false; return false; }
|
|
712
|
+
const head = clause.split(/\s+/).slice(0, 3).join(' ');
|
|
713
|
+
if (/\b(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause)) {
|
|
714
|
+
const leadsWithCondition = /^(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause);
|
|
715
|
+
const preCondition = leadsWithCondition ? '' : clause.split(/\b(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/)[0].trim();
|
|
716
|
+
if (preCondition && /\b(?:and|va|then|roi)\s+(?:stop|cancel|kill|terminate|revoke|reclaim|dung|huy|thu hoi|ket thuc)\b/.test(preCondition)) { conditional = true; return false; }
|
|
717
|
+
const consequent = leadsWithCondition ? (/\s(?:then|thi)\s/.test(clause) ? clause.split(/\s(?:then|thi)\s/).pop() : '') : clause;
|
|
718
|
+
if (STATE_ACTION.test(consequent.split(/\s+/).slice(0, 3).join(' '))) { conditional = true; return false; }
|
|
719
|
+
gated = leadsWithCondition && !STATE_ACTION.test(consequent);
|
|
720
|
+
return false;
|
|
721
|
+
}
|
|
722
|
+
const wasGated = gated;
|
|
723
|
+
gated = false;
|
|
724
|
+
const stops = (wasGated ? STATE_ACTION.test(clause) : STATE_ACTION.test(head)) && (wasGated || STATE_OBJECT.test(clause));
|
|
725
|
+
if (stops && wasGated) { conditional = true; return false; }
|
|
726
|
+
return stops;
|
|
727
|
+
});
|
|
728
|
+
return { action, conditional: conditional && !action, targets };
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function classifySemanticText(input = {}) {
|
|
732
|
+
const semantic = classifySemanticCore(input);
|
|
733
|
+
if (semantic.taskKind !== 'READ_ONLY' || semantic.conditionalObligations || semantic.publication || !isStateOperationRequest(input.promptText)) return semantic;
|
|
734
|
+
const { verificationOnly: _verification, statusReport: _status, ...rest } = semantic;
|
|
735
|
+
const shape = stateOperationShape(input.promptText);
|
|
736
|
+
return { ...rest, stateVerification: true, ...(shape.action ? { stateAction: true } : shape.conditional ? { stateConditionalStop: true } : {}), ...(shape.targets.length ? { stateTargets: shape.targets } : {}) };
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
|
|
626
740
|
promptText = publicationScope(promptText).text;
|
|
627
741
|
const releaseText = String(promptText).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
|
|
628
742
|
const preflight = releaseText.match(/\b(?:yarn\s+release:verify|npm\s+run\s+release:verify)\b/)?.[0];
|
|
@@ -633,13 +747,13 @@ function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
|
|
|
633
747
|
if (ordersPublicationText(promptText)) {
|
|
634
748
|
const implementation = hasExplicitOrder(clauses.filter((clause) => !/\b(?:release|publish)\b/.test(clause)));
|
|
635
749
|
const remaining = clauses.filter((clause) => !ordersPublicationText(clause) && !/\b(?:release|publish)\b/.test(clause)).join('; ');
|
|
636
|
-
const base = remaining.trim() ?
|
|
750
|
+
const base = remaining.trim() ? classifySemanticCore({ promptText: remaining, targetFile }) : {};
|
|
637
751
|
delete base.verificationOnly;
|
|
638
752
|
delete base.statusReport;
|
|
639
753
|
return { ...base, taskKind: implementation ? 'MIXED' : 'OPERATIONAL', publication: true, ...(releasePolicy ? { releasePolicy } : {}) };
|
|
640
754
|
}
|
|
641
755
|
if (!/[a-z0-9]/.test(text)) return { taskKind: 'READ_ONLY' };
|
|
642
|
-
if (declaredReadOnly(promptText, releasePolicy)) return { taskKind: 'READ_ONLY', ...(isVerificationOnlyRequest(promptText) ? { verificationOnly: true } : {}) };
|
|
756
|
+
if (declaredReadOnly(promptText, releasePolicy)) return { taskKind: 'READ_ONLY', ...(isVerificationOnlyRequest(promptText) && !bansTestRuns(promptText) ? { verificationOnly: true } : {}) };
|
|
643
757
|
const sourceOrder = actionable.some((clause) => /\b(?:implement|fix(?:es)?|apply|refactor|modify|edit|write|update|sua|viet|chinh)\b/.test(clause)
|
|
644
758
|
&& /\b(?:source|code|logic|scheduler|implementation|ma nguon)\b|\.[cm]?[jt]sx?\b/.test(clause));
|
|
645
759
|
const codeChangeVerb = actionable.some((clause) => !/^(?:run\s+|execute\s+)?git\s+/.test(clause) && /\b(?:implement|fix(?:es)?|apply|refactor|modify|edit|write|update|sua|viet|chinh)\b/.test(clause));
|
|
@@ -678,7 +792,7 @@ function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
|
|
|
678
792
|
&& !/\.[cm]?[jt]sx?\b/.test(clause) && !/\bgit\b/.test(clause));
|
|
679
793
|
const nativeDomain = cronOperation ? 'scheduled-job' : gitOperation !== runtimeOperation ? (gitOperation ? 'git-integrity' : 'service-runtime') : null;
|
|
680
794
|
const operation = Boolean(nativeDomain);
|
|
681
|
-
if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', verificationOnly: true };
|
|
795
|
+
if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', ...(bansTestRuns(promptText) ? {} : { verificationOnly: true }) };
|
|
682
796
|
const CONFIG_CHANGE_REPORT_CLAUSE = /\b(?:da|has|have|had|already)\s+(?:doi|thay doi|changed?|updated?)\b|\b(?:nao|gi|which|what|report|bao cao)\b[^.;]*?\b(?:doi|thay doi|changed?|updated?)\b/;
|
|
683
797
|
const CONFIG_MUTATION_VERB = /\b(?:set|change|toggle|enable|disable|switch|turn|configure|modify|update|edit|doi(?!\s+chieu\b)|bat(?!\s+dau\b)|tat(?!\s+ca\b)|chinh)\b/;
|
|
684
798
|
const CONFIG_NOUN = /\b(?:configuration|config|toggle|cau hinh)\b/;
|
|
@@ -731,6 +845,7 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
731
845
|
return { ...(contract || {}), ...semantic,
|
|
732
846
|
completionEvidence: semantic.taskKind === 'DOCUMENTATION_OUTPUT' ? ['report-artifact'] : operationOnly ? ['operation-verification']
|
|
733
847
|
: semantic.taskKind === 'MIXED' ? [...new Set([...evidence, 'write-evidence', 'operation-verification'])]
|
|
848
|
+
: semantic.taskKind === 'READ_ONLY' && semantic.stateVerification ? ['state-verification']
|
|
734
849
|
: semantic.taskKind === 'READ_ONLY' && semantic.statusReport ? []
|
|
735
850
|
: semantic.taskKind === 'READ_ONLY' ? (semantic.verificationOnly ? ['verification-evidence'] : ['impact-evidence'])
|
|
736
851
|
// A routed contract owns the debt; an unrouted (informational/null) turn carries none, because
|
|
@@ -954,6 +1069,9 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
954
1069
|
return tierLaneModule;
|
|
955
1070
|
}
|
|
956
1071
|
function writeTierLaneLines(summary, taskId) {
|
|
1072
|
+
if (summary?.playbookId === 'bug-fix') {
|
|
1073
|
+
process.stdout.write('[ukit-skill-router] Bug-fix evidence (include in any worker prompt): before editing, run the failing repro once and keep its failing result; after the fix re-run that same command and keep the passing result; state the root cause with UKIT_EVIDENCE="class=root-cause;claim=<mechanism>" on a Bash call. A worker\'s own runs count for this task only through its host-linked session.\n');
|
|
1074
|
+
}
|
|
957
1075
|
const lane = summary?.tierLane;
|
|
958
1076
|
if (!lane?.instruction) {
|
|
959
1077
|
return;
|
|
@@ -4089,6 +4207,7 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4089
4207
|
const compactState = { ...sharedState };
|
|
4090
4208
|
delete compactState.source;
|
|
4091
4209
|
delete compactState.ts;
|
|
4210
|
+
delete compactState.ownerControl; // STOP is per-session state, never a cached route fact
|
|
4092
4211
|
return compactState;
|
|
4093
4212
|
}
|
|
4094
4213
|
|
|
@@ -4112,16 +4231,64 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4112
4231
|
? null
|
|
4113
4232
|
: String(sessionCandidate).trim() || null;
|
|
4114
4233
|
|
|
4115
|
-
//
|
|
4116
|
-
//
|
|
4117
|
-
|
|
4118
|
-
async function
|
|
4234
|
+
// Compare the observed session route under the lock before ordinary writes.
|
|
4235
|
+
// Handoff writes use their separate authority-locked commit protocol.
|
|
4236
|
+
const sessionRoutePath = sessionId && path.join(projectRoot, '.ukit/storage/cache/route-state', `${sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`);
|
|
4237
|
+
async function readRouteVersion() {
|
|
4238
|
+
try {
|
|
4239
|
+
const bytes = await fsp.readFile(sessionRoutePath, 'utf8');
|
|
4240
|
+
const route = JSON.parse(bytes);
|
|
4241
|
+
if (!route || route.sessionId !== sessionId || !route.taskInstanceId) throw new Error('invalid session route');
|
|
4242
|
+
return bytes;
|
|
4243
|
+
} catch (error) {
|
|
4244
|
+
if (error.code === 'ENOENT') return null;
|
|
4245
|
+
throw new Error('existing session route unavailable');
|
|
4246
|
+
}
|
|
4247
|
+
}
|
|
4248
|
+
let expectedRouteVersion;
|
|
4249
|
+
async function persistRouteState(text, recoveryOwner = null) {
|
|
4250
|
+
if (sessionId) {
|
|
4251
|
+
// The lock primitive ships beside this hook; resolve it from the hook's own install dir so a
|
|
4252
|
+
// workspace whose runtime copy is absent/partial still takes the same lock (never unlocked).
|
|
4253
|
+
const lockModule = path.join(process.env.HOOK_DIR || path.join(projectRoot, '.claude', 'hooks'), '..', 'ukit', 'runtime', 'async-lock.mjs');
|
|
4254
|
+
const { withAsyncLock } = await import(pathToFileURL(lockModule).href);
|
|
4255
|
+
const sidecar = path.join(projectRoot, '.ukit/storage/cache/route-state', `${sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`);
|
|
4256
|
+
const result = await withAsyncLock(sidecar, {}, async () => {
|
|
4257
|
+
if (recoveryOwner) {
|
|
4258
|
+
let route;
|
|
4259
|
+
let missing = false;
|
|
4260
|
+
try { route = JSON.parse(await fsp.readFile(sidecar, 'utf8')); }
|
|
4261
|
+
catch (error) { if (error.code !== 'ENOENT') throw new Error('existing session route unavailable'); missing = true; }
|
|
4262
|
+
if (!missing && (!route || !route.taskInstanceId || route.sessionId !== sessionId || route.taskInstanceId !== recoveryOwner.taskInstanceId || route.routeGeneration !== recoveryOwner.routeGeneration)) {
|
|
4263
|
+
throw new Error('recovery would overwrite another task route');
|
|
4264
|
+
}
|
|
4265
|
+
} else if (!handoffSkill && !handoffExpansion && await readRouteVersion() !== expectedRouteVersion) {
|
|
4266
|
+
throw new Error('session route changed before write');
|
|
4267
|
+
}
|
|
4268
|
+
const persisted = await persistRouteStateLocked(text);
|
|
4269
|
+
expectedRouteVersion = await readRouteVersion();
|
|
4270
|
+
return persisted;
|
|
4271
|
+
});
|
|
4272
|
+
if (!result.ok) throw new Error(`session route lock ${result.reason}`);
|
|
4273
|
+
return result.value;
|
|
4274
|
+
}
|
|
4275
|
+
return persistRouteStateLocked(text);
|
|
4276
|
+
}
|
|
4277
|
+
async function persistRouteStateLocked(text) {
|
|
4119
4278
|
const persisted = JSON.parse(text);
|
|
4120
4279
|
persisted.taskInstanceId = taskInstanceId;
|
|
4280
|
+
// The task identity is minted on a fresh owner prompt and retained only on
|
|
4281
|
+
// the router's continuation lineage. It is also the route generation.
|
|
4282
|
+
persisted.routeGeneration = taskInstanceId;
|
|
4121
4283
|
// Bounded audit metadata (short strings, additive): where this turn's task id and
|
|
4122
4284
|
// contract came from — 'system' marks a synthetic continuation that resumed the
|
|
4123
4285
|
// previous task instead of minting a fresh one. No consumer branches on these yet.
|
|
4124
4286
|
persisted.taskIdOrigin = continuingTask ? (systemOriginTurn ? 'system' : 'continue') : 'fresh';
|
|
4287
|
+
// A handoff binding follows only the same routed task; cached routes must
|
|
4288
|
+
// never carry a prior task's run identity into a fresh owner prompt.
|
|
4289
|
+
if (handoffRunId) persisted.handoffRunId = handoffRunId;
|
|
4290
|
+
else if (continuingTask && previous.handoffRunId) persisted.handoffRunId = previous.handoffRunId;
|
|
4291
|
+
else delete persisted.handoffRunId;
|
|
4125
4292
|
if (continuingTask && previous.routingContext?.lastExplicitUserPromptText) {
|
|
4126
4293
|
persisted.routingContext ||= {};
|
|
4127
4294
|
persisted.routingContext.lastExplicitUserPromptText = previous.routingContext.lastExplicitUserPromptText;
|
|
@@ -4133,6 +4300,9 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4133
4300
|
persisted.routingContext.mutationOrder = previous.routingContext.mutationOrder;
|
|
4134
4301
|
}
|
|
4135
4302
|
}
|
|
4303
|
+
// The STOP marker lives until the next genuine owner prompt re-routes (no TTL).
|
|
4304
|
+
if (ownerControlTurn) persisted.ownerControl = { kind: 'stop', sessionId, ts: Date.now() };
|
|
4305
|
+
else if (previous.ownerControl?.kind === 'stop' && (payload.tool_name || systemOriginTurn || !extractPrompt(payload).trim())) persisted.ownerControl = previous.ownerControl;
|
|
4136
4306
|
if (continuingTask && !persisted.suspendedContract && previous.suspendedContract) {
|
|
4137
4307
|
persisted.suspendedContract = previous.suspendedContract;
|
|
4138
4308
|
}
|
|
@@ -4142,7 +4312,7 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4142
4312
|
persisted.routeSummary ||= {};
|
|
4143
4313
|
persisted.routeSummary.executionContract = previous.routeSummary.executionContract;
|
|
4144
4314
|
persisted.contractOrigin = 'carried-system';
|
|
4145
|
-
for (const key of ['expectedSourceFiles', 'completionState', 'continuationState', 'executionMode']) {
|
|
4315
|
+
for (const key of ['expectedSourceFiles', 'expectedSourceProvenance', 'completionState', 'continuationState', 'executionMode']) {
|
|
4146
4316
|
if (previous.routeSummary[key] !== undefined) persisted.routeSummary[key] = previous.routeSummary[key];
|
|
4147
4317
|
else delete persisted.routeSummary[key];
|
|
4148
4318
|
}
|
|
@@ -4266,7 +4436,7 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4266
4436
|
persisted.requestKey = previous.requestKey;
|
|
4267
4437
|
persisted.routingContext = { ...previous.routingContext };
|
|
4268
4438
|
persisted.routeSummary ||= {};
|
|
4269
|
-
for (const key of ['executionContract', 'expectedSourceFiles', 'completionState', 'continuationState', 'executionMode']) {
|
|
4439
|
+
for (const key of ['executionContract', 'expectedSourceFiles', 'expectedSourceProvenance', 'completionState', 'continuationState', 'executionMode']) {
|
|
4270
4440
|
if (previous.routeSummary[key] !== undefined) persisted.routeSummary[key] = previous.routeSummary[key];
|
|
4271
4441
|
else delete persisted.routeSummary[key];
|
|
4272
4442
|
}
|
|
@@ -4290,30 +4460,67 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4290
4460
|
persisted.semanticProvenance = { engineVersion: analysis.engineVersion, actions: analysis.actions,
|
|
4291
4461
|
spans: analysis.spans.map(({ raw, ...span }) => span) };
|
|
4292
4462
|
}
|
|
4463
|
+
// Persistence revision prevents byte-identical ABA; it is not ownership authority.
|
|
4464
|
+
if (sessionId) persisted.routePersistenceRevision = crypto.randomUUID();
|
|
4293
4465
|
text = JSON.stringify(persisted);
|
|
4294
|
-
|
|
4295
|
-
|
|
4466
|
+
// Publication: pending marker -> shared write -> final sidecar (the commit point). We hold the sidecar
|
|
4467
|
+
// lock, so no other route writer can change either file in between: when the shared write fails and the
|
|
4468
|
+
// shared slot is provably unchanged, restore the previous committed sidecar instead of stranding a
|
|
4469
|
+
// pending marker that would make a still-valid previous route unreadable.
|
|
4470
|
+
const readOrNull = async (file) => { try { return await fsp.readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
|
|
4471
|
+
const priorSidecar = sessionId ? await readOrNull(sessionRoutePath) : null;
|
|
4472
|
+
const priorShared = sessionId ? await readOrNull(statePath) : null;
|
|
4473
|
+
if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true }));
|
|
4296
4474
|
try {
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
if (
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4475
|
+
await writeJsonFileAtomic(statePath, text);
|
|
4476
|
+
} catch (error) {
|
|
4477
|
+
if (sessionId) {
|
|
4478
|
+
let sharedNow;
|
|
4479
|
+
try { sharedNow = await readOrNull(statePath); } catch { sharedNow = undefined; }
|
|
4480
|
+
if (sharedNow !== undefined && sharedNow === priorShared) {
|
|
4481
|
+
try {
|
|
4482
|
+
if (priorSidecar === null) await fsp.rm(sessionRoutePath, { force: true });
|
|
4483
|
+
else await writeJsonFileAtomic(sessionRoutePath, priorSidecar);
|
|
4484
|
+
} catch { /* the pending marker stays: readers fail closed */ }
|
|
4305
4485
|
}
|
|
4306
4486
|
}
|
|
4307
|
-
|
|
4487
|
+
throw error;
|
|
4488
|
+
}
|
|
4489
|
+
// Read-back verification is only meaningful under the session sidecar lock; sessionless
|
|
4490
|
+
// routers share the slot unserialized, so a newer legitimate write is not a failed one.
|
|
4491
|
+
if (sessionId) {
|
|
4492
|
+
const readBack = await fsp.readFile(statePath, 'utf8');
|
|
4493
|
+
let foreign = false;
|
|
4494
|
+
if (readBack !== text) { try { foreign = String(JSON.parse(readBack)?.sessionId || '').trim() !== sessionId; } catch {} }
|
|
4495
|
+
// Another session may legitimately publish to the single shared slot right after our rename;
|
|
4496
|
+
// only a same-session mismatch (or unreadable bytes) means our own write did not land.
|
|
4497
|
+
if (readBack !== text && !foreign) throw new Error('shared route verification failed');
|
|
4498
|
+
}
|
|
4499
|
+
if (!sessionId) return persisted;
|
|
4500
|
+
const dir = path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state');
|
|
4501
|
+
const sidecar = path.join(dir, `${String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`);
|
|
4502
|
+
await writeJsonFileAtomic(sidecar, text);
|
|
4503
|
+
if (await fsp.readFile(sidecar, 'utf8') !== text) throw new Error('sidecar route verification failed');
|
|
4308
4504
|
return persisted;
|
|
4309
4505
|
}
|
|
4506
|
+
expectedRouteVersion = sessionId ? await readRouteVersion() : null;
|
|
4310
4507
|
const storedPrevious = await readJson(statePath, {});
|
|
4311
4508
|
// The shared slot may belong to another session; recover only our owned sidecar.
|
|
4312
|
-
const
|
|
4509
|
+
const sessionSidecarRead = sessionId
|
|
4313
4510
|
? await readJson(path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default'}.json`), {})
|
|
4314
4511
|
: {};
|
|
4512
|
+
const sidecarPrevious = sessionId && String(storedPrevious?.sessionId || '').trim() !== sessionId ? sessionSidecarRead : {};
|
|
4513
|
+
// Only a COMMITTED publication is a previous route: a pending marker, or a shared document whose
|
|
4514
|
+
// revision the sidecar never confirmed, is an interrupted write and must not seed task continuity.
|
|
4515
|
+
// Legacy state without a persistence revision keeps its old meaning.
|
|
4516
|
+
const publishedPrevious = (state) => {
|
|
4517
|
+
if (!sessionId || String(state?.sessionId || '').trim() !== sessionId) return true;
|
|
4518
|
+
if (state.routePublicationIncomplete || sessionSidecarRead.routePublicationIncomplete) return false;
|
|
4519
|
+
if (!state.routePersistenceRevision) return true;
|
|
4520
|
+
return sessionSidecarRead.routePersistenceRevision === state.routePersistenceRevision;
|
|
4521
|
+
};
|
|
4315
4522
|
let previous = sessionId
|
|
4316
|
-
? [storedPrevious, sidecarPrevious].find((state) => String(state?.sessionId || '').trim() === sessionId) || {}
|
|
4523
|
+
? [storedPrevious, sidecarPrevious].find((state) => String(state?.sessionId || '').trim() === sessionId && publishedPrevious(state)) || {}
|
|
4317
4524
|
: storedPrevious;
|
|
4318
4525
|
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
4526
|
extractPrompt(payload).normalize('NFD').replace(/[̀-ͯ]/g, '').trim());
|
|
@@ -4361,9 +4568,13 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4361
4568
|
} catch { boundGateContinuation = false; }
|
|
4362
4569
|
}
|
|
4363
4570
|
}
|
|
4571
|
+
const ownerControlTurn = Boolean(sessionId && promptOrigin !== 'system' && !boundGateContinuation && !payload.tool_name
|
|
4572
|
+
&& (classifyOwnerControl(extractPrompt(payload)).kind === 'stop'
|
|
4573
|
+
|| (payload.ukit_harness === 'omp' && payload.ukit_owner_input === 'contains-stop')));
|
|
4364
4574
|
const systemOriginTurn = (() => {
|
|
4365
4575
|
const promptTrim = extractPrompt(payload).trim();
|
|
4366
4576
|
if (!promptTrim) return false;
|
|
4577
|
+
if (ownerControlTurn && previous.taskInstanceId) return true;
|
|
4367
4578
|
if (/^This session is being continued from a previous conversation/i.test(promptTrim)) return true;
|
|
4368
4579
|
// Bridge-owned metadata only (ukit-bridge.js maps the host's session-stop-continuation
|
|
4369
4580
|
// attribution); an arbitrary prompt prefix proves nothing and is never trusted here.
|
|
@@ -4543,11 +4754,236 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4543
4754
|
if (previous.routeSummary?.continuationState?.required === false) return false;
|
|
4544
4755
|
return true;
|
|
4545
4756
|
})();
|
|
4546
|
-
const
|
|
4547
|
-
|
|
4757
|
+
const handoffSkill = payload.tool_name === 'Skill'
|
|
4758
|
+
&& /^(?:ukit:)?handoff-fullstack$/.test(String(payload.tool_input?.skill || ''));
|
|
4759
|
+
const handoffExpansion = payload.hook_event_name === 'UserPromptExpansion'
|
|
4760
|
+
&& payload.expansion_type === 'slash_command'
|
|
4761
|
+
&& /^(?:ukit:)?handoff-fullstack$/.test(String(payload.command_name || ''));
|
|
4762
|
+
const ownerResumeTurn = (() => {
|
|
4763
|
+
if (previous.ownerControl?.kind !== 'stop' || previous.ownerControl.sessionId !== sessionId || !sessionId || !previous.taskInstanceId
|
|
4764
|
+
|| payload.tool_name || promptOrigin === 'system' || ownerControlTurn) return false;
|
|
4765
|
+
const fold = (text) => String(text ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/\u0111/gi, 'd').toLowerCase();
|
|
4766
|
+
const body = fold(extractPrompt(payload)).trim();
|
|
4767
|
+
if (!/^(?:continue|resume|keep going|proceed|tiep tuc|lam tiep)\s*[:,\u2013\u2014-]\s*\S/.test(body)) return false;
|
|
4768
|
+
const targets = (text) => new Set(fold(text).match(/[\w.-]+\/[\w./-]+|[\w-]+\.[a-z][a-z0-9]{0,7}\b/g) || []);
|
|
4769
|
+
const wanted = targets(body);
|
|
4770
|
+
const owned = targets(previous.routingContext?.lastExplicitUserPromptText);
|
|
4771
|
+
return wanted.size > 0 && [...wanted].every((target) => owned.has(target));
|
|
4772
|
+
})();
|
|
4773
|
+
const continuingTask = Boolean(previous.taskInstanceId && (payload.tool_name || handoffExpansion || continuationPrompt || ownerResumeTurn || systemOriginTurn || guidanceTurn));
|
|
4774
|
+
let taskInstanceId = continuingTask
|
|
4548
4775
|
? previous.taskInstanceId
|
|
4549
4776
|
: `task-${crypto.randomBytes(16).toString("hex")}`;
|
|
4777
|
+
// OMP prompt text can contain an identical heading without a command
|
|
4778
|
+
// invocation, so it is not sufficient evidence for creating provenance.
|
|
4779
|
+
// The Skill registration exists solely for this invocation; other skills must
|
|
4780
|
+
// not reroute or overwrite the current task as if they were user prompts.
|
|
4781
|
+
if (payload.tool_name === 'Skill' && !handoffSkill) process.exit(0);
|
|
4782
|
+
let handoffRunId = continuingTask ? previous.handoffRunId : null;
|
|
4783
|
+
const HOOK_SHAPED_PROMPT = /^\s*(?:UKit completion gate:|UKit handoff|\[ukit-[\w-]+\]|\[ukit\]\s)/;
|
|
4784
|
+
if (previous.ownerControl?.kind === 'stop' && !payload.tool_name && (!extractPrompt(payload).trim() || HOOK_SHAPED_PROMPT.test(extractPrompt(payload)))) process.exit(0);
|
|
4785
|
+
if (previous.ownerControl?.kind === 'stop' && !payload.tool_name && payload.ukit_harness === 'omp'
|
|
4786
|
+
&& (payload.ukit_owner_input === 'before-stop' || payload.ukit_owner_input === 'unproven') && extractPrompt(payload).trim()) process.exit(0);
|
|
4787
|
+
if (!payload.tool_name && !systemOriginTurn) {
|
|
4788
|
+
const hookText = extractPrompt(payload);
|
|
4789
|
+
let inertHook = /^\s*\[ukit-[\w-]+\]/.test(hookText);
|
|
4790
|
+
if (!inertHook && /^UKit completion gate:/.test(hookText.trim())) {
|
|
4791
|
+
try {
|
|
4792
|
+
inertHook = (await import(pathToFileURL(path.join(projectRoot, '.claude', 'ukit', 'runtime', 'execution-ledger.mjs')).href)).isCompletionGateContinuationText(hookText);
|
|
4793
|
+
} catch { inertHook = true; }
|
|
4794
|
+
}
|
|
4795
|
+
if (inertHook) process.exit(0);
|
|
4796
|
+
}
|
|
4797
|
+
if (ownerControlTurn) {
|
|
4798
|
+
const priorPrompt = previous.routingContext?.lastExplicitUserPromptText || '';
|
|
4799
|
+
await ensureDir(statePath);
|
|
4800
|
+
await persistRouteState(JSON.stringify({
|
|
4801
|
+
...(sessionId ? { sessionId } : {}),
|
|
4802
|
+
ts: Date.now(),
|
|
4803
|
+
source: 'skill-router-owner-control',
|
|
4804
|
+
activeSkills: [],
|
|
4805
|
+
routingContext: compactRoutingContext({ promptText: '', lastExplicitUserPromptText: priorPrompt, commandText: '', targetFile: '', contextIntent: '', taskType: '', mutationOrder: typeof previous.routingContext?.mutationOrder === 'boolean' ? previous.routingContext.mutationOrder : null, planOnly: null }),
|
|
4806
|
+
...(previous.routeSummary ? { routeSummary: previous.routeSummary } : {}),
|
|
4807
|
+
...(previous.requestKey ? { requestKey: previous.requestKey } : {}),
|
|
4808
|
+
}));
|
|
4809
|
+
process.exit(0);
|
|
4810
|
+
}
|
|
4811
|
+
const denyHandoff = (reason) => {
|
|
4812
|
+
const message = `UKit handoff resume BLOCKED: ${reason}; cursor untouched.`;
|
|
4813
|
+
process.stdout.write(JSON.stringify(handoffExpansion
|
|
4814
|
+
? { decision: 'block', reason: message }
|
|
4815
|
+
: { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: message } }));
|
|
4816
|
+
process.exit(0);
|
|
4817
|
+
};
|
|
4818
|
+
async function denyCommittedHandoff(provenance, runId, error) {
|
|
4819
|
+
try {
|
|
4820
|
+
await provenance.withHandoffOwner({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration: taskInstanceId }, async () => {
|
|
4821
|
+
const ownership = await provenance.resolveHandoffApplicability({ projectRoot, sessionId, taskInstanceId, runId, routeGeneration: taskInstanceId });
|
|
4822
|
+
if (ownership.status !== 'OWNED') throw new Error('authority unavailable');
|
|
4823
|
+
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}`);
|
|
4824
|
+
});
|
|
4825
|
+
} catch {}
|
|
4826
|
+
denyHandoff(String(error.message).slice(0, 160));
|
|
4827
|
+
}
|
|
4828
|
+
if ((handoffSkill || handoffExpansion) && !sessionId) denyHandoff('missing session identity');
|
|
4829
|
+
if ((handoffSkill || handoffExpansion) && sessionId) {
|
|
4830
|
+
const provenance = await import(pathToFileURL(path.join(projectRoot, '.claude/ukit/runtime/handoff-provenance.mjs')).href);
|
|
4831
|
+
const args = String(handoffExpansion ? payload.command_args || '' : payload.tool_input?.args || '').trim();
|
|
4832
|
+
const resume = /^--resume-run=(handoff-[a-f0-9]{64})$/.exec(args);
|
|
4833
|
+
const recovery = /^--recover-run=(handoff-[a-f0-9]{64}) --generation=(0|[1-9][0-9]*)$/.exec(args);
|
|
4834
|
+
const adopt = /^--adopt-legacy-run=(handoff-[a-f0-9]{64})$/.exec(args);
|
|
4835
|
+
if (args.includes('--recover-run') || args.includes('--generation')) {
|
|
4836
|
+
if (!recovery || !Number.isSafeInteger(Number(recovery[2]))) denyHandoff('explicit recovery requires --recover-run=<RunId> --generation=<generation>');
|
|
4837
|
+
if (handoffSkill) {
|
|
4838
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4839
|
+
const owner = ownership.claim || ownership.binding;
|
|
4840
|
+
if (ownership.status !== 'OWNED' || ownership.generation !== Number(recovery[2])
|
|
4841
|
+
|| owner?.runId !== recovery[1] || owner?.taskInstanceId !== taskInstanceId) {
|
|
4842
|
+
denyHandoff('recovery requires a reconciled route for the committed owner');
|
|
4843
|
+
}
|
|
4844
|
+
process.exit(0);
|
|
4845
|
+
}
|
|
4846
|
+
try {
|
|
4847
|
+
await provenance.withHandoffRecovery({ projectRoot, sessionId, runId: recovery[1], generation: Number(recovery[2]) }, async owner => {
|
|
4848
|
+
const cursor = await fs.promises.readFile(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8');
|
|
4849
|
+
const ids = [...cursor.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
|
|
4850
|
+
if (ids.length !== 1 || ids[0][1] !== recovery[1]) throw new Error('target cursor identity mismatch');
|
|
4851
|
+
taskInstanceId = owner.taskInstanceId;
|
|
4852
|
+
if (owner.routeGeneration !== taskInstanceId) throw new Error('unsupported recovery route generation');
|
|
4853
|
+
handoffRunId = recovery[1];
|
|
4854
|
+
await persistRouteState(JSON.stringify({ sessionId, ts: Date.now(), source: 'skill-router-handoff-recovery' }), owner);
|
|
4855
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4856
|
+
if (ownership.status !== 'OWNED' || ownership.generation !== owner.generation) throw new Error('recovery route unavailable');
|
|
4857
|
+
});
|
|
4858
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptExpansion', additionalContext: `UKit handoff recovery RunId: ${handoffRunId}; generation ${recovery[2]}. Ownership is unchanged; pause remains unchanged.` } }));
|
|
4859
|
+
process.exit(0);
|
|
4860
|
+
} catch (error) { await denyCommittedHandoff(provenance, recovery[1], error); }
|
|
4861
|
+
}
|
|
4862
|
+
if (args.includes('--adopt-legacy-run') && !adopt) {
|
|
4863
|
+
denyHandoff('explicit legacy adoption requires exactly --adopt-legacy-run=<RunId>');
|
|
4864
|
+
}
|
|
4865
|
+
if (adopt && handoffSkill) {
|
|
4866
|
+
// The model-driven Skill path never adopts: it only confirms the owner's expansion already did.
|
|
4867
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4868
|
+
const owner = ownership.claim || ownership.binding;
|
|
4869
|
+
if (ownership.status !== 'OWNED' || owner?.runId !== adopt[1] || owner?.taskInstanceId !== taskInstanceId || owner?.routeGeneration !== taskInstanceId) {
|
|
4870
|
+
denyHandoff('legacy adoption requires the owner\'s explicit slash-command invocation');
|
|
4871
|
+
}
|
|
4872
|
+
handoffRunId = adopt[1];
|
|
4873
|
+
} else if (adopt) {
|
|
4874
|
+
// Explicit owner-invoked migration only: never reached from session start, Stop or an ordinary prompt.
|
|
4875
|
+
taskInstanceId = `task-${crypto.randomBytes(16).toString('hex')}`;
|
|
4876
|
+
try {
|
|
4877
|
+
await provenance.adoptLegacyHandoffRun({ projectRoot, sessionId, taskInstanceId, routeGeneration: taskInstanceId, runId: adopt[1] });
|
|
4878
|
+
} catch (error) {
|
|
4879
|
+
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]}`);
|
|
4880
|
+
}
|
|
4881
|
+
handoffRunId = adopt[1];
|
|
4882
|
+
}
|
|
4883
|
+
if (!adopt && args.includes('--resume-run') && !resume) {
|
|
4884
|
+
denyHandoff('an explicit user invocation with exactly --resume-run=<RunId> is required');
|
|
4885
|
+
}
|
|
4886
|
+
if (adopt) {
|
|
4887
|
+
// Identity is committed above; the shared route publication below binds the route to it.
|
|
4888
|
+
} else if (resume && handoffSkill) {
|
|
4889
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4890
|
+
if (ownership.status !== 'OWNED' || !ownership.claim || ownership.claim.runId !== resume[1]
|
|
4891
|
+
|| ownership.claim.taskInstanceId !== taskInstanceId || ownership.claim.routeGeneration !== taskInstanceId) {
|
|
4892
|
+
denyHandoff('resume requires an active claim from the current user invocation');
|
|
4893
|
+
}
|
|
4894
|
+
handoffRunId = resume[1];
|
|
4895
|
+
} else if (resume) {
|
|
4896
|
+
// A new explicit invocation is not a verified redelivery of the prior task.
|
|
4897
|
+
taskInstanceId = `task-${crypto.randomBytes(16).toString('hex')}`;
|
|
4898
|
+
try {
|
|
4899
|
+
const cursor = await fs.promises.readFile(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8');
|
|
4900
|
+
const ids = [...cursor.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
|
|
4901
|
+
if (ids.length !== 1 || ids[0][1] !== resume[1]) throw new Error('target cursor identity mismatch');
|
|
4902
|
+
const current = await provenance.resolveHandoffApplicability({ projectRoot, sessionId, taskInstanceId, runId: resume[1], routeGeneration: taskInstanceId });
|
|
4903
|
+
if (current.status === 'UNKNOWN') throw new Error('handoff authority unavailable');
|
|
4904
|
+
// Do not publish route identity until the ownership commit succeeds.
|
|
4905
|
+
// Without a verified redelivery identity, interruption may require a new
|
|
4906
|
+
// explicit transfer rather than treating session identity as a retry.
|
|
4907
|
+
await provenance.claimHandoffResume({ projectRoot, sessionId, taskInstanceId, runId: resume[1], routeGeneration: taskInstanceId });
|
|
4908
|
+
handoffRunId = resume[1];
|
|
4909
|
+
} catch (error) {
|
|
4910
|
+
await denyCommittedHandoff(provenance, resume[1], error);
|
|
4911
|
+
}
|
|
4912
|
+
} else {
|
|
4913
|
+
try {
|
|
4914
|
+
let cursor;
|
|
4915
|
+
try { cursor = await fs.promises.readFile(path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8'); }
|
|
4916
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
4917
|
+
let ownsLiveCursor = false;
|
|
4918
|
+
if (cursor != null) {
|
|
4919
|
+
const phase = /^Phase:\s*(\S+)\s*$/im.exec(cursor)?.[1]?.toLowerCase();
|
|
4920
|
+
if (!phase || !['done', 'blocked'].includes(phase)) {
|
|
4921
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4922
|
+
const owner = ownership.claim || ownership.binding;
|
|
4923
|
+
if (ownership.status !== 'OWNED' || !continuingTask || !handoffRunId || owner?.taskInstanceId !== taskInstanceId
|
|
4924
|
+
|| owner?.routeGeneration !== taskInstanceId || owner?.runId !== handoffRunId) {
|
|
4925
|
+
if (handoffExpansion && ownership.status === 'UNKNOWN') {
|
|
4926
|
+
const ids = [...cursor.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
|
|
4927
|
+
if (ids.length === 1 && /^handoff-[a-f0-9]{64}$/.test(ids[0][1])) {
|
|
4928
|
+
try {
|
|
4929
|
+
const committed = await provenance.currentHandoffRecovery({ projectRoot, sessionId, runId: ids[0][1] });
|
|
4930
|
+
denyHandoff(`committed-but-unreconciled. RunId ${ids[0][1]}, generation ${committed.generation}. Run /ukit:handoff-fullstack --recover-run=${ids[0][1]} --generation=${committed.generation}`);
|
|
4931
|
+
} catch {}
|
|
4932
|
+
}
|
|
4933
|
+
}
|
|
4934
|
+
const legacy = await provenance.describeLegacyHandoffCursor({ runRoot: projectRoot });
|
|
4935
|
+
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}`);
|
|
4936
|
+
throw new Error('live cursor requires explicit --resume-run=<RunId>');
|
|
4937
|
+
}
|
|
4938
|
+
ownsLiveCursor = true;
|
|
4939
|
+
}
|
|
4940
|
+
}
|
|
4941
|
+
handoffRunId ||= `handoff-${crypto.createHash('sha256').update(`${sessionId}\0${taskInstanceId}`).digest('hex')}`;
|
|
4942
|
+
if (!ownsLiveCursor) await provenance.bindHandoffRun({ projectRoot, sessionId, taskInstanceId, runId: handoffRunId, routeGeneration: taskInstanceId });
|
|
4943
|
+
} catch (error) { denyHandoff(String(error.message).slice(0, 360)); }
|
|
4944
|
+
}
|
|
4945
|
+
}
|
|
4550
4946
|
const runtimeConfig = await loadRuntimeConfig(projectRoot);
|
|
4947
|
+
if (handoffSkill || handoffExpansion) {
|
|
4948
|
+
try {
|
|
4949
|
+
const provenance = await import(pathToFileURL(path.join(projectRoot, '.claude/ukit/runtime/handoff-provenance.mjs')).href);
|
|
4950
|
+
await provenance.withHandoffOwner({ projectRoot, sessionId, taskInstanceId, runId: handoffRunId, routeGeneration: taskInstanceId }, async () => {
|
|
4951
|
+
await persistRouteState(JSON.stringify({ ...previous, sessionId, ts: Date.now(), source: 'skill-router-handoff-start' }));
|
|
4952
|
+
if (handoffExpansion && handoffRunId) {
|
|
4953
|
+
const ownership = await provenance.resolveCursorApplicability({ projectRoot, sessionId });
|
|
4954
|
+
const owner = ownership.claim || ownership.binding;
|
|
4955
|
+
if (ownership.status === 'OWNED' && owner?.taskInstanceId === taskInstanceId && owner?.runId === handoffRunId) {
|
|
4956
|
+
const cursorPath = path.join(projectRoot, 'docs/AI_HANDOFF/RUN.md');
|
|
4957
|
+
const cursor = await fs.promises.readFile(cursorPath, 'utf8');
|
|
4958
|
+
const cursorIds = [...cursor.matchAll(/^RunId:\s*(\S+)\s*$/gim)];
|
|
4959
|
+
if (cursorIds.length !== 1 || cursorIds[0][1] !== handoffRunId) throw new Error('cursor identity changed before pause lift');
|
|
4960
|
+
if (/^Paused:\s*yes\s*$/im.test(cursor)) {
|
|
4961
|
+
const next = cursor.replace(/^(Paused:\s*)yes(\s*)$/im, '$1no$2');
|
|
4962
|
+
if (await fs.promises.readFile(cursorPath, 'utf8') !== cursor) throw new Error('cursor changed before pause lift');
|
|
4963
|
+
const tmp = `${cursorPath}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
4964
|
+
try {
|
|
4965
|
+
await fs.promises.writeFile(tmp, next, { flag: 'wx' });
|
|
4966
|
+
await fs.promises.rename(tmp, cursorPath);
|
|
4967
|
+
} finally { await fs.promises.rm(tmp, { force: true }).catch(() => {}); }
|
|
4968
|
+
if (await fs.promises.readFile(cursorPath, 'utf8') !== next) throw new Error('pause lift verification failed');
|
|
4969
|
+
}
|
|
4970
|
+
}
|
|
4971
|
+
}
|
|
4972
|
+
});
|
|
4973
|
+
} catch (error) {
|
|
4974
|
+
const provenance = await import(pathToFileURL(path.join(projectRoot, '.claude/ukit/runtime/handoff-provenance.mjs')).href);
|
|
4975
|
+
await denyCommittedHandoff(provenance, handoffRunId, error);
|
|
4976
|
+
}
|
|
4977
|
+
if (handoffRunId) {
|
|
4978
|
+
process.stdout.write(JSON.stringify({
|
|
4979
|
+
hookSpecificOutput: {
|
|
4980
|
+
hookEventName: handoffExpansion ? 'UserPromptExpansion' : 'PreToolUse',
|
|
4981
|
+
additionalContext: `UKit handoff invocation RunId: ${handoffRunId}. Preserve this exact identity in RUN.md through every rewrite, cycle and resume.`,
|
|
4982
|
+
},
|
|
4983
|
+
}));
|
|
4984
|
+
}
|
|
4985
|
+
process.exit(0);
|
|
4986
|
+
}
|
|
4551
4987
|
// BL-013: the hook/bridge payload's transcript pointer (ukit-bridge.js:217,228
|
|
4552
4988
|
// forwards transcriptPath; Claude Code payloads carry transcript_path). The
|
|
4553
4989
|
// extractor reads a bounded tail of this file — never the whole transcript.
|
|
@@ -4909,6 +5345,7 @@ function applyTaskSemantics(contract, semantic) {
|
|
|
4909
5345
|
ts: now,
|
|
4910
5346
|
requestKey,
|
|
4911
5347
|
routeSummary: rescuedRouteSummary,
|
|
5348
|
+
ownerControl: undefined,
|
|
4912
5349
|
};
|
|
4913
5350
|
reusedState.fingerprint = buildRouteStateFingerprint(reusedState);
|
|
4914
5351
|
|
|
@@ -5118,7 +5555,7 @@ if [ -f "$THRESHOLD_SCRIPT" ]; then
|
|
|
5118
5555
|
# PostToolUse call used to pay a second full node spawn for that no-op, doubling the
|
|
5119
5556
|
# per-mutation hook latency. Tool payloads always carry tool_name; skip them.
|
|
5120
5557
|
case "$INPUT" in
|
|
5121
|
-
*'"tool_name"'*) ;;
|
|
5558
|
+
*'"tool_name"'*|*'"UserPromptExpansion"'*) ;;
|
|
5122
5559
|
*) printf '%s' "$INPUT" | CLAUDE_PROJECT_DIR="$PROJECT_ROOT" node "$THRESHOLD_SCRIPT" prompt 2>/dev/null || true ;;
|
|
5123
5560
|
esac
|
|
5124
5561
|
fi
|