@ngockhoale/ukit 3.4.74 → 3.4.76

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 (30) hide show
  1. package/CHANGELOG.md +110 -95
  2. package/manifests/platform.full.yaml +15 -0
  3. package/package.json +14 -4
  4. package/src/cli/commands/markerStore.js +15 -0
  5. package/src/cli/index.js +7 -0
  6. package/src/core/markerStoreMigration.js +122 -0
  7. package/template_project/.claude/hooks/completion-gate.sh +10 -1
  8. package/template_project/.claude/hooks/handoff-resume.sh +9 -0
  9. package/template_project/.claude/hooks/owner-stop-gate.mjs +41 -0
  10. package/template_project/.claude/hooks/skill-router.sh +262 -28
  11. package/template_project/.claude/settings.json +11 -1
  12. package/template_project/.claude/ukit/index/publication-intent.mjs +144 -18
  13. package/template_project/.claude/ukit/index/route-task.mjs +91 -9
  14. package/template_project/.claude/ukit/runtime/cron-operation-adapter.mjs +11 -4
  15. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +369 -29
  16. package/template_project/.claude/ukit/runtime/operation-evidence.mjs +9 -0
  17. package/template_project/.claude/ukit/runtime/resumable-run.mjs +33 -11
  18. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +161 -32
  19. package/template_project/.omp/hooks/pre/ukit-bridge.js +552 -4
  20. package/scripts/bug/triage.mjs +0 -76
  21. package/scripts/dev/worktree-preflight.mjs +0 -166
  22. package/scripts/docs/render-instructions.mjs +0 -66
  23. package/scripts/index/build-index.mjs +0 -102
  24. package/scripts/index/query-index.mjs +0 -128
  25. package/scripts/index/refresh-index.mjs +0 -195
  26. package/scripts/install/sync-installed-mirror.mjs +0 -263
  27. package/scripts/measure-decision-gateway.mjs +0 -306
  28. package/scripts/probe/codex-capability-probe.mjs +0 -169
  29. package/scripts/skill/audit-skill.mjs +0 -68
  30. package/scripts/test/run-handoff-isolated.mjs +0 -178
@@ -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=436a0d9c586c1da4d418cfa8bfd377fa45471885fc5ff0ed471b0f6a7b342088
204
+ // BEGIN GENERATED SEMANTIC ENGINE sha256=d125c6ef30c4bec1e3065148855cfd0b90c1af5acd90de2020de02607a4e0adf
205
205
  // Canonical task semantics; intent never grants authorization or proves completion.
206
- const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:287d478b06a81ac1f9fcc1c53fd00217ab13bf6af53aca3bd662df0989e30b5e';
206
+ const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:d54a8c14f321c1eeba4832e4461cd6d0c2231b2f7a80932ac3129f1e8dd792f9';
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 }) {
@@ -247,8 +247,8 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
247
247
  const text = foldIntent(raw);
248
248
  const quoted = Boolean(marker || fence || /^\s*>/.test(raw));
249
249
  const context = quoted ? 'quotation' : description && bullet ? 'description' : 'instruction';
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;
250
+ const polarity = /\b(?:do not|don't|never|must not|no|khong|chua|prohibited|forbidden|banned)\b/.test(text) || /đừng/i.test(raw) ? 'prohibited' : 'affirmative';
251
+ const condition = text.match(/\b(?:if|neu|sau khi|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,26 @@ 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
+ if (span.context === 'instruction' && span.polarity === 'affirmative' && span.condition
278
+ && /\b(?:phat hanh|xuat ban)\s+npm\b/.test(folded)
279
+ && /\b(?:neu|sau khi)\b/.test(span.condition) && !nativeReleasePolicy) deferredSpans.add(span);
280
+ const verb = folded.match(CONDITIONAL_RUNTIME_VERB);
281
+ const cond = span.condition ? folded.indexOf(span.condition) : -1;
282
+ if (!verb || cond < 0 || span.context !== 'instruction' || span.polarity !== 'affirmative' || nativeReleasePolicy
283
+ || CONDITIONAL_RUNTIME_EXCLUDED.test(folded)) return;
284
+ const governed = verb.index >= cond || /^(?:only\s+(?:if|when)|unless)\b/.test(span.condition);
285
+ if (!NEED_OR_FAILURE_CONDITION.test(span.condition)) return;
286
+ const leadsVerification = VERIFICATION_LEAD.test(folded.slice(0, cond)) && cond > 0
287
+ || spans.slice(0, index).some(prior => prior.context === 'instruction' && prior.polarity === 'affirmative'
288
+ && !prior.condition && VERIFICATION_LEAD.test(foldIntent(prior.raw)));
289
+ if (governed && leadsVerification) deferredSpans.add(span);
290
+ });
275
291
  // An explicit alternative links both consequences. Keep the unconditional
276
292
  // review prefix, but do not require a repair before its review has found one.
277
293
  const alternatives = spans.filter(span => span.condition?.startsWith('otherwise:'));
@@ -289,8 +305,12 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
289
305
  if (span.context === 'quotation' || span.context === 'description' || approvalPending || deferredSpans.has(span) || evidenceStatement) {
290
306
  // Retain the prefix before a comma-introduced postfix repair condition.
291
307
  // Leading conditions and otherwise consequences are masked in full.
292
- const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|otherwise)\b/.test(foldIntent(span.raw))
293
- ? span.raw.match(/^[^,]*,/)?.[0] || '' : '';
308
+ const folded = foldIntent(span.raw);
309
+ const coordinatedRelease = folded.match(/\b(?:va|roi)\s+(?:phat hanh|xuat ban)\s+npm\b/);
310
+ const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|only after|only once|otherwise)\b/.test(folded)
311
+ ? coordinatedRelease && /\b(?:neu|sau khi)\b/.test(span.condition || '')
312
+ ? span.raw.slice(0, coordinatedRelease.index)
313
+ : span.raw.match(/^[^,]*,/)?.[0] || '' : '';
294
314
  const masked = prefix + span.raw.slice(prefix.length).replace(/[^\r\n]/g, ' ');
295
315
  semanticInput = semanticInput.slice(0, span.start) + masked + semanticInput.slice(span.end);
296
316
  }
@@ -330,8 +350,14 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
330
350
  }
331
351
  return { engineVersion: SEMANTIC_ENGINE_VERSION, identity: { taskInstanceId, sessionId }, original, spans, actions, semantic };
332
352
  }
353
+ 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/;
354
+ const CONDITIONAL_RUNTIME_VERB = /\b(?:redeploy|deploy|restart|khoi dong lai|trien khai)\b/;
355
+ const CONDITIONAL_RUNTIME_EXCLUDED = /\b(?:publish|phat hanh|commit|push|tag|git|implement|fix|edit|modify|sua)\b/;
356
+ const VERIFICATION_LEAD = /^[-*+\u2022>\d.)\s]*(?:(?:please|hay|vui long|now|also|first)\s+)*(?:verify|check|confirm|validate|inspect|kiem tra|xac nhan)\b/;
357
+ 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';
358
+ const PAST_RELEASE_ITEM = new RegExp(`^(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}`);
333
359
  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/;
334
- 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/;
360
+ const PUBLISH_ORDER_IMPERATIVE = /^(?:please\s+|just\s+|now\s+|also\s+)*(?:run|do|execute|perform|thuc hien|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/;
335
361
  const PUBLISH_ORDER_HEADER = /prohibit|forbidden|out of scope|non-goal|scope control/;
336
362
  function defectRepairBranches(text) {
337
363
  return [...text.matchAll(/(?:^|\n|\.\s+)[ \t]*(?:[-*]|\d+[.)])?\s*((?:neu\s+(?:gap|phat hien|tim thay|co)|if\b)[^.!?]*(?:\.(?!\w)|$))/g)]
@@ -451,10 +477,11 @@ function ordersPublicationText(promptText = '') {
451
477
  if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
452
478
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
453
479
  const commandItem = item.replace(/^(?:please|just|now|also|then)\s+/, '');
454
- 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);
455
- 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);
480
+ const publication = /\bnpm\s+publish\b/.test(commandItem) && /^(?:npm\s+publish|run|do|execute|perform|thuc hien|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/.test(commandItem);
481
+ 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);
456
482
  const politeItem = item.replace(/^(?:(?:please|just|now|also|then|vui long|hay)\s+)+/, '');
457
- 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);
483
+ const viPublish = /^(?:(?:su dung(?: lenh)?|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)
484
+ || /^(?:(?:sua|kiem thu|hoan tat)\b[^.;\n]*\b(?:va|roi)\s+|(?:va|roi)\s+)(?:phat hanh|xuat ban)\s+npm\b/.test(politeItem);
458
485
  if (!negated && (releaseOrder || viPublish || (publication && (
459
486
  (/^npm\s+publish\b/.test(politeItem) && (/^(?:[\s*•-]|\d+[.)])*(?:(?:please|just|now|also)\s+)*(?:npm\s+publish|run|execute|perform|commit|push|tag)\b/.test(hard.trim()) || /\bcontinue the release workflow:/.test(hard))) || PUBLISH_ORDER_IMPERATIVE.test(item)
460
487
  || /\b(?:chay|run)\s+`?npm\s+publish\b/.test(item)
@@ -466,7 +493,7 @@ function ordersPublicationText(promptText = '') {
466
493
  return ordered;
467
494
  }
468
495
 
469
- const NOT_A_SERVICE = new Set(['it', 'this', 'that', 'them', 'the', 'all', 'everything', 'service', 'services', 'again', 'now', 'to', 'and', 'then']);
496
+ 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']);
470
497
  function nativeOperationGoal(domain, actionable, text) {
471
498
  const goal = { domain, target: null, desiredState: 'verified', completionSemantics: 'execute-and-verify', requiredTargets: [] };
472
499
  const clauses = actionable.join(' . ');
@@ -518,16 +545,24 @@ function neutralizeNonOrders(text) {
518
545
  return source.replace(noVerbList(), ' ')
519
546
  .replace(/\brelease-(?:publication|verification)\b|\brelease\s+(?:instructions?|authorization|obligations?|policies|readiness)\b/g, 'publication topic')
520
547
  .replace(/\brelease\s+(?:safety|verification\s+plan)\b/g, 'publication topic')
548
+ .replace(new RegExp(`(^|[\\n.;]\\s*)(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}[^.;\\n]*`, 'g'), '$1publication topic')
521
549
  .replace(/^[ \t]*[-*+•][ \t]*owner\s+yeu\s+cau\b[^\n]*/gm, ' ')
522
550
  .replace(/^([ \t]*[-*+•][ \t]*)release\s+progress\s+reporter(?=[ \t]*(?:,|$))/gm, '$1progress reporter')
523
551
  .replace(/^[ \t]*(?:[-*+\u2022]|\d+[.)])[ \t]*(?:negative|positive)\s+controls?\b[^\n]*(?:\n(?![ \t]*(?:[-*+\u2022]|\d+[.)])|[ \t]*\n)[^\n]*)*/gm, ' ')
524
552
  .replace(/(?:^|(?<=[.;][ \t]))[^.;\n]*\b(?:khong\s+(?:cho\s+phep|duoc|lam)|(?:does|do|did|is|are)\s+not\s+(?:allow|permit|authori[sz]e)\w*|not\s+(?:allowed|permitted|authori[sz]ed)|prohibitions?|prohibited(?:\s+actions?)?|forbidden(?:\s+actions?)?|banned|must\s+not\s+do)\s*:[ \t]*(?:\n[ \t]*(?:[-*+\u2022]|\d+[.)])[^\n]*)+/gm, ' ')
525
553
  .replace(new RegExp(`\\b(?:do\\s+not|don't|dont|must\\s+not|never|shall\\s+not)\\s+[^.;\\n]*?(?=\\s+(?:and|va)\\s+(?:${NON_ORDER_VERBS})\\b|\\s+(?:but|nhung|then|however)\\b|[.;\\n]|$)`, 'g'), ' ')
554
+ // Negated sufficiency ("git commit/tag/release chua du de ban giao", "a git commit is not enough /
555
+ // insufficient"): the negation sits AFTER the operation enumeration, so the khong/chua span strip
556
+ // below would remove only the predicate tail and leave the bare "git commit/tag/release" fragment
557
+ // standing as a phantom imperative. Consume the enumeration together with its negated predicate.
558
+ .replace(new RegExp(`\\b(?:(?:git|npm)\\s+)?(?:commit|push|tag|release|deploy(?:ment)?|redeploy|restart|publish|phat\\s+hanh|trien\\s+khai)(?:\\s*/\\s*(?:commit|push|tag|release|deploy(?:ment)?|redeploy|restart|publish|phat\\s+hanh|trien\\s+khai))*\\s+(?:(?:(?:is|are|was|were)\\s+)?(?:not\\s+(?:enough|sufficient)|insufficient)\\b|(?:(?:tuyet\\s+doi\\s+)?khong|chua)\\b)[^.;\\n]*`, 'g'), ' ')
526
559
  .replace(new RegExp(`\\b(?:(?:tuyet\\s+doi\\s+)?khong|chua)\\s+[^.;\\n]*?(?=\\s+(?:nhung|tuy nhien)\\b|[.;\\n]|$)`, 'g'), ' ')
527
560
  .replace(/"[^"\n]*\s[^"\n]*"|`[^`\n]*\s[^`\n]*`|\u201c[^\u201d\n]*\u201d/g, ' ')
528
561
  .replace(/\b(?:uu tien|prefer(?:red)?)\s+(?:a\s+|an\s+)?(?:configuration|config|cau hinh)\s+(?:change|changes|update|thay doi)\b/g, ' ')
529
562
  .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, ' ')
530
563
  .replace(/[^.;\n]*\b(?:nao|gi|sao|the nao|bao nhieu)\b[^.;\n]*\?/g, ' ')
564
+ .replace(/\b(?:truoc khi|before)\s+(?:quay lai|tro lai|returning|going back|you (?:go|return)|we (?:go|return))\b[^.;\n]*/g, ' ')
565
+ .replace(/\b(?:cua|do|tu)\s+chinh\b|\bchinh\s+(?:cac|nhung|phien|no|minh|toi|ban than)\b/g, ' ')
531
566
  .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, ' ')
532
567
  .replace(/\bwrite\s*\/\s*verification\b|\bverification\s*\/\s*write\b|\bwrite\s+(?:or|and)\s+verification\b/g, ' ')
533
568
  .replace(/\bwrite\s+permission\b/g, 'permission')
@@ -545,7 +580,7 @@ function neutralizeNonOrders(text) {
545
580
  });
546
581
  }
547
582
 
548
- const READ_ONLY_DECLARATION = /\breviewer\s*[,—:-]?\s+read[\s_-]*only\b|\bread[\s_-]*only(?:\s+\w+){0,3}?\s+(?:audit|investigation|review|analysis|inspection|inventory|task|request|session|pass|check|diagnos\w+|verification|forensics?|reports?)\b|(?:^|\n)[\s*#>_-]*read[\s_-]*only\s*[.:!—-]|\b(?:audit|investigation|review|analysis|inventory)[\s-]*only\b|[(,]\s*read[\s_-]*only\s*[).]|\bchi\s+(?:doc|audit|kiem tra|kiem ke|phan tich|dieu tra)\b|\bkhong\s+sua\b|\b(?:make|with)\s+no\s+(?:source\s+|code\s+|file\s+)?(?:changes|edits|modifications)\b|\b(?:do\s+not|don't|dont|never)\s+(?:\w+\s+){0,2}edits?\b/;
583
+ const READ_ONLY_DECLARATION = /\breviewer\s*[,—:-]?\s+read[\s_-]*only\b|\bread[\s_-]*only(?:\s+\w+){0,3}?\s+(?:audit|investigation|review|analysis|inspection|inventory|task|request|session|pass|check|diagnos\w+|verification|forensics?|reports?)\b|(?:^|\n)[\s*#>_-]*read[\s_-]*only\s*[.:!—-]|\b(?:audit|investigation|review|analysis|inventory)[\s-]*only\b|[(,]\s*read[\s_-]*only\s*[).]|\bchi\s+(?:doc|audit|kiem tra|kiem ke|phan tich|dieu tra)\b|\bkhong\s+sua\b(?=\s*(?:$|[.,;:!?)\n])|\s+(?:code|file|files|source|repo|repository|gi|bat|moi|them|lai|nua|du\s+an|tai\s+lieu|test|tests|mot|nao|ca|ledger|gate|receipts?|worklog)\b)|\b(?:make|with)\s+no\s+(?:source\s+|code\s+|file\s+)?(?:changes|edits|modifications)\b|\b(?:do\s+not|don't|dont|never)\s+(?:\w+\s+){0,2}edits?\b/;
549
584
  const ORDER_VERBS = 'implement|fix|apply|refactor|modify|edit|write|update|add|create|build|install|deploy|redeploy|restart|push|commit|rename|remove|delete|replace|change|sua|viet|chinh|them|bo sung|tao|xoa|enable|disable|set|toggle|configure|migrate|upgrade|publish|release|trien khai|khoi dong lai|(?:run|execute)\\s+(?:git\\s+(?:push|clean|commit|reset|rebase|merge|tag|stash|checkout|restore|cherry-pick)|(?:npm|yarn)\\s+publish)|git\\s+(?:push|clean|commit|reset|rebase|merge|tag|stash|checkout|restore|cherry-pick)';
550
585
  const IMPERATIVE_ORDER = new RegExp(`^(?:[-*+\\u2022>\\d.)\\s]*)(?:(?:please|hay|vui long|now|also|first|then)\\s+)*(?:${ORDER_VERBS})\\b\\s+\\S`);
551
586
  const MODAL_ORDER = new RegExp(`\\b(?:please|hay|vui long|need to|needs to|must|should|want(?:\\s+you)? to|toi muon|can phai|yeu cau)\\s+(?:[\\w-]+\\s+){0,2}(?:${ORDER_VERBS})\\b`);
@@ -575,6 +610,13 @@ function declaredReadOnly(promptText, releasePolicy) {
575
610
 
576
611
  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/;
577
612
  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/;
613
+ 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;
614
+ 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/;
615
+ const bansTestRuns = (promptText) => {
616
+ const plain = String(promptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
617
+ const bans = plain.match(BANS_TEST_RUNS);
618
+ return !!bans && !bans.some((ban) => /\bon\s+\w+$/.test(ban)) && !OWN_TARGET.test(plain.replace(BANS_TEST_RUNS, ' '));
619
+ };
578
620
  function isVerificationOnlyRequest(promptText) {
579
621
  const plain = String(promptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase()
580
622
  .replace(/```[\s\S]*?```/g, ' ').replace(/^[ \t]*>.*$/gm, ' ');
@@ -598,6 +640,27 @@ function neutralizeBannedLists(text) {
598
640
  });
599
641
  }
600
642
 
643
+ const OWNER_CONTROL_HOOK_TEXT = /^\s*(?:UKit completion gate:|UKit handoff|\[ukit[-\w]*\]|<system-reminder|<task-notification)/i;
644
+ 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))*$/;
645
+ 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))*$/;
646
+ 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.-]+/;
647
+ 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/;
648
+ function classifyOwnerControl(promptText = '') {
649
+ const raw = String(promptText ?? '').normalize('NFC').trim();
650
+ if (!raw || OWNER_CONTROL_HOOK_TEXT.test(raw)) return { kind: null };
651
+ const stripped = raw.replace(/^[\s*#_-]+/, '');
652
+ if (/^[>"'`\u201c\u2018]/.test(stripped)) return { kind: null };
653
+ const sentences = stripped.split(/[.!?\n]/);
654
+ const [lead, ...rest] = sentences[0].split(/[:;]/);
655
+ const first = lead.trim().toLowerCase().replace(/\s+/g, ' ');
656
+ if (!first || first.length > 80) return { kind: null };
657
+ if (OWNER_CONTROL_TASK_WORD.test(rest.join(' ').toLowerCase())) return { kind: null };
658
+ if (!OWNER_STOP_EN.test(first) && !OWNER_STOP_VI.test(first)) return { kind: null };
659
+ const next = (sentences.slice(1).find((part) => part.trim()) || '').trim().toLowerCase();
660
+ if (OWNER_CONTROL_TASK_LEAD.test(next)) return { kind: null };
661
+ return { kind: 'stop' };
662
+ }
663
+
601
664
  function classifyTaskSemantics(input = {}) {
602
665
  return analyzeTaskIntent(input).semantic;
603
666
  }
@@ -612,7 +675,7 @@ const collapseInspectionSentences = (text) => text.replace(INSPECTION_SENTENCE,
612
675
 
613
676
  function actionableClauses(promptText) {
614
677
  const text = neutralizeBannedLists(neutralizeNonOrders(collapseInspectionSentences(String(promptText).normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[đĐ]/g, 'd').toLowerCase())));
615
- const clauses = text.split(/\s*(?:[;\n,]|\.(?:\s+|$)|\band\b|\bthen\b|\bva\b)\s*/);
678
+ 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*/);
616
679
  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)
617
680
  && !/^[\s*+•>\d.)-]*(?:(?:please|just|hay|vui long|now|also)\s+)*(?:audit|inspect|review|analyze|analyse|explain|read|kiem tra|phan tich)\b/.test(clause)
618
681
  // A fragment led by a subordinator continues the previous clause's predicate ("…, including source
@@ -627,7 +690,69 @@ function ordersAdditiveChange(promptText = '') {
627
690
  return actionableClauses(publicationScope(promptText).text).actionable.some((clause) => ADDITIVE_ORDER_LEAD.test(clause));
628
691
  }
629
692
 
630
- function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
693
+ const STATE_OBJECT = /\b(?:shells?|jobs?|process(?:es)?|pids?|agents?|subagents?|wakeups?|tien trinh|tac vu nen|background (?:tasks?|work)|crons?)\b/;
694
+ 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/;
695
+ const STATE_ACTION = /\b(?:stop|cancel|kill|terminate|revoke|reclaim|dung|huy|thu hoi|ket thuc)\b/;
696
+ function statePlain(promptText) {
697
+ return String(promptText).normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[\u0111\u0110]/g, 'd').toLowerCase()
698
+ .replace(/```[\s\S]*?```/g, ' ').replace(/^[ \t]*>.*$/gm, ' ');
699
+ }
700
+ function isStateOperationRequest(promptText = '') {
701
+ const plain = statePlain(promptText);
702
+ 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;
703
+ return plain.split(/[;!?\n]+|[.:](?=\s|$)/).some((clause) => {
704
+ const lead = clause.match(STATE_LEAD);
705
+ if (!lead) return false;
706
+ // A clause whose verb is negated ("khong tu kill process", "do not stop the job") states a boundary, not an
707
+ // order to inspect or stop state. Only a negator BEFORE the verb counts: "stop X; do not ..." stays an order.
708
+ if (/\b(?:khong|do not|don't|never|not)\b/.test(clause.slice(0, lead.index))) return false;
709
+ const after = clause.slice(lead.index + lead[0].length);
710
+ const near = after.match(/^(?:\s+[\p{L}\p{N}_-]+){0,5}?\s+/u);
711
+ const window = after.split(/\s+/).slice(0, 7).join(' ');
712
+ return near !== null && STATE_OBJECT.test(window);
713
+ });
714
+ }
715
+
716
+ function stateOperationShape(promptText = '') {
717
+ const plain = statePlain(promptText);
718
+ const unquoted = plain.replace(/`[^`\n]*`|"[^"\n]*"|\u201c[^\u201d\n]*\u201d/g, ' ');
719
+ 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);
720
+ let conditional = false;
721
+ let gated = false;
722
+ const action = plain.split(/[;!?\n]+|[.:](?=\s|$)|,\s*/).some((raw) => {
723
+ const clause = raw.replace(/^[\s*\-\d.)]+/, '').trim();
724
+ if (!clause) return false;
725
+ const conditionLead = /^(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause);
726
+ if (!conditionLead && /\b(?:khong|do not|don't|never|not)\b/.test(clause)) return false;
727
+ 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; }
728
+ const head = clause.split(/\s+/).slice(0, 3).join(' ');
729
+ if (/\b(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause)) {
730
+ const leadsWithCondition = /^(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause);
731
+ const preCondition = leadsWithCondition ? '' : clause.split(/\b(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/)[0].trim();
732
+ 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; }
733
+ const consequent = leadsWithCondition ? (/\s(?:then|thi)\s/.test(clause) ? clause.split(/\s(?:then|thi)\s/).pop() : '') : clause;
734
+ if (STATE_ACTION.test(consequent.split(/\s+/).slice(0, 3).join(' '))) { conditional = true; return false; }
735
+ gated = leadsWithCondition && !STATE_ACTION.test(consequent);
736
+ return false;
737
+ }
738
+ const wasGated = gated;
739
+ gated = false;
740
+ const stops = (wasGated ? STATE_ACTION.test(clause) : STATE_ACTION.test(head)) && (wasGated || STATE_OBJECT.test(clause));
741
+ if (stops && wasGated) { conditional = true; return false; }
742
+ return stops;
743
+ });
744
+ return { action, conditional: conditional && !action, targets };
745
+ }
746
+
747
+ function classifySemanticText(input = {}) {
748
+ const semantic = classifySemanticCore(input);
749
+ if (semantic.taskKind !== 'READ_ONLY' || semantic.conditionalObligations || semantic.publication || !isStateOperationRequest(input.promptText)) return semantic;
750
+ const { verificationOnly: _verification, statusReport: _status, ...rest } = semantic;
751
+ const shape = stateOperationShape(input.promptText);
752
+ return { ...rest, stateVerification: true, ...(shape.action ? { stateAction: true } : shape.conditional ? { stateConditionalStop: true } : {}), ...(shape.targets.length ? { stateTargets: shape.targets } : {}) };
753
+ }
754
+
755
+ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
631
756
  promptText = publicationScope(promptText).text;
632
757
  const releaseText = String(promptText).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
633
758
  const preflight = releaseText.match(/\b(?:yarn\s+release:verify|npm\s+run\s+release:verify)\b/)?.[0];
@@ -638,13 +763,13 @@ function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
638
763
  if (ordersPublicationText(promptText)) {
639
764
  const implementation = hasExplicitOrder(clauses.filter((clause) => !/\b(?:release|publish)\b/.test(clause)));
640
765
  const remaining = clauses.filter((clause) => !ordersPublicationText(clause) && !/\b(?:release|publish)\b/.test(clause)).join('; ');
641
- const base = remaining.trim() ? classifySemanticText({ promptText: remaining, targetFile }) : {};
766
+ const base = remaining.trim() ? classifySemanticCore({ promptText: remaining, targetFile }) : {};
642
767
  delete base.verificationOnly;
643
768
  delete base.statusReport;
644
769
  return { ...base, taskKind: implementation ? 'MIXED' : 'OPERATIONAL', publication: true, ...(releasePolicy ? { releasePolicy } : {}) };
645
770
  }
646
771
  if (!/[a-z0-9]/.test(text)) return { taskKind: 'READ_ONLY' };
647
- if (declaredReadOnly(promptText, releasePolicy)) return { taskKind: 'READ_ONLY', ...(isVerificationOnlyRequest(promptText) ? { verificationOnly: true } : {}) };
772
+ if (declaredReadOnly(promptText, releasePolicy)) return { taskKind: 'READ_ONLY', ...(isVerificationOnlyRequest(promptText) && !bansTestRuns(promptText) ? { verificationOnly: true } : {}) };
648
773
  const sourceOrder = actionable.some((clause) => /\b(?:implement|fix(?:es)?|apply|refactor|modify|edit|write|update|sua|viet|chinh)\b/.test(clause)
649
774
  && /\b(?:source|code|logic|scheduler|implementation|ma nguon)\b|\.[cm]?[jt]sx?\b/.test(clause));
650
775
  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));
@@ -683,7 +808,7 @@ function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
683
808
  && !/\.[cm]?[jt]sx?\b/.test(clause) && !/\bgit\b/.test(clause));
684
809
  const nativeDomain = cronOperation ? 'scheduled-job' : gitOperation !== runtimeOperation ? (gitOperation ? 'git-integrity' : 'service-runtime') : null;
685
810
  const operation = Boolean(nativeDomain);
686
- if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', verificationOnly: true };
811
+ if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', ...(bansTestRuns(promptText) ? {} : { verificationOnly: true }) };
687
812
  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/;
688
813
  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/;
689
814
  const CONFIG_NOUN = /\b(?:configuration|config|toggle|cau hinh)\b/;
@@ -736,6 +861,7 @@ function applyTaskSemantics(contract, semantic) {
736
861
  return { ...(contract || {}), ...semantic,
737
862
  completionEvidence: semantic.taskKind === 'DOCUMENTATION_OUTPUT' ? ['report-artifact'] : operationOnly ? ['operation-verification']
738
863
  : semantic.taskKind === 'MIXED' ? [...new Set([...evidence, 'write-evidence', 'operation-verification'])]
864
+ : semantic.taskKind === 'READ_ONLY' && semantic.stateVerification ? ['state-verification']
739
865
  : semantic.taskKind === 'READ_ONLY' && semantic.statusReport ? []
740
866
  : semantic.taskKind === 'READ_ONLY' ? (semantic.verificationOnly ? ['verification-evidence'] : ['impact-evidence'])
741
867
  // A routed contract owns the debt; an unrouted (informational/null) turn carries none, because
@@ -959,6 +1085,9 @@ function applyTaskSemantics(contract, semantic) {
959
1085
  return tierLaneModule;
960
1086
  }
961
1087
  function writeTierLaneLines(summary, taskId) {
1088
+ if (summary?.playbookId === 'bug-fix') {
1089
+ 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');
1090
+ }
962
1091
  const lane = summary?.tierLane;
963
1092
  if (!lane?.instruction) {
964
1093
  return;
@@ -4094,6 +4223,7 @@ function applyTaskSemantics(contract, semantic) {
4094
4223
  const compactState = { ...sharedState };
4095
4224
  delete compactState.source;
4096
4225
  delete compactState.ts;
4226
+ delete compactState.ownerControl; // STOP is per-session state, never a cached route fact
4097
4227
  return compactState;
4098
4228
  }
4099
4229
 
@@ -4186,6 +4316,9 @@ function applyTaskSemantics(contract, semantic) {
4186
4316
  persisted.routingContext.mutationOrder = previous.routingContext.mutationOrder;
4187
4317
  }
4188
4318
  }
4319
+ // The STOP marker lives until the next genuine owner prompt re-routes (no TTL).
4320
+ if (ownerControlTurn) persisted.ownerControl = { kind: 'stop', sessionId, ts: Date.now() };
4321
+ else if (previous.ownerControl?.kind === 'stop' && (payload.tool_name || systemOriginTurn || !extractPrompt(payload).trim())) persisted.ownerControl = previous.ownerControl;
4189
4322
  if (continuingTask && !persisted.suspendedContract && previous.suspendedContract) {
4190
4323
  persisted.suspendedContract = previous.suspendedContract;
4191
4324
  }
@@ -4195,7 +4328,7 @@ function applyTaskSemantics(contract, semantic) {
4195
4328
  persisted.routeSummary ||= {};
4196
4329
  persisted.routeSummary.executionContract = previous.routeSummary.executionContract;
4197
4330
  persisted.contractOrigin = 'carried-system';
4198
- for (const key of ['expectedSourceFiles', 'completionState', 'continuationState', 'executionMode']) {
4331
+ for (const key of ['expectedSourceFiles', 'expectedSourceProvenance', 'completionState', 'continuationState', 'executionMode']) {
4199
4332
  if (previous.routeSummary[key] !== undefined) persisted.routeSummary[key] = previous.routeSummary[key];
4200
4333
  else delete persisted.routeSummary[key];
4201
4334
  }
@@ -4319,7 +4452,7 @@ function applyTaskSemantics(contract, semantic) {
4319
4452
  persisted.requestKey = previous.requestKey;
4320
4453
  persisted.routingContext = { ...previous.routingContext };
4321
4454
  persisted.routeSummary ||= {};
4322
- for (const key of ['executionContract', 'expectedSourceFiles', 'completionState', 'continuationState', 'executionMode']) {
4455
+ for (const key of ['executionContract', 'expectedSourceFiles', 'expectedSourceProvenance', 'completionState', 'continuationState', 'executionMode']) {
4323
4456
  if (previous.routeSummary[key] !== undefined) persisted.routeSummary[key] = previous.routeSummary[key];
4324
4457
  else delete persisted.routeSummary[key];
4325
4458
  }
@@ -4353,7 +4486,16 @@ function applyTaskSemantics(contract, semantic) {
4353
4486
  const readOrNull = async (file) => { try { return await fsp.readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
4354
4487
  const priorSidecar = sessionId ? await readOrNull(sessionRoutePath) : null;
4355
4488
  const priorShared = sessionId ? await readOrNull(statePath) : null;
4356
- if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true }));
4489
+ // The pending marker is the only session record while the publication is in flight: it carries the owner STOP
4490
+ // (from this publication, else the committed sidecar it replaces) so an interrupted publication cannot lift it.
4491
+ const committedStop = (() => {
4492
+ try {
4493
+ const committed = priorSidecar === null ? null : JSON.parse(priorSidecar);
4494
+ return committed?.ownerControl?.kind === 'stop' && committed.sessionId === sessionId ? committed.ownerControl : null;
4495
+ } catch { return null; }
4496
+ })();
4497
+ const markerControl = persisted.ownerControl ?? committedStop;
4498
+ if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true, ...(markerControl ? { ownerControl: markerControl } : {}) }));
4357
4499
  try {
4358
4500
  await writeJsonFileAtomic(statePath, text);
4359
4501
  } catch (error) {
@@ -4451,9 +4593,13 @@ function applyTaskSemantics(contract, semantic) {
4451
4593
  } catch { boundGateContinuation = false; }
4452
4594
  }
4453
4595
  }
4596
+ const ownerControlTurn = Boolean(sessionId && promptOrigin !== 'system' && !boundGateContinuation && !payload.tool_name
4597
+ && (classifyOwnerControl(extractPrompt(payload)).kind === 'stop'
4598
+ || (payload.ukit_harness === 'omp' && payload.ukit_owner_input === 'contains-stop')));
4454
4599
  const systemOriginTurn = (() => {
4455
4600
  const promptTrim = extractPrompt(payload).trim();
4456
4601
  if (!promptTrim) return false;
4602
+ if (ownerControlTurn && previous.taskInstanceId) return true;
4457
4603
  if (/^This session is being continued from a previous conversation/i.test(promptTrim)) return true;
4458
4604
  // Bridge-owned metadata only (ukit-bridge.js maps the host's session-stop-continuation
4459
4605
  // attribution); an arbitrary prompt prefix proves nothing and is never trusted here.
@@ -4469,18 +4615,38 @@ function applyTaskSemantics(contract, semantic) {
4469
4615
  const buf = Buffer.alloc(len);
4470
4616
  fs.readSync(fd, buf, 0, len, size - len);
4471
4617
  const lines = buf.toString('utf8').split('\n');
4618
+ // Host-authored proof of a PEER delivery: a queued_command attachment whose origin the host
4619
+ // stamped as 'peer', bound to this session and to the exact prompt text. The envelope text
4620
+ // alone is never proof (a human can paste it); only the host's attachment counts.
4621
+ const peerDeliveryIds = new Set();
4622
+ for (const l of lines) {
4623
+ if (!l || !l.includes('queued_command')) continue;
4624
+ let a; try { a = JSON.parse(l); } catch { continue; }
4625
+ const at = a?.attachment;
4626
+ if (a.type === 'attachment' && at?.type === 'queued_command' && at.origin?.kind === 'peer'
4627
+ && typeof at.delivery_id === 'string' && sessionId && a.sessionId === sessionId
4628
+ && typeof at.prompt === 'string' && at.prompt.trim() === promptTrim) {
4629
+ peerDeliveryIds.add(at.delivery_id);
4630
+ }
4631
+ }
4632
+ let deliveryCurrent = true;
4472
4633
  for (let i = lines.length - 1; i >= 0; i -= 1) {
4473
4634
  const line = lines[i];
4474
4635
  if (!line) continue;
4475
4636
  let entry; try { entry = JSON.parse(line); } catch { continue; }
4476
- // Cross-session delivery is queued, not a user order. Require the host's
4477
- // consumed delivery record, exact content and this session's owner. An
4478
- // enqueue, a foreign delivery or a human-pasted envelope is not proof.
4479
- if (entry.type === 'queue-operation' && entry.operation === 'remove'
4637
+ // A response after a queued delivery means that delivery belongs to an earlier turn;
4638
+ // never let its text exempt a later owner prompt. Host hook metadata may follow the
4639
+ // delivery before this hook runs, but an assistant message is a turn boundary.
4640
+ if (entry.type === 'assistant' && entry.isSidechain !== true) deliveryCurrent = false;
4641
+ // Queued deliveries are not user orders. Require the host's consumed delivery record, exact
4642
+ // content and this session's owner. An enqueue, a foreign delivery or a human-pasted envelope
4643
+ // is not proof. A peer agent-message counts only with the host's peer attachment for that delivery.
4644
+ if (deliveryCurrent && entry.type === 'queue-operation' && entry.operation === 'remove'
4480
4645
  && entry.reason === 'absorbed_mid_turn' && entry.deliveryId
4481
4646
  && sessionId && entry.sessionId === sessionId
4482
4647
  && typeof entry.content === 'string' && entry.content.trim() === promptTrim
4483
- && /^<cross-session-message\s/.test(promptTrim)) {
4648
+ && (/^<cross-session-message\s/.test(promptTrim)
4649
+ || (/^<agent-message\s/.test(promptTrim) && peerDeliveryIds.has(entry.deliveryId)))) {
4484
4650
  coordinationTurn = true;
4485
4651
  return false;
4486
4652
  }
@@ -4626,6 +4792,34 @@ function applyTaskSemantics(contract, semantic) {
4626
4792
  if (GUIDANCE_MUTATION_VERB.test(guidanceResidue)) return false;
4627
4793
  if (GUIDANCE_LOOKUP_ORDER.test(guidanceResidue.replace(/\b(?:sau|after)\s+[a-z]+/g, (temporal, offset, text) => (GUIDANCE_TEMPORAL_ORDER_HEAD.test(text.slice(offset)) ? temporal : ' ')))) return false;
4628
4794
  }
4795
+ // Re-anchored linkage: "keep this work on the X" names X as the NOTE's topic. X binds only
4796
+ // when EVERY content word of X matches the task's own explicit prompt. Scope reading is
4797
+ // deterministic, not semantic: the phrase may contain slashes, ampersands, dotted FILE
4798
+ // names (punctuation followed by an alphanumeric stays inside the scope, so
4799
+ // "package.json" is one name, never truncated to "package") and quoted or parenthesized
4800
+ // parts (parentheticals are asides and are stripped); it ends at punctuation, a NEWLINE
4801
+ // or end of text. Words of 2-3 chars (API, CLI, MCP) count by EXACT equality; longer
4802
+ // words match only as prefix + bound morphology suffix ("deployment" ~ "deploy"), so a
4803
+ // prefix share alone never binds ("contractor" is not "contract", "production backlog"
4804
+ // is not "deploy to production"). Quantifier and temporal fragments (only/just/also/
4805
+ // for now/...) are never scope words. All this keeps the P0 isolation: receipt or
4806
+ // backlog reading never inherits a deploy order.
4807
+ const reanchoredScope = folded.match(/\b(?:this|current)\s+(?:work|task|change|one)\s+(?:on|for|about|regarding|within|inside)\s+(?:the\s+|this\s+|our\s+)?([a-z0-9][a-z0-9 .\/_()&'-]*?)(?=[!?:;,]|\.(?![a-z0-9])|\r|\n|$)/);
4808
+ if (reanchoredScope) {
4809
+ const priorPrompt = String(previous.routingContext?.lastExplicitUserPromptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase();
4810
+ if (priorPrompt) {
4811
+ const scopeWords = reanchoredScope[1].replace(/[()]/g, ' ').replace(/\.(?![a-z0-9])/g, ' ').split(/[^a-z0-9]+/).filter((w) => w.length >= 2
4812
+ && !['work', 'task', 'this', 'that', 'scope', 'current', 'focus', 'focused', 'change', 'note', 'plan', 'only', 'just', 'also', 'too', 'still', 'again', 'first', 'next', 'then', 'now', 'later', 'the', 'and', 'for', 'our', 'its', 'with', 'into', 'from', 'of', 'to', 'in', 'on', 'at', 'by', 'or'].includes(w));
4813
+ const priorWords = priorPrompt.split(/[^a-z0-9]+/).filter((w) => w.length >= 2);
4814
+ const wordMatches = (w) => priorWords.some((p) => {
4815
+ if (p === w) return true;
4816
+ if (w.length < 4 || p.length < 4) return false;
4817
+ const [short, long] = w.length <= p.length ? [w, p] : [p, w];
4818
+ return long.startsWith(short) && ['s', 'es', 'ed', 'ing', 'ment', 'ments', 'ion', 'ions', 'ly', 'er', 'ers', 'ation', 'ations'].includes(long.slice(short.length));
4819
+ });
4820
+ if (scopeWords.length > 0 && !scopeWords.every(wordMatches)) return false;
4821
+ }
4822
+ }
4629
4823
  if (!previous.taskInstanceId) return false;
4630
4824
  const contract = previous.routeSummary?.executionContract;
4631
4825
  if (!contract?.taskKind) return false;
@@ -4638,7 +4832,18 @@ function applyTaskSemantics(contract, semantic) {
4638
4832
  const handoffExpansion = payload.hook_event_name === 'UserPromptExpansion'
4639
4833
  && payload.expansion_type === 'slash_command'
4640
4834
  && /^(?:ukit:)?handoff-fullstack$/.test(String(payload.command_name || ''));
4641
- const continuingTask = Boolean(previous.taskInstanceId && (payload.tool_name || handoffExpansion || continuationPrompt || systemOriginTurn || guidanceTurn));
4835
+ const ownerResumeTurn = (() => {
4836
+ if (previous.ownerControl?.kind !== 'stop' || previous.ownerControl.sessionId !== sessionId || !sessionId || !previous.taskInstanceId
4837
+ || payload.tool_name || promptOrigin === 'system' || ownerControlTurn) return false;
4838
+ const fold = (text) => String(text ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/\u0111/gi, 'd').toLowerCase();
4839
+ const body = fold(extractPrompt(payload)).trim();
4840
+ if (!/^(?:continue|resume|keep going|proceed|tiep tuc|lam tiep)\s*[:,\u2013\u2014-]\s*\S/.test(body)) return false;
4841
+ const targets = (text) => new Set(fold(text).match(/[\w.-]+\/[\w./-]+|[\w-]+\.[a-z][a-z0-9]{0,7}\b/g) || []);
4842
+ const wanted = targets(body);
4843
+ const owned = targets(previous.routingContext?.lastExplicitUserPromptText);
4844
+ return wanted.size > 0 && [...wanted].every((target) => owned.has(target));
4845
+ })();
4846
+ const continuingTask = Boolean(previous.taskInstanceId && (payload.tool_name || handoffExpansion || continuationPrompt || ownerResumeTurn || systemOriginTurn || guidanceTurn));
4642
4847
  let taskInstanceId = continuingTask
4643
4848
  ? previous.taskInstanceId
4644
4849
  : `task-${crypto.randomBytes(16).toString("hex")}`;
@@ -4648,6 +4853,34 @@ function applyTaskSemantics(contract, semantic) {
4648
4853
  // not reroute or overwrite the current task as if they were user prompts.
4649
4854
  if (payload.tool_name === 'Skill' && !handoffSkill) process.exit(0);
4650
4855
  let handoffRunId = continuingTask ? previous.handoffRunId : null;
4856
+ const HOOK_SHAPED_PROMPT = /^\s*(?:UKit completion gate:|UKit handoff|\[ukit-[\w-]+\]|\[ukit\]\s)/;
4857
+ if (previous.ownerControl?.kind === 'stop' && !payload.tool_name && (!extractPrompt(payload).trim() || HOOK_SHAPED_PROMPT.test(extractPrompt(payload)))) process.exit(0);
4858
+ if (previous.ownerControl?.kind === 'stop' && !payload.tool_name && payload.ukit_harness === 'omp'
4859
+ && (payload.ukit_owner_input === 'before-stop' || payload.ukit_owner_input === 'unproven') && extractPrompt(payload).trim()) process.exit(0);
4860
+ if (!payload.tool_name && !systemOriginTurn) {
4861
+ const hookText = extractPrompt(payload);
4862
+ let inertHook = /^\s*\[ukit-[\w-]+\]/.test(hookText);
4863
+ if (!inertHook && /^UKit completion gate:/.test(hookText.trim())) {
4864
+ try {
4865
+ inertHook = (await import(pathToFileURL(path.join(projectRoot, '.claude', 'ukit', 'runtime', 'execution-ledger.mjs')).href)).isCompletionGateContinuationText(hookText);
4866
+ } catch { inertHook = true; }
4867
+ }
4868
+ if (inertHook) process.exit(0);
4869
+ }
4870
+ if (ownerControlTurn) {
4871
+ const priorPrompt = previous.routingContext?.lastExplicitUserPromptText || '';
4872
+ await ensureDir(statePath);
4873
+ await persistRouteState(JSON.stringify({
4874
+ ...(sessionId ? { sessionId } : {}),
4875
+ ts: Date.now(),
4876
+ source: 'skill-router-owner-control',
4877
+ activeSkills: [],
4878
+ routingContext: compactRoutingContext({ promptText: '', lastExplicitUserPromptText: priorPrompt, commandText: '', targetFile: '', contextIntent: '', taskType: '', mutationOrder: typeof previous.routingContext?.mutationOrder === 'boolean' ? previous.routingContext.mutationOrder : null, planOnly: null }),
4879
+ ...(previous.routeSummary ? { routeSummary: previous.routeSummary } : {}),
4880
+ ...(previous.requestKey ? { requestKey: previous.requestKey } : {}),
4881
+ }));
4882
+ process.exit(0);
4883
+ }
4651
4884
  const denyHandoff = (reason) => {
4652
4885
  const message = `UKit handoff resume BLOCKED: ${reason}; cursor untouched.`;
4653
4886
  process.stdout.write(JSON.stringify(handoffExpansion
@@ -5185,6 +5418,7 @@ function applyTaskSemantics(contract, semantic) {
5185
5418
  ts: now,
5186
5419
  requestKey,
5187
5420
  routeSummary: rescuedRouteSummary,
5421
+ ownerControl: undefined,
5188
5422
  };
5189
5423
  reusedState.fingerprint = buildRouteStateFingerprint(reusedState);
5190
5424
 
@@ -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": [
@@ -112,7 +122,7 @@
112
122
  ],
113
123
  "PostToolUse": [
114
124
  {
115
- "matcher": "CronDelete|CronList",
125
+ "matcher": "CronDelete|CronList|TaskStop|TaskOutput",
116
126
  "hooks": [
117
127
  {
118
128
  "type": "command",