@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.
Files changed (28) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/manifests/documentation.yaml +10 -0
  3. package/manifests/platform.full.yaml +15 -0
  4. package/package.json +4 -1
  5. package/template_project/.claude/commands/ukit/handoff-fullstack.md +34 -12
  6. package/template_project/.claude/hooks/completion-gate.sh +10 -1
  7. package/template_project/.claude/hooks/handoff-resume.sh +38 -53
  8. package/template_project/.claude/hooks/owner-stop-gate.mjs +41 -0
  9. package/template_project/.claude/hooks/skill-router.sh +473 -36
  10. package/template_project/.claude/hooks/verification-guard.sh +8 -1
  11. package/template_project/.claude/settings.json +33 -1
  12. package/template_project/.claude/ukit/index/publication-intent.mjs +128 -13
  13. package/template_project/.claude/ukit/index/route-task.mjs +124 -26
  14. package/template_project/.claude/ukit/runtime/block-breaker.mjs +1 -0
  15. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +8 -1
  16. package/template_project/.claude/ukit/runtime/cron-operation-adapter.mjs +14 -5
  17. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +399 -35
  18. package/template_project/.claude/ukit/runtime/handoff-intent.mjs +5 -0
  19. package/template_project/.claude/ukit/runtime/handoff-provenance.mjs +277 -0
  20. package/template_project/.claude/ukit/runtime/loop-state.mjs +23 -4
  21. package/template_project/.claude/ukit/runtime/operation-evidence.mjs +9 -0
  22. package/template_project/.claude/ukit/runtime/reinject-context.mjs +10 -0
  23. package/template_project/.claude/ukit/runtime/resumable-run.mjs +33 -11
  24. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +284 -58
  25. package/template_project/.omp/hooks/pre/ukit-bridge.js +171 -3
  26. package/scripts/dev/worktree-preflight.mjs +0 -166
  27. package/scripts/measure-decision-gateway.mjs +0 -306
  28. package/scripts/probe/codex-capability-probe.mjs +0 -169
@@ -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
- const state = await readJson(statePath, null);
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;
@@ -59,6 +59,16 @@
59
59
  },
60
60
  "hooks": {
61
61
  "PreToolUse": [
62
+ {
63
+ "matcher": ".*",
64
+ "hooks": [
65
+ {
66
+ "type": "command",
67
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/owner-stop-gate.mjs\":5",
68
+ "timeout": 15
69
+ }
70
+ ]
71
+ },
62
72
  {
63
73
  "matcher": "Read|Grep|Glob",
64
74
  "hooks": [
@@ -79,6 +89,16 @@
79
89
  }
80
90
  ]
81
91
  },
92
+ {
93
+ "matcher": "Skill",
94
+ "hooks": [
95
+ {
96
+ "type": "command",
97
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/skill-router.sh\":20",
98
+ "timeout": 30
99
+ }
100
+ ]
101
+ },
82
102
  {
83
103
  "matcher": "MultiEdit|NotebookEdit|Agent|Task",
84
104
  "hooks": [
@@ -102,7 +122,7 @@
102
122
  ],
103
123
  "PostToolUse": [
104
124
  {
105
- "matcher": "CronDelete|CronList",
125
+ "matcher": "CronDelete|CronList|TaskStop|TaskOutput",
106
126
  "hooks": [
107
127
  {
108
128
  "type": "command",
@@ -164,6 +184,18 @@
164
184
  ]
165
185
  }
166
186
  ],
187
+ "UserPromptExpansion": [
188
+ {
189
+ "matcher": "^(ukit:)?handoff-fullstack$",
190
+ "hooks": [
191
+ {
192
+ "type": "command",
193
+ "command": "node \"$CLAUDE_PROJECT_DIR/.claude/ukit/runtime/hook-chain-runner.mjs\" --emit-verdict - \"$CLAUDE_PROJECT_DIR/.claude/hooks/skill-router.sh\":20",
194
+ "timeout": 30
195
+ }
196
+ ]
197
+ }
198
+ ],
167
199
  "UserPromptSubmit": [
168
200
  {
169
201
  "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:092abf191252a5a8f601b66235084726e76c2757b6875cfe5a5243dbbc6f9f6c';
3
+ export const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:d2c70fa8c68d50f31917ee7befd16f6df36a441a2aae79a0de879f5b0a09edf1';
4
4
 
5
5
  export function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
6
6
  return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
@@ -10,7 +10,7 @@ export function semanticContractIdentity({ promptText = '', targetFile = '', tas
10
10
  const semanticContractShape = (contract) => JSON.stringify([
11
11
  contract?.taskKind, contract?.publication === true, contract?.operationGoal ?? null,
12
12
  contract?.configurationScope ?? null, contract?.releasePolicy ?? null, contract?.conditionalObligations ?? null,
13
- contract?.reportArtifact ?? null, contract?.verificationOnly === true, contract?.statusReport === true,
13
+ contract?.reportArtifact ?? null, contract?.verificationOnly === true, contract?.statusReport === true, contract?.stateVerification === true, contract?.stateAction === true, contract?.stateConditionalStop === true, (contract?.stateTargets || []).join(','),
14
14
  [...(contract?.completionEvidence || [])].sort(),
15
15
  ]);
16
16
  export function compareSemanticContracts({ stored, fresh, previousIdentity, identity }) {
@@ -45,7 +45,7 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
45
45
  const quoted = Boolean(marker || fence || /^\s*>/.test(raw));
46
46
  const context = quoted ? 'quotation' : description && bullet ? 'description' : 'instruction';
47
47
  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';
48
- const condition = text.match(/\b(?:if|neu|only if|only when)\b[^,;.\n]*/)?.[0] || null;
48
+ const condition = text.match(/\b(?:if|neu|only if|only when|only after|only once)\b[^,;.\n]*/)?.[0] || null;
49
49
  spans.push({ start: offset + part.index, end: offset + part.index + raw.length, raw,
50
50
  context, polarity, condition, activation: condition ? 'pending' : context !== 'instruction' || polarity === 'prohibited' ? 'inactive' : 'eligible' });
51
51
  }
@@ -65,10 +65,23 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
65
65
  const nativeReleasePolicy = classifySemanticText({ promptText: original, targetFile }).releasePolicy;
66
66
  const deferredSpans = new Set(spans.filter(span => span.context === 'instruction'
67
67
  && span.polarity === 'affirmative' && span.condition
68
- && /^(?:[-*+•\d.)\s]*)(?:if|neu|only if|only when)\b/.test(foldIntent(span.raw))
68
+ && /^(?:[-*+•\d.)\s]*)(?:if|neu|only if|only when|only after|only once)\b/.test(foldIntent(span.raw))
69
69
  && !nativeReleasePolicy && !VERIFICATION_GOAL.test(foldIntent(original))
70
70
  && !defectRepairBranches(foldIntent(span.raw)).length
71
71
  && ordersPublicationText(foldIntent(span.raw).replace(/^[^,]*,\s*/, ''))));
72
+ spans.forEach((span, index) => {
73
+ const folded = foldIntent(span.raw);
74
+ const verb = folded.match(CONDITIONAL_RUNTIME_VERB);
75
+ const cond = span.condition ? folded.indexOf(span.condition) : -1;
76
+ if (!verb || cond < 0 || span.context !== 'instruction' || span.polarity !== 'affirmative' || nativeReleasePolicy
77
+ || CONDITIONAL_RUNTIME_EXCLUDED.test(folded)) return;
78
+ const governed = verb.index >= cond || /^(?:only\s+(?:if|when)|unless)\b/.test(span.condition);
79
+ if (!NEED_OR_FAILURE_CONDITION.test(span.condition)) return;
80
+ const leadsVerification = VERIFICATION_LEAD.test(folded.slice(0, cond)) && cond > 0
81
+ || spans.slice(0, index).some(prior => prior.context === 'instruction' && prior.polarity === 'affirmative'
82
+ && !prior.condition && VERIFICATION_LEAD.test(foldIntent(prior.raw)));
83
+ if (governed && leadsVerification) deferredSpans.add(span);
84
+ });
72
85
  // An explicit alternative links both consequences. Keep the unconditional
73
86
  // review prefix, but do not require a repair before its review has found one.
74
87
  const alternatives = spans.filter(span => span.condition?.startsWith('otherwise:'));
@@ -82,10 +95,11 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
82
95
  }
83
96
  for (const span of [...spans].reverse()) {
84
97
  const approvalPending = span.condition && /\b(?:approv\w*|permission|authori[sz]\w*)\b/.test(span.condition);
85
- if (span.context === 'quotation' || span.context === 'description' || approvalPending || deferredSpans.has(span)) {
98
+ 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));
99
+ if (span.context === 'quotation' || span.context === 'description' || approvalPending || deferredSpans.has(span) || evidenceStatement) {
86
100
  // Retain the prefix before a comma-introduced postfix repair condition.
87
101
  // Leading conditions and otherwise consequences are masked in full.
88
- const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|otherwise)\b/.test(foldIntent(span.raw))
102
+ const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|only after|only once|otherwise)\b/.test(foldIntent(span.raw))
89
103
  ? span.raw.match(/^[^,]*,/)?.[0] || '' : '';
90
104
  const masked = prefix + span.raw.slice(prefix.length).replace(/[^\r\n]/g, ' ');
91
105
  semanticInput = semanticInput.slice(0, span.start) + masked + semanticInput.slice(span.end);
@@ -126,6 +140,12 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
126
140
  }
127
141
  return { engineVersion: SEMANTIC_ENGINE_VERSION, identity: { taskInstanceId, sessionId }, original, spans, actions, semantic };
128
142
  }
143
+ 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/;
144
+ const CONDITIONAL_RUNTIME_VERB = /\b(?:redeploy|deploy|restart|khoi dong lai|trien khai)\b/;
145
+ const CONDITIONAL_RUNTIME_EXCLUDED = /\b(?:publish|phat hanh|commit|push|tag|git|implement|fix|edit|modify|sua)\b/;
146
+ const VERIFICATION_LEAD = /^[-*+\u2022>\d.)\s]*(?:(?:please|hay|vui long|now|also|first)\s+)*(?:verify|check|confirm|validate|inspect|kiem tra|xac nhan)\b/;
147
+ 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';
148
+ const PAST_RELEASE_ITEM = new RegExp(`^(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}`);
129
149
  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/;
130
150
  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/;
131
151
  const PUBLISH_ORDER_HEADER = /prohibit|forbidden|out of scope|non-goal|scope control/;
@@ -209,9 +229,13 @@ export function publicationScope(promptText = '') {
209
229
  const bullet = /^\s*(?:[-*•]|\d+[.)])\s+/.test(line);
210
230
  if (!bullet) prohibitionBlock = PUBLISH_ORDER_NEGATOR.test(line) && /:\s*$/.test(line);
211
231
  for (const clause of line.split(/;|\.\s+|\bthen\b|\bbut\b|\binstead\b/)) {
232
+ // A temporary restriction pending prerequisites is not a task-wide prohibition.
233
+ // This classification does not authorize execution or establish those prerequisites.
212
234
  let negated = bullet && prohibitionBlock;
213
235
  for (const raw of clause.split(/,|\band\b|\bor\b|\bnor\b/)) {
214
236
  const item = raw.replace(/^[\s*•-]+/, '').trim();
237
+ if (/\b(?:do not|don't|must not|not yet)\b[^,]*\b(?:publish|publication|release)\b[^,]*\b(?:while|until|before)\b/.test(item)
238
+ || /\b(?:publish|publication|release)\b[^,]*\b(?:must not|not yet)\b[^,]*\b(?:until|before|while)\b/.test(item)) continue;
215
239
  if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
216
240
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
217
241
  if (negated && /\b(?:release|publish|publication)\b/.test(item)) prohibited = true;
@@ -244,7 +268,7 @@ function ordersPublicationText(promptText = '') {
244
268
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
245
269
  const commandItem = item.replace(/^(?:please|just|now|also|then)\s+/, '');
246
270
  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);
247
- 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);
271
+ 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);
248
272
  const politeItem = item.replace(/^(?:(?:please|just|now|also|then|vui long|hay)\s+)+/, '');
249
273
  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);
250
274
  if (!negated && (releaseOrder || viPublish || (publication && (
@@ -258,7 +282,7 @@ function ordersPublicationText(promptText = '') {
258
282
  return ordered;
259
283
  }
260
284
 
261
- const NOT_A_SERVICE = new Set(['it', 'this', 'that', 'them', 'the', 'all', 'everything', 'service', 'services', 'again', 'now', 'to', 'and', 'then']);
285
+ 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']);
262
286
  function nativeOperationGoal(domain, actionable, text) {
263
287
  const goal = { domain, target: null, desiredState: 'verified', completionSemantics: 'execute-and-verify', requiredTargets: [] };
264
288
  const clauses = actionable.join(' . ');
@@ -310,6 +334,7 @@ function neutralizeNonOrders(text) {
310
334
  return source.replace(noVerbList(), ' ')
311
335
  .replace(/\brelease-(?:publication|verification)\b|\brelease\s+(?:instructions?|authorization|obligations?|policies|readiness)\b/g, 'publication topic')
312
336
  .replace(/\brelease\s+(?:safety|verification\s+plan)\b/g, 'publication topic')
337
+ .replace(new RegExp(`(^|[\\n.;]\\s*)(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}[^.;\\n]*`, 'g'), '$1publication topic')
313
338
  .replace(/^[ \t]*[-*+•][ \t]*owner\s+yeu\s+cau\b[^\n]*/gm, ' ')
314
339
  .replace(/^([ \t]*[-*+•][ \t]*)release\s+progress\s+reporter(?=[ \t]*(?:,|$))/gm, '$1progress reporter')
315
340
  .replace(/^[ \t]*(?:[-*+\u2022]|\d+[.)])[ \t]*(?:negative|positive)\s+controls?\b[^\n]*(?:\n(?![ \t]*(?:[-*+\u2022]|\d+[.)])|[ \t]*\n)[^\n]*)*/gm, ' ')
@@ -320,6 +345,8 @@ function neutralizeNonOrders(text) {
320
345
  .replace(/\b(?:uu tien|prefer(?:red)?)\s+(?:a\s+|an\s+)?(?:configuration|config|cau hinh)\s+(?:change|changes|update|thay doi)\b/g, ' ')
321
346
  .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, ' ')
322
347
  .replace(/[^.;\n]*\b(?:nao|gi|sao|the nao|bao nhieu)\b[^.;\n]*\?/g, ' ')
348
+ .replace(/\b(?:truoc khi|before)\s+(?:quay lai|tro lai|returning|going back|you (?:go|return)|we (?:go|return))\b[^.;\n]*/g, ' ')
349
+ .replace(/\b(?:cua|do|tu)\s+chinh\b|\bchinh\s+(?:cac|nhung|phien|no|minh|toi|ban than)\b/g, ' ')
323
350
  .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, ' ')
324
351
  .replace(/\bwrite\s*\/\s*verification\b|\bverification\s*\/\s*write\b|\bwrite\s+(?:or|and)\s+verification\b/g, ' ')
325
352
  .replace(/\bwrite\s+permission\b/g, 'permission')
@@ -367,6 +394,13 @@ function declaredReadOnly(promptText, releasePolicy) {
367
394
 
368
395
  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/;
369
396
  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/;
397
+ 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;
398
+ 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/;
399
+ const bansTestRuns = (promptText) => {
400
+ const plain = String(promptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
401
+ const bans = plain.match(BANS_TEST_RUNS);
402
+ return !!bans && !bans.some((ban) => /\bon\s+\w+$/.test(ban)) && !OWN_TARGET.test(plain.replace(BANS_TEST_RUNS, ' '));
403
+ };
370
404
  export function isVerificationOnlyRequest(promptText) {
371
405
  const plain = String(promptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase()
372
406
  .replace(/```[\s\S]*?```/g, ' ').replace(/^[ \t]*>.*$/gm, ' ');
@@ -390,6 +424,27 @@ function neutralizeBannedLists(text) {
390
424
  });
391
425
  }
392
426
 
427
+ const OWNER_CONTROL_HOOK_TEXT = /^\s*(?:UKit completion gate:|UKit handoff|\[ukit[-\w]*\]|<system-reminder|<task-notification)/i;
428
+ 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))*$/;
429
+ 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))*$/;
430
+ 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.-]+/;
431
+ 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/;
432
+ export function classifyOwnerControl(promptText = '') {
433
+ const raw = String(promptText ?? '').normalize('NFC').trim();
434
+ if (!raw || OWNER_CONTROL_HOOK_TEXT.test(raw)) return { kind: null };
435
+ const stripped = raw.replace(/^[\s*#_-]+/, '');
436
+ if (/^[>"'`\u201c\u2018]/.test(stripped)) return { kind: null };
437
+ const sentences = stripped.split(/[.!?\n]/);
438
+ const [lead, ...rest] = sentences[0].split(/[:;]/);
439
+ const first = lead.trim().toLowerCase().replace(/\s+/g, ' ');
440
+ if (!first || first.length > 80) return { kind: null };
441
+ if (OWNER_CONTROL_TASK_WORD.test(rest.join(' ').toLowerCase())) return { kind: null };
442
+ if (!OWNER_STOP_EN.test(first) && !OWNER_STOP_VI.test(first)) return { kind: null };
443
+ const next = (sentences.slice(1).find((part) => part.trim()) || '').trim().toLowerCase();
444
+ if (OWNER_CONTROL_TASK_LEAD.test(next)) return { kind: null };
445
+ return { kind: 'stop' };
446
+ }
447
+
393
448
  export function classifyTaskSemantics(input = {}) {
394
449
  return analyzeTaskIntent(input).semantic;
395
450
  }
@@ -404,7 +459,7 @@ const collapseInspectionSentences = (text) => text.replace(INSPECTION_SENTENCE,
404
459
 
405
460
  function actionableClauses(promptText) {
406
461
  const text = neutralizeBannedLists(neutralizeNonOrders(collapseInspectionSentences(String(promptText).normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[đĐ]/g, 'd').toLowerCase())));
407
- const clauses = text.split(/\s*(?:[;\n,]|\.(?:\s+|$)|\band\b|\bthen\b|\bva\b)\s*/);
462
+ 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*/);
408
463
  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)
409
464
  && !/^[\s*+•>\d.)-]*(?:(?:please|just|hay|vui long|now|also)\s+)*(?:audit|inspect|review|analyze|analyse|explain|read|kiem tra|phan tich)\b/.test(clause)
410
465
  // A fragment led by a subordinator continues the previous clause's predicate ("…, including source
@@ -419,7 +474,66 @@ export function ordersAdditiveChange(promptText = '') {
419
474
  return actionableClauses(publicationScope(promptText).text).actionable.some((clause) => ADDITIVE_ORDER_LEAD.test(clause));
420
475
  }
421
476
 
422
- function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
477
+ const STATE_OBJECT = /\b(?:shells?|jobs?|process(?:es)?|pids?|agents?|subagents?|wakeups?|tien trinh|tac vu nen|background (?:tasks?|work)|crons?)\b/;
478
+ 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/;
479
+ const STATE_ACTION = /\b(?:stop|cancel|kill|terminate|revoke|reclaim|dung|huy|thu hoi|ket thuc)\b/;
480
+ function statePlain(promptText) {
481
+ return String(promptText).normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[\u0111\u0110]/g, 'd').toLowerCase()
482
+ .replace(/```[\s\S]*?```/g, ' ').replace(/^[ \t]*>.*$/gm, ' ');
483
+ }
484
+ export function isStateOperationRequest(promptText = '') {
485
+ const plain = statePlain(promptText);
486
+ 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;
487
+ return plain.split(/[;!?\n]+|[.:](?=\s|$)/).some((clause) => {
488
+ const lead = clause.match(STATE_LEAD);
489
+ if (!lead) return false;
490
+ const after = clause.slice(lead.index + lead[0].length);
491
+ const near = after.match(/^(?:\s+[\p{L}\p{N}_-]+){0,5}?\s+/u);
492
+ const window = after.split(/\s+/).slice(0, 7).join(' ');
493
+ return near !== null && STATE_OBJECT.test(window);
494
+ });
495
+ }
496
+
497
+ export function stateOperationShape(promptText = '') {
498
+ const plain = statePlain(promptText);
499
+ const unquoted = plain.replace(/`[^`\n]*`|"[^"\n]*"|\u201c[^\u201d\n]*\u201d/g, ' ');
500
+ 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);
501
+ let conditional = false;
502
+ let gated = false;
503
+ const action = plain.split(/[;!?\n]+|[.:](?=\s|$)|,\s*/).some((raw) => {
504
+ const clause = raw.replace(/^[\s*\-\d.)]+/, '').trim();
505
+ if (!clause) return false;
506
+ const conditionLead = /^(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause);
507
+ if (!conditionLead && /\b(?:khong|do not|don't|never|not)\b/.test(clause)) return false;
508
+ 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; }
509
+ const head = clause.split(/\s+/).slice(0, 3).join(' ');
510
+ if (/\b(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause)) {
511
+ const leadsWithCondition = /^(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause);
512
+ const preCondition = leadsWithCondition ? '' : clause.split(/\b(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/)[0].trim();
513
+ 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; }
514
+ const consequent = leadsWithCondition ? (/\s(?:then|thi)\s/.test(clause) ? clause.split(/\s(?:then|thi)\s/).pop() : '') : clause;
515
+ if (STATE_ACTION.test(consequent.split(/\s+/).slice(0, 3).join(' '))) { conditional = true; return false; }
516
+ gated = leadsWithCondition && !STATE_ACTION.test(consequent);
517
+ return false;
518
+ }
519
+ const wasGated = gated;
520
+ gated = false;
521
+ const stops = (wasGated ? STATE_ACTION.test(clause) : STATE_ACTION.test(head)) && (wasGated || STATE_OBJECT.test(clause));
522
+ if (stops && wasGated) { conditional = true; return false; }
523
+ return stops;
524
+ });
525
+ return { action, conditional: conditional && !action, targets };
526
+ }
527
+
528
+ function classifySemanticText(input = {}) {
529
+ const semantic = classifySemanticCore(input);
530
+ if (semantic.taskKind !== 'READ_ONLY' || semantic.conditionalObligations || semantic.publication || !isStateOperationRequest(input.promptText)) return semantic;
531
+ const { verificationOnly: _verification, statusReport: _status, ...rest } = semantic;
532
+ const shape = stateOperationShape(input.promptText);
533
+ return { ...rest, stateVerification: true, ...(shape.action ? { stateAction: true } : shape.conditional ? { stateConditionalStop: true } : {}), ...(shape.targets.length ? { stateTargets: shape.targets } : {}) };
534
+ }
535
+
536
+ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
423
537
  promptText = publicationScope(promptText).text;
424
538
  const releaseText = String(promptText).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
425
539
  const preflight = releaseText.match(/\b(?:yarn\s+release:verify|npm\s+run\s+release:verify)\b/)?.[0];
@@ -430,13 +544,13 @@ function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
430
544
  if (ordersPublicationText(promptText)) {
431
545
  const implementation = hasExplicitOrder(clauses.filter((clause) => !/\b(?:release|publish)\b/.test(clause)));
432
546
  const remaining = clauses.filter((clause) => !ordersPublicationText(clause) && !/\b(?:release|publish)\b/.test(clause)).join('; ');
433
- const base = remaining.trim() ? classifySemanticText({ promptText: remaining, targetFile }) : {};
547
+ const base = remaining.trim() ? classifySemanticCore({ promptText: remaining, targetFile }) : {};
434
548
  delete base.verificationOnly;
435
549
  delete base.statusReport;
436
550
  return { ...base, taskKind: implementation ? 'MIXED' : 'OPERATIONAL', publication: true, ...(releasePolicy ? { releasePolicy } : {}) };
437
551
  }
438
552
  if (!/[a-z0-9]/.test(text)) return { taskKind: 'READ_ONLY' };
439
- if (declaredReadOnly(promptText, releasePolicy)) return { taskKind: 'READ_ONLY', ...(isVerificationOnlyRequest(promptText) ? { verificationOnly: true } : {}) };
553
+ if (declaredReadOnly(promptText, releasePolicy)) return { taskKind: 'READ_ONLY', ...(isVerificationOnlyRequest(promptText) && !bansTestRuns(promptText) ? { verificationOnly: true } : {}) };
440
554
  const sourceOrder = actionable.some((clause) => /\b(?:implement|fix(?:es)?|apply|refactor|modify|edit|write|update|sua|viet|chinh)\b/.test(clause)
441
555
  && /\b(?:source|code|logic|scheduler|implementation|ma nguon)\b|\.[cm]?[jt]sx?\b/.test(clause));
442
556
  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));
@@ -475,7 +589,7 @@ function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
475
589
  && !/\.[cm]?[jt]sx?\b/.test(clause) && !/\bgit\b/.test(clause));
476
590
  const nativeDomain = cronOperation ? 'scheduled-job' : gitOperation !== runtimeOperation ? (gitOperation ? 'git-integrity' : 'service-runtime') : null;
477
591
  const operation = Boolean(nativeDomain);
478
- if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', verificationOnly: true };
592
+ if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', ...(bansTestRuns(promptText) ? {} : { verificationOnly: true }) };
479
593
  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/;
480
594
  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/;
481
595
  const CONFIG_NOUN = /\b(?:configuration|config|toggle|cau hinh)\b/;
@@ -528,6 +642,7 @@ export function applyTaskSemantics(contract, semantic) {
528
642
  return { ...(contract || {}), ...semantic,
529
643
  completionEvidence: semantic.taskKind === 'DOCUMENTATION_OUTPUT' ? ['report-artifact'] : operationOnly ? ['operation-verification']
530
644
  : semantic.taskKind === 'MIXED' ? [...new Set([...evidence, 'write-evidence', 'operation-verification'])]
645
+ : semantic.taskKind === 'READ_ONLY' && semantic.stateVerification ? ['state-verification']
531
646
  : semantic.taskKind === 'READ_ONLY' && semantic.statusReport ? []
532
647
  : semantic.taskKind === 'READ_ONLY' ? (semantic.verificationOnly ? ['verification-evidence'] : ['impact-evidence'])
533
648
  // A routed contract owns the debt; an unrouted (informational/null) turn carries none, because
@@ -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 previousState = previousStateOwnershipBlocked
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');
@@ -1389,11 +1412,14 @@ async function main() {
1389
1412
  const guidanceRefresh = Boolean(guidanceReuse) && Boolean(lastPrompt);
1390
1413
  if (continuingTask || guidanceRefresh) promptText = lastPrompt;
1391
1414
  const carryGuidanceState = (state) => {
1415
+ if (sessionId && previousState.ownerControl?.kind === 'stop' && previousState.ownerControl.sessionId === sessionId) {
1416
+ state.ownerControl = previousState.ownerControl;
1417
+ }
1392
1418
  if (!guidanceRefresh || state.taskInstanceId !== previousState.taskInstanceId) return state;
1393
1419
  state.requestKey = previousState.requestKey;
1394
1420
  state.routingContext = { ...previousState.routingContext };
1395
1421
  state.routeSummary ||= {};
1396
- for (const key of ['executionContract', 'expectedSourceFiles', 'completionState', 'continuationState', 'executionMode']) {
1422
+ for (const key of ['executionContract', 'expectedSourceFiles', 'expectedSourceProvenance', 'completionState', 'continuationState', 'executionMode']) {
1397
1423
  if (previousState.routeSummary[key] !== undefined) state.routeSummary[key] = previousState.routeSummary[key];
1398
1424
  else delete state.routeSummary[key];
1399
1425
  }
@@ -1496,7 +1522,7 @@ async function main() {
1496
1522
  }
1497
1523
  const sharedState = carryGuidanceState({ ...reusableState, taskInstanceId, taskIdOrigin, source: 'task-route', ts: Date.now() });
1498
1524
  if (canPersistRouteState) {
1499
- try { await persistSharedRouteState(sharedStatePath, sharedState); }
1525
+ try { await requirePersistedRouteState(sharedStatePath, sharedState, { expectedRouteBytes }); }
1500
1526
  catch (error) { console.error(`route-task: state persist degraded — ${error?.message ?? error}`); }
1501
1527
  }
1502
1528
  printRouteState(sharedState);
@@ -1597,7 +1623,7 @@ async function main() {
1597
1623
  // Advisory persistence — an EACCES/ENOSPC under the lock must never lose
1598
1624
  // the printed route; degrade to stderr and print anyway.
1599
1625
  try {
1600
- await persistSharedRouteState(sharedStatePath, sharedState);
1626
+ await requirePersistedRouteState(sharedStatePath, sharedState, { expectedRouteBytes });
1601
1627
  await appendRouteAuditEntry(routeAuditPath, buildRouteAuditEntry({
1602
1628
  state: sharedState,
1603
1629
  }));
@@ -1655,7 +1681,7 @@ async function main() {
1655
1681
  // Advisory persistence — an EACCES/ENOSPC under the lock must never lose
1656
1682
  // the printed route; degrade to stderr and print anyway.
1657
1683
  try {
1658
- await persistSharedRouteState(sharedStatePath, sharedState);
1684
+ await requirePersistedRouteState(sharedStatePath, sharedState, { expectedRouteBytes });
1659
1685
  await appendRouteAuditEntry(routeAuditPath, buildRouteAuditEntry({
1660
1686
  route,
1661
1687
  state: sharedState,
@@ -4127,7 +4153,41 @@ export async function applyRoleAdviceConsult({
4127
4153
  }
4128
4154
 
4129
4155
 
4130
- function buildRouteSummary({
4156
+ const PROMPT_FILE_TOKEN_RE = /[\w@.~+-]+(?:\/[\w@.~+-]+)*\.[A-Za-z][\w]{0,9}\b/g;
4157
+ const PROMPT_DIR_TOKEN_RE = /[\w@.~+-]+(?:\/[\w@.~+-]+)*\/(?![\w@.~+-])|[\w@.~+-]+(?:\/[\w@.~+-]+)+(?![\w@.~+/-])/g;
4158
+ function promptNamesFile(promptTokens, filePath, promptDirs = []) {
4159
+ const file = String(filePath).replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase();
4160
+ const base = file.split('/').pop();
4161
+ if (promptDirs.some((dir) => file.startsWith(`${dir}/`) || file.includes(`/${dir}/`))) return true;
4162
+ return promptTokens.some((token) => token === file
4163
+ || (token.includes('/') && file.endsWith(`/${token}`))
4164
+ || (token.includes('/') && token.endsWith(`/${file}`))
4165
+ || token === base);
4166
+ }
4167
+ const DOCS_HOUSEKEEPING_PROMPT = /\b(?:docs?|documentation|readme|changelog|worklog|archive|archiving|status\s+(?:file|doc|update)|plans?|commit|tai\s*lieu|tài\s*liệu|luu\s*tru|lưu\s*trữ)\b/i;
4168
+ const CODE_CHANGE_PROMPT = /\b(?:fix|bug|implement|refactor|rewrite|add\s+(?:a\s+|an\s+|the\s+)?(?:function|feature|option|test|endpoint|handler|support)|patch|crash|error|regression|sua\s+loi|sửa\s+lỗi|them\s+tinh\s+nang|thêm\s+tính\s+năng)\b/i;
4169
+ export function deriveExpectedSourceProvenance({ promptText = '', targetFile = null, primaryTargets = [], relatedTests = [] } = {}) {
4170
+ const valid = (list) => (Array.isArray(list) ? list : []).filter((f) => typeof f === 'string' && f.trim());
4171
+ const promptTokens = String(promptText ?? '').replace(/\\/g, '/').toLowerCase()
4172
+ .match(PROMPT_FILE_TOKEN_RE)?.map((t) => t.replace(/^\.\//, '')) ?? [];
4173
+ const promptDirs = (String(promptText ?? '').replace(/\\/g, '/').toLowerCase().match(PROMPT_DIR_TOKEN_RE) ?? [])
4174
+ .map((d) => d.replace(/^\.\//, '').replace(/\/+$/, '')).filter((d) => d && !/\.[a-z][\w]{0,9}$/.test(d));
4175
+ const primaries = valid(primaryTargets);
4176
+ const tests = valid(relatedTests);
4177
+ const target = typeof targetFile === 'string' && targetFile.trim() ? targetFile : null;
4178
+ const named = (f) => promptNamesFile(promptTokens, f, promptDirs);
4179
+ const anchored = Boolean(target) || [...primaries, ...tests].some(named);
4180
+ const advisory = DOCS_HOUSEKEEPING_PROMPT.test(String(promptText ?? '')) && !CODE_CHANGE_PROMPT.test(String(promptText ?? ''));
4181
+ const entries = [];
4182
+ if (target) entries.push({ file: target, source: 'target' });
4183
+ for (const f of primaries) entries.push({ file: f, source: named(f) ? 'prompt' : target ? 'target' : anchored || advisory ? 'index-guess' : 'index-primary' });
4184
+ for (const f of tests) entries.push({ file: f, source: !anchored ? (advisory ? 'index-guess' : 'index-primary') : named(f) ? 'prompt' : 'related-test' });
4185
+ const seen = new Set();
4186
+ const expectedSourceProvenance = entries.filter((e) => (seen.has(e.file) ? false : seen.add(e.file))).slice(0, 8);
4187
+ return { expectedSourceFiles: expectedSourceProvenance.map((e) => e.file), expectedSourceProvenance };
4188
+ }
4189
+
4190
+ export function buildRouteSummary({
4131
4191
  activeSkills = [],
4132
4192
  routingContext = {},
4133
4193
  contextRecommendation = null,
@@ -4157,11 +4217,12 @@ function buildRouteSummary({
4157
4217
  // files, so carry the full resolver list (target + primaryTargets + relatedTests), bounded
4158
4218
  // for compact route state. Absent when the route has no indexed context — the ledger then
4159
4219
  // falls back to its legacy any-read behaviour.
4160
- const expectedSourceFiles = unique([
4161
- ...(routingContext.targetFile ? [routingContext.targetFile] : []),
4162
- ...(preview.primaryTargets ?? []),
4163
- ...(preview.relatedTests ?? []),
4164
- ].filter((filePath) => typeof filePath === 'string' && filePath.trim())).slice(0, 8);
4220
+ const { expectedSourceFiles, expectedSourceProvenance } = deriveExpectedSourceProvenance({
4221
+ promptText: routingContext.lastExplicitUserPromptText || routingContext.promptText,
4222
+ targetFile: routingContext.targetFile,
4223
+ primaryTargets: preview.primaryTargets,
4224
+ relatedTests: preview.relatedTests,
4225
+ });
4165
4226
  const primaryCommands = unique(verificationRecommendation?.commands ?? []);
4166
4227
  const fallbackCommands = unique(verificationRecommendation?.fallbackCommands ?? []);
4167
4228
  const preferredOrder = unique(
@@ -4342,7 +4403,7 @@ function buildRouteSummary({
4342
4403
  continuationState,
4343
4404
  autonomyLevel,
4344
4405
  continuousExecution,
4345
- ...(expectedSourceFiles.length > 0 ? { expectedSourceFiles } : {}),
4406
+ ...(expectedSourceFiles.length > 0 ? { expectedSourceFiles, expectedSourceProvenance } : {}),
4346
4407
  intentMode: routingContext.intentMode ?? null,
4347
4408
  handoffFile,
4348
4409
  delegateHint: delegationRecommendation?.hint ?? null,
@@ -6129,6 +6190,7 @@ export function compactRouteSummary(routeSummary = null) {
6129
6190
  // to legacy any-read behaviour.
6130
6191
  ...(Array.isArray(routeSummary.expectedSourceFiles) && routeSummary.expectedSourceFiles.length > 0 ? {
6131
6192
  expectedSourceFiles: routeSummary.expectedSourceFiles,
6193
+ ...(Array.isArray(routeSummary.expectedSourceProvenance) ? { expectedSourceProvenance: routeSummary.expectedSourceProvenance } : {}),
6132
6194
  } : {}),
6133
6195
  nextActionType: routeSummary.nextActionType ?? null,
6134
6196
  nextActionCommand: routeSummary.nextActionCommand ?? null,
@@ -6399,21 +6461,57 @@ export async function writeJsonAtomic(filePath, value) {
6399
6461
  // writer mid-flight. Fail-closed (CX-8): a busy lock skips the write — the next
6400
6462
  // route recomputes and overwrites the whole document anyway, so a skipped
6401
6463
  // 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.
6464
+ export async function persistSharedRouteState(filePath, state, { expectedRouteBytes } = {}) {
6409
6465
  const owner = normalizeSessionId(state?.sessionId);
6410
- if (owner) {
6411
- try {
6412
- const root = path.resolve(path.dirname(filePath), '..', '..');
6413
- const safe = owner.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
6414
- await writeJsonAtomic(path.join(root, '.ukit', 'storage', 'cache', 'route-state', `${safe}.json`), state);
6415
- } catch { /* shared write is authoritative */ }
6416
- }
6466
+ const root = path.resolve(path.dirname(filePath), '..', '..');
6467
+ const safe = owner?.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
6468
+ const sidecar = owner && path.join(root, '.ukit', 'storage', 'cache', 'route-state', `${safe}.json`);
6469
+ if (sidecar && expectedRouteBytes === undefined) return { ok: false, reason: 'missing-expected-version', waitedMs: 0 };
6470
+ const write = async () => {
6471
+ let current = null;
6472
+ if (sidecar) {
6473
+ try { current = await fs.readFile(sidecar, 'utf8'); }
6474
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
6475
+ if (current !== expectedRouteBytes) return { ok: false, reason: 'stale', waitedMs: 0 };
6476
+ }
6477
+ // This is a persistence revision, not handoff ownership or generation.
6478
+ // Stamp every publication so an A → B → A route cannot recreate its old bytes.
6479
+ const published = sidecar ? { ...state, routePersistenceRevision: crypto.randomUUID() } : state;
6480
+ if (sidecar) await writeJsonAtomic(sidecar, { sessionId: owner, taskInstanceId: state.taskInstanceId, routeGeneration: state.routeGeneration, routePersistenceRevision: published.routePersistenceRevision, routePublicationIncomplete: true });
6481
+ // The sidecar lock is held, so no other route writer can publish meanwhile. When the shared write
6482
+ // did not happen (lock busy/failed) and the shared slot is provably unchanged, restore the previous
6483
+ // committed sidecar instead of stranding a pending marker over a still-valid route.
6484
+ const readBytes = async (file) => { try { return await fs.readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
6485
+ const priorShared = sidecar ? await readBytes(filePath) : null;
6486
+ const rollback = async () => {
6487
+ if (!sidecar) return;
6488
+ try {
6489
+ if (await readBytes(filePath) !== priorShared) return;
6490
+ if (current === null) await fs.rm(sidecar, { force: true });
6491
+ else {
6492
+ // Byte-exact: other writers compare the sidecar by its exact bytes.
6493
+ const tempPath = `${sidecar}.tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
6494
+ try { await fs.writeFile(tempPath, current, 'utf8'); await fs.rename(tempPath, sidecar); }
6495
+ catch (error) { await fs.rm(tempPath, { force: true }).catch(() => {}); throw error; }
6496
+ }
6497
+ } catch { /* the pending marker stays: readers fail closed */ }
6498
+ };
6499
+ let result;
6500
+ try { result = await withAsyncLock(filePath, {}, () => writeJsonAtomic(filePath, published)); }
6501
+ catch (error) { await rollback(); throw error; }
6502
+ if (!result.ok) { await rollback(); return result; }
6503
+ if (sidecar) await writeJsonAtomic(sidecar, published);
6504
+ return result;
6505
+ };
6506
+ const locked = sidecar ? await withAsyncLock(sidecar, {}, write) : { ok: true, value: await write() };
6507
+ const result = locked.ok ? locked.value : locked;
6508
+ if (!result.ok) console.error(`route-task: route lock ${result.reason} after ${result.waitedMs}ms — state write skipped (fail-closed)`);
6509
+ return result;
6510
+ }
6511
+
6512
+ async function requirePersistedRouteState(filePath, state, options) {
6513
+ const result = await persistSharedRouteState(filePath, state, options);
6514
+ if (!result.ok) throw new Error(`route state not persisted: ${result.reason}`);
6417
6515
  return result;
6418
6516
  }
6419
6517
 
@@ -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 {
@@ -1489,7 +1489,14 @@ async function runCli() {
1489
1489
  })();
1490
1490
 
1491
1491
  if (mode === 'prompt') {
1492
- const routeState = await readJson(path.join(projectRoot, '.claude', 'ukit', 'skill-router-state.json'), {});
1492
+ let routeState = await readJson(path.join(projectRoot, '.claude', 'ukit', 'skill-router-state.json'), {});
1493
+ // Advisory reader: a pending or unconfirmed route publication is an interrupted write, not a route.
1494
+ if (routeState?.sessionId) {
1495
+ const owner = String(routeState.sessionId).trim().replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
1496
+ const committed = await readJson(path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-state', `${owner}.json`), {});
1497
+ if (routeState.routePublicationIncomplete || committed.routePublicationIncomplete
1498
+ || (routeState.routePersistenceRevision && committed.routePersistenceRevision !== routeState.routePersistenceRevision)) routeState = {};
1499
+ }
1493
1500
  const promptText = extractPrompt(payload);
1494
1501
  if (!promptText.trim()) {
1495
1502
  return;