@ngockhoale/ukit 3.5.6 → 3.5.8

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.
@@ -96,12 +96,31 @@ try {
96
96
  }
97
97
  return text;
98
98
  });
99
- const block = (name) => new RegExp(`^<${name}(?:\\s[^>]*)?>[\\s\\S]*<\\/${name}>$`, "i");
99
+ // A value is internal only when it is a SEQUENCE of closed blocks of one tag with nothing but
100
+ // whitespace between them. A greedy open...close match would swallow owner text sitting between two
101
+ // blocks (block, owner order, block) and silently drop that order.
102
+ const block = (name) => ({
103
+ test(value) {
104
+ const one = new RegExp(`^<${name}(?:\\s[^>]*)?>[\\s\\S]*?<\\/${name}>\\s*`);
105
+ let rest = String(value);
106
+ let n = 0;
107
+ for (let m = one.exec(rest); m; m = one.exec(rest)) { rest = rest.slice(m[0].length); n += 1; }
108
+ return n > 0 && rest === "";
109
+ },
110
+ });
100
111
  const internal = candidates.some((value) => (
101
112
  block("task-notification").test(value)
102
113
  || block("tool-result").test(value)
103
114
  || block("system-reminder").test(value)
104
- || /^<local-command-caveat(?:\s[^>]*)?>[\s\S]*<\/local-command-stdout>$/i.test(value)
115
+ || ((value) => {
116
+ // Host caveat echo: same shape as before (caveat open ... stdout close), but as a sequence of
117
+ // lazy units so owner text between two echoes is never swallowed.
118
+ const one = /^<local-command-caveat(?:\s[^>]*)?>[\s\S]*?<\/local-command-stdout>\s*/;
119
+ let rest = String(value);
120
+ let n = 0;
121
+ for (let m = one.exec(rest); m; m = one.exec(rest)) { rest = rest.slice(m[0].length); n += 1; }
122
+ return n > 0 && rest === "";
123
+ })(value)
105
124
  ));
106
125
  process.stdout.write(internal ? "1" : "0");
107
126
  } catch {
@@ -198,12 +217,26 @@ const { pathToFileURL } = require('url');
198
217
  const { spawn } = require('child_process');
199
218
 
200
219
  const HOOK_DEADLINE_MS = Number.parseInt(process.env.UKIT_HOOK_DEADLINE_MS || '', 10) || 3000;
201
- setTimeout(() => process.exit(0), HOOK_DEADLINE_MS).unref();
220
+ // A deadline kill is exit 0. When the kill lands inside the window where a fresh owner prompt has
221
+ // not yet published its route, the previous (armed) contract would stay live for the new prompt; the
222
+ // handler installed below writes a bounded pending marker first so readers fail closed instead.
223
+ // Every other kill exits at once. The second timer is armed first and guarantees exit even if that write
224
+ // hangs (worst case: deadline + 400 ms + the 300 ms bounded exit-fold spin; no sync fs is added here).
225
+ // LIMIT: a timer cannot fire during synchronous work, only at the next await after the deadline; a sync
226
+ // stretch that outlives the host's own hook budget is killed by the host with no marker (3.5.6 behaviour).
227
+ let deadlineReached = false;
228
+ let deadlineHandler = null;
229
+ setTimeout(() => {
230
+ deadlineReached = true;
231
+ if (!deadlineHandler) process.exit(0);
232
+ setTimeout(() => process.exit(0), 400).unref();
233
+ try { Promise.resolve(deadlineHandler()).then(() => process.exit(0), () => process.exit(0)); } catch { process.exit(0); }
234
+ }, HOOK_DEADLINE_MS).unref();
202
235
 
203
236
  (async () => {
204
- // BEGIN GENERATED SEMANTIC ENGINE sha256=db789c44db60937d51b7d9a4a9481264feb9f7152b88721bc973a16c4129f7fc
237
+ // BEGIN GENERATED SEMANTIC ENGINE sha256=c75ad63540825f83a0b87d35aa14cd05c536b950b6b97aef8f9a3fe3767f59cf
205
238
  // Canonical task semantics; intent never grants authorization or proves completion.
206
- const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:86afd8b71e068da6a63a85fcf003f79be262881f6c203fa44682853cf8acb4f7';
239
+ const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:02b15877348961e92a6d682beeb94b0dde7e116fb2b2ba9b5c419147772732f8';
207
240
 
208
241
  function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
209
242
  return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
@@ -226,7 +259,24 @@ function compareSemanticContracts({ stored, fresh, previousIdentity, identity })
226
259
  }
227
260
  const foldIntent = (text) => String(text).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
228
261
 
262
+ // The analysers are pure functions of their arguments but one hook run asks the same question about the same
263
+ // prompt dozens of times. Memoise per exact input (bounded, insertion-order eviction) and hand every caller its
264
+ // own structuredClone, so no caller can mutate the cache or another caller's result.
265
+ const SEMANTIC_MEMO_LIMIT = 16;
266
+ const memoCloned = (cache, key, compute) => {
267
+ const hit = cache.get(key);
268
+ if (hit !== undefined) return structuredClone(hit);
269
+ const value = compute();
270
+ if (cache.size >= SEMANTIC_MEMO_LIMIT) cache.delete(cache.keys().next().value);
271
+ cache.set(key, structuredClone(value));
272
+ return value;
273
+ };
274
+ const analyzeMemo = new Map();
229
275
  function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId = null, sessionId = null } = {}) {
276
+ return memoCloned(analyzeMemo, JSON.stringify([String(promptText), targetFile, taskInstanceId, sessionId]),
277
+ () => analyzeTaskIntentUncached({ promptText, targetFile, taskInstanceId, sessionId }));
278
+ }
279
+ function analyzeTaskIntentUncached({ promptText = '', targetFile = '', taskInstanceId = null, sessionId = null } = {}) {
230
280
  const original = String(promptText);
231
281
  const spans = [];
232
282
  let fence = null;
@@ -415,7 +465,11 @@ function classifyProhibitionItem(item, authorized, proper) {
415
465
  return null;
416
466
  }
417
467
 
468
+ const scopeMemo = new Map();
418
469
  function publicationScope(promptText = '') {
470
+ return memoCloned(scopeMemo, String(promptText), () => publicationScopeUncached(promptText));
471
+ }
472
+ function publicationScopeUncached(promptText = '') {
419
473
  const plain = String(promptText).normalize('NFC')
420
474
  .replace(/\bdùng\b/giu, 'su dung').replace(/đừng/giu, 'khong')
421
475
  .replace(/(^|[\n;.]\s*)([ \t]*(?:[-*+•]|\d+[.)])?[ \t]*)dung(?=\s+(?:publish|release|npm|git|run|fix|sua)\b)/gi, '$1$2khong')
@@ -736,8 +790,139 @@ const OWNER_STOP_EN = /^(?:please\s+)?(?:stop|halt|pause|cancel|abort)(?:\s+(?:a
736
790
  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))*$/;
737
791
  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.-]+/;
738
792
  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/;
793
+ // A STANDING POLICY states how the owner wants bugs handled in general ("luôn nhớ: có bug là phải fix ngay",
794
+ // "always remember: any bug must be fixed immediately, at its root cause"). It names no defect, so it owes no
795
+ // repro/root-cause contract. CLOSED GRAMMAR: the prompt is split into clauses and returns true ONLY if EVERY
796
+ // non-empty clause, whole and anchored (^...$), is one of the enumerated forms below, and at least one clause is
797
+ // a defect rule. No clause is skipped (only clauses of pure whitespace/punctuation are empty), no clause passes
798
+ // by "all its words are in a set", and no script is exempt: text in any alphabet that matches no form is an
799
+ // order. Any doubt returns false (a real bug order keeps its full evidence duty; a wrong release is the worse
800
+ // error). Global rejects first: concrete referent (path/identifier/quote/version/URL/exit code), a symptom
801
+ // statement, a deictic aimed at a present defect, no policy marker anywhere. The splitter (SP_CLAUSE_SPLIT)
802
+ // cuts on punctuation/newline ONLY and never contains a letter, so no connector word is dropped unjudged;
803
+ // "và" exists only inside form RC. Clause forms (judged on raw NFC text, accents exact, see below):
804
+ // F1 MARK a marker phrase alone ("luôn nhớ", "from now on", "nguyên tắc của tôi")
805
+ // R1 [MARK] (có|thấy|gặp|phát hiện) DEF (là|thì) [phải|luôn] FIX ADV*
806
+ // R2 [MARK] mọi DEF [là|đều] phải FIX ADV*
807
+ // R3 [MARK] (any|every|each|all) DEF (must|should|shall|needs to|has to|gets) [be] FIX ADV*
808
+ // R4 [MARK] bare-plural-DEF (must|should|shall|get) [be] FIX ADV*
809
+ // R5 [MARK] no DEF [luôn] [là (tiêu chí|nguyên tắc|quy tắc|quan điểm) [của tôi]] (nominal slogan)
810
+ // RC (R1|R2|R3|R4) và R6 (rule và purpose)
811
+ // R6 [phải] [tận root cause] để không (tái hiện|xảy ra|lặp lại) DEF nữa (purpose)
812
+ // F3 MARK [vẫn] là phải FIX ADV* (marker REQUIRED; no defect word, no scope word anywhere)
813
+ // F3p quan điểm của tôi [lần chạy này] vẫn là phải FIX ADV* (owner's exact opening)
814
+ // F4 fix [trên ukit] không phải chỉ để pass [thôi] [đâu] (negated purpose)
815
+ // F5 one fixed adverb phrase [nhé], or "nhé" alone ("ngay lập tức", "at its root cause", ...); reachable only after punctuation
816
+ // V1/V2/V3 three enumerated product-rationale sentences ("ukit là sản phẩm tôi sử dụng hỗ trợ rất nhiều sản phẩm khác" ...)
817
+ // ADV* is ONE closed whole-phrase adverb (SP_PHRASE: "ngay lập tức", "triệt để", "at its root cause", ...),
818
+ // optionally followed by "nhé"; never a run of loose words.
819
+ // ACCENTS ARE NEVER FOLDED BEFORE MATCHING. The grammar is written once, in canonical accented spelling; spw()
820
+ // compiles each Vietnamese word to an exact alternation of (its fully unaccented form | its ONE canonical
821
+ // spelling). So "lập" and "lắp"/"lấp"/"lặp", "để" and "đè"/"đẻ", "thấy" and "thay"/"thầy", "nữa" and "nửa" are
822
+ // different words: an accented token that is not the canonical spelling matches nothing. A token with no
823
+ // diacritic still stands for the canonical word (unaccented typing keeps working). English words are ASCII
824
+ // literals, so "FİXED" or "fíx" match nothing. SP_CANONICAL lists every accented word the grammar uses.
825
+ const SP_FOLD = (s) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd');
826
+ const SP_ACCENTED = new Set();
827
+ const spw = (token) => {
828
+ const t = token.normalize('NFC');
829
+ const f = SP_FOLD(t);
830
+ if (f === t) return t;
831
+ SP_ACCENTED.add(t);
832
+ return `(?:${f}|${t})`;
833
+ };
834
+ const sp = (phrase) => phrase.trim().split(/\s+/).map(spw).join('\\s+');
835
+ const spAny = (...phrases) => `(?:${phrases.map(sp).join('|')})`;
836
+ const SP_DEF = `(?:bugs?|${sp('lỗi')}|defects?|crash(?:es)?|errors?|exceptions?|broken|regressions?|failures?|failing|fails?)`;
837
+ const SP_DEF_PLURAL = `(?:bugs|${sp('lỗi')}|defects|crashes|errors|exceptions|regressions|failures)`;
838
+ const SP_FIXV = `(?:fix|fixed|fixes|fixing|${sp('sửa')}|${sp('khắc phục')}|${sp('xử lý')}|resolved?)`;
839
+ // Adverbs are a closed list of whole PHRASES, never a run of words: one primary phrase, then optionally "nhé".
840
+ const SP_PHRASE = spAny('ngay lập tức', 'ngay luôn', 'ngay', 'luôn', 'triệt để', 'tận gốc', 'hoàn toàn', 'tận root cause', 'tận root cáue',
841
+ 'at its root cause', 'at the root cause', 'at its root', 'immediately', 'right away', 'at once', 'properly', 'fully', 'completely', 'thoroughly');
842
+ const SP_ADVRUN = `(?:\\s+${SP_PHRASE})?(?:\\s+${sp('nhé')})?`;
843
+ const SP_MARK = `(?:${spAny('luôn nhớ', 'luôn luôn', 'từ giờ', 'từ nay', 'nguyên tắc', 'tiêu chí', 'quy tắc', 'quan điểm',
844
+ 'always remember', 'from now on', 'as a rule', 'my rule is', 'my policy is', 'my principle is')})(?:\\s+${sp('của tôi')})?`;
845
+ const SP_MARK_PFX = `(?:${SP_MARK}\\s+)?`;
846
+ // The enumerated clause forms (see the header comment). Every one is anchored at both ends. Connector words
847
+ // (và ...) exist ONLY inside the compound form RC below; the clause splitter never consumes a word.
848
+ const SP_R1 = `${SP_MARK_PFX}${spAny('có', 'thấy', 'gặp', 'phát hiện')}\\s+${SP_DEF}\\s+${spAny('là', 'thì')}\\s+(?:${spAny('phải', 'luôn')}\\s+)?${SP_FIXV}${SP_ADVRUN}`;
849
+ const SP_R2 = `${SP_MARK_PFX}${sp('mọi')}\\s+${SP_DEF}\\s+(?:${sp('là')}\\s+|${sp('đều')}\\s+)?${sp('phải')}\\s+${SP_FIXV}${SP_ADVRUN}`;
850
+ const SP_R3 = `${SP_MARK_PFX}(?:any|every|each|all)\\s+${SP_DEF}\\s+(?:must|should|shall|needs? to|has to|gets?)\\s+(?:be\\s+)?${SP_FIXV}${SP_ADVRUN}`;
851
+ const SP_R4 = `${SP_MARK_PFX}${SP_DEF_PLURAL}\\s+(?:must|should|shall|get)\\s+(?:be\\s+)?${SP_FIXV}${SP_ADVRUN}`;
852
+ const SP_R6 = `(?:${sp('phải')}\\s+)?(?:${spAny('tận root cause', 'tận root cáue')}\\s+)?${sp('để không')}\\s+${spAny('tái hiện', 'xảy ra', 'lặp lại')}\\s+${SP_DEF}\\s+${sp('nữa')}`;
853
+ const SP_CLAUSE_FORMS = [
854
+ new RegExp(`^${SP_MARK}$`), // F1
855
+ new RegExp(`^${SP_R1}$`), // R1
856
+ new RegExp(`^${SP_R2}$`), // R2
857
+ new RegExp(`^${SP_R3}$`), // R3
858
+ new RegExp(`^${SP_R4}$`), // R4
859
+ new RegExp(`^${SP_MARK_PFX}no\\s+${SP_DEF}(?:\\s+${sp('luôn')})?(?:\\s+${sp('là')}\\s+${spAny('tiêu chí', 'nguyên tắc', 'quy tắc', 'quan điểm')}(?:\\s+${sp('của tôi')})?)?$`), // R5
860
+ new RegExp(`^(?:${SP_R1}|${SP_R2}|${SP_R3}|${SP_R4})\\s+${sp('và')}\\s+${SP_R6}$`), // RC: rule và purpose (owner's P2)
861
+ new RegExp(`^${SP_R6}$`), // R6
862
+ new RegExp(`^${SP_MARK}\\s+(?:${sp('vẫn')}\\s+)?${sp('là phải')}\\s+${SP_FIXV}${SP_ADVRUN}$`), // F3 (marker required)
863
+ new RegExp(`^${sp('quan điểm của tôi')}(?:\\s+${sp('lần chạy này')})?\\s+${sp('vẫn là phải')}\\s+${SP_FIXV}${SP_ADVRUN}$`), // F3p
864
+ new RegExp(`^fix(?:\\s+${sp('trên ukit')})?\\s+${sp('không phải chỉ để')}\\s+pass(?:\\s+${sp('thôi')})?(?:\\s+${sp('đâu')})?$`), // F4
865
+ new RegExp(`^(?:${SP_PHRASE}(?:\\s+${sp('nhé')})?|${sp('nhé')})$`), // F5 (reachable only after punctuation)
866
+ new RegExp(`^${sp('ukit là sản phẩm tôi sử dụng hỗ trợ rất nhiều sản phẩm khác')}$`), // V1
867
+ new RegExp(`^${sp('ukit là sản phẩm quan trọng')}$`), // V2
868
+ new RegExp(`^${sp('ukit hỗ trợ rất nhiều sản phẩm khác')}$`), // V3
869
+ ];
870
+ // Folded key -> canonical accented spelling(s). One spelling per word; a word with two legitimate tone
871
+ // placements would list both here and in the grammar.
872
+ const SP_CANONICAL = {};
873
+ for (const w of [...SP_ACCENTED].sort()) (SP_CANONICAL[SP_FOLD(w)] ||= []).push(w);
874
+ // The splitter splits on punctuation/newline ONLY. It must never contain a letter: a word consumed by a
875
+ // splitter is discarded unjudged. (Asserted by a test.)
876
+ const SP_CLAUSE_SPLIT = /[.!?;:\n,]+/;
877
+ // Forms that state a defect rule: at least one clause must be one of them (R1-R5 and RC).
878
+ const SP_RULE_FORM_COUNT = 7;
879
+ const STANDING_POLICY_MARKER = /\b(?:luon nho|luon luon|tu gio|tu nay|nguyen tac|tieu chi|quy tac|quan diem|always remember|from now on|as a rule|my (?:rule|policy|principle) is)\b/;
880
+ const STANDING_POLICY_CONCRETE = /[`"“”«»]|https?:\/\/|www\.|\b\w+\(\)|[\w.-]+\/[\w.-]+|\b[\w-]+\.(?:m?js|cjs|jsx?|tsx?|json|md|sh|py|ya?ml|css|html?|go|rs|java|rb|php|sql|toml|txt|lock|log)\b|\b[a-z]+[A-Z]\w*|\b\w+_\w+|\b\w*Error\b|\bE[A-Z]{3,}\b|\bv?\d+\.\d+|\bexit\s*(?:code|status)?\s*:?\s*-?\d+|\bstack\b|\b\d{3,}\b/;
881
+ const STANDING_POLICY_SYMPTOM = /\b(?:bi loi|khong chay|khong hoat dong|hong|treo|sai|van con|chua (?:duoc )?(?:fix|sua)|crash(?:es|ed)?|(?:does ?n[o']?t|won'?t|is ?n[o']?t) work|(?:is|are) broken|fail(?:s|ed|ing)?)\b/;
882
+ const STANDING_POLICY_DEICTIC_ANYWHERE = /\b(?:the above|above|vua roi|hien tai|current(?:ly)?|dang|failing|following|ben tren|o tren)\b/;
883
+ function isStandingPolicyPrompt(promptText = '') {
884
+ const raw = String(promptText ?? '').trim();
885
+ if (!raw || raw.length > 800 || STANDING_POLICY_CONCRETE.test(raw)) return false;
886
+ // The global rejects (marker present, no symptom, no deictic) are deliberately lenient and run on a folded
887
+ // copy; the clause forms below run on the RAW lowercase NFC text, where accents are exact. Nothing but
888
+ // Latin combining marks and "đ" is ever removed from the folded copy, and the raw text is what is judged.
889
+ const text = raw.toLowerCase().normalize('NFC').replace(/\s+/g, ' ');
890
+ const folded = SP_FOLD(text);
891
+ if (!STANDING_POLICY_MARKER.test(folded) || STANDING_POLICY_DEICTIC_ANYWHERE.test(folded) || STANDING_POLICY_SYMPTOM.test(folded)) return false;
892
+ const clauses = text.split(SP_CLAUSE_SPLIT);
893
+ let ruleClauses = 0;
894
+ for (const clause of clauses) {
895
+ const norm = clause.replace(/\s+/g, ' ').trim();
896
+ // Only a clause that is empty after whitespace/ASCII punctuation is skipped. Anything else (a letter or
897
+ // digit of any script, an emoji, a symbol) must match an enumerated form, else the prompt is not a policy.
898
+ if (!norm.replace(/[\s!-/:-@[-`{-~]/g, '')) continue;
899
+ const form = SP_CLAUSE_FORMS.findIndex((re) => re.test(norm));
900
+ if (form < 0) return false;
901
+ if (form >= 1 && form < SP_RULE_FORM_COUNT) ruleClauses += 1;
902
+ }
903
+ return ruleClauses > 0;
904
+ }
905
+
906
+ // A host-delivered peer (teammate/subagent/other-session) message: optional banner line, one or more CLOSED
907
+ // peer blocks, then nothing or (banner required) the host's own single-paragraph trailer, recognised by its
908
+ // stable lead words. Owner words anywhere else make it an owner prompt. A host wording change falls back to
909
+ // "not a peer prompt" (old routing), never to dropping owner text. Mirrors the early-exit check in skill-router.sh.
910
+ function isPeerMessagePrompt(promptText = '') {
911
+ const text = String(promptText ?? '').trim();
912
+ const banner = /^Another Claude session sent a message:[ \t]*\r?\n/i;
913
+ const bannered = banner.test(text);
914
+ let rest = text.replace(banner, '').trim();
915
+ const peerBlock = /^<(agent-message|teammate-message|cross-session-message)(?:\s[^>]*)?>[\s\S]*?<\/\1>\s*/;
916
+ let blocks = 0;
917
+ for (let m = peerBlock.exec(rest); m; m = peerBlock.exec(rest)) { rest = rest.slice(m[0].length); blocks += 1; }
918
+ const trailer = /^(?:This came from another Claude session|That .other Claude session. is an agent working inside this same session)[^\r\n]{0,1500}$/i;
919
+ return blocks > 0 && (rest === '' || (bannered && trailer.test(rest.trim())));
920
+ }
921
+
739
922
  function classifyOwnerControl(promptText = '') {
740
923
  const raw = String(promptText ?? '').normalize('NFC').trim();
924
+ // Text shape is never provenance here: an envelope-first/banner-first text already yields kind null because
925
+ // OWNER_STOP_EN/VI are anchored on the first lead (proved 0 diffs vs the former isPeerMessagePrompt guard).
741
926
  if (!raw || OWNER_CONTROL_HOOK_TEXT.test(raw)) return { kind: null };
742
927
  const stripped = raw.replace(/^[\s*#_-]+/, '');
743
928
  if (/^[>"'`\u201c\u2018]/.test(stripped)) return { kind: null };
@@ -929,7 +1114,13 @@ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
929
1114
  const cronOperation = actionable.some((clause) => /\b(?:delete|remove|cancel|xoa|huy|ensure|dam bao)\b/.test(clause)
930
1115
  && /\bcron\b|scheduled\s+(?:cron\s+)?(?:task|job)|tac vu\s+(?:cron|dinh ky)/.test(clause))
931
1116
  && (!codeChangeVerb || hasOperationId);
1117
+ // Pure per clause and asked once by runtimeClause and once by gitClause for every clause; compute each clause once.
1118
+ const operationNotOrderedMemo = new Map();
932
1119
  const operationNotOrdered = (clause) => {
1120
+ if (!operationNotOrderedMemo.has(clause)) operationNotOrderedMemo.set(clause, operationNotOrderedUncached(clause));
1121
+ return operationNotOrderedMemo.get(clause);
1122
+ };
1123
+ const operationNotOrderedUncached = (clause) => {
933
1124
  const OP = '(?:restart|redeploy|deploy(?:ment)?|trien khai|khoi dong lai|git\\s+push|push\\s+(?:to\\s+)?origin|commit|push)';
934
1125
  const BAN = '(?:bi\\s+(?:cam|chan)|forbidden|prohibited|banned|not\\s+allowed|not\\s+permitted|disallowed)';
935
1126
  if (/\b(?:was|were|previously|before|formerly|no\s+longer|even\s+though|although|though|now\s+allows?|now\s+permits?|owner\s+allows?|khong\s+bi|da\s+duoc\s+phep|except)\b/.test(clause)) return false;
@@ -2918,7 +3109,9 @@ function applyTaskSemantics(contract, semantic) {
2918
3109
  return false;
2919
3110
  }
2920
3111
  }
2921
- const implementWords = /(?<![A-Za-z0-9_])(implement|apply|update|modify|add|create|ship|deliver|fix|refactor|remove|delete|rename|change|write|build|make|install|run|deploy|execute|sửa|thêm|tạo|xóa|đổi|thay thế|cập nhật|viết|build|chạy|cài)(?![A-Za-z0-9_])/.test(raw);
3112
+ // chạy/tạo/cài are judged by the shared position rule (ambiguousVerbOrder), not by bare presence.
3113
+ const implementWords = /(?<![A-Za-z0-9_])(implement|apply|update|modify|add|create|ship|deliver|fix|refactor|remove|delete|rename|change|write|build|make|install|run|deploy|execute|sửa|thêm|xóa|đổi|thay thế|cập nhật|viết|build)(?![A-Za-z0-9_])/.test(softenEnglishNouns(raw))
3114
+ || ambiguousVerbOrder(raw);
2922
3115
  if (implementWords && !consultShape) return false;
2923
3116
  const investigationWords = /\b(why|debug|triage|root cause|investigate|tại sao)\b/.test(raw);
2924
3117
  if (investigationWords && !consultShape) return false;
@@ -2964,6 +3157,8 @@ function applyTaskSemantics(contract, semantic) {
2964
3157
  }
2965
3158
 
2966
3159
  function hasAdvisoryOnlyAssertion({ promptText = '', commandText = '' } = {}) {
3160
+ // A standing owner policy about bugs in general is advisory: no defect is named, nothing to repro.
3161
+ if (!String(commandText || '').trim() && isStandingPolicyPrompt(promptText)) return true;
2967
3162
  const folded = `${promptText ?? ''}\n${commandText ?? ''}`
2968
3163
  .toLowerCase()
2969
3164
  .normalize('NFD')
@@ -3036,7 +3231,51 @@ function applyTaskSemantics(contract, semantic) {
3036
3231
  // folding, so "Cái này là gì, tại sao…" is not read as an install order (3.4.81 telemetry audit).
3037
3232
  function maskTonedNonVerbs(text = '') {
3038
3233
  return String(text ?? '').normalize('NFC')
3039
- .replace(/(?<![\p{L}\p{N}_])(?:cái|chính|việt|cháy|chảy|đợi|đời|đối|đội|đôi|đói|sữa|thèm)(?![\p{L}\p{N}_])/giu, ' _ ');
3234
+ .replace(/(?<![\p{L}\p{N}_])(?:cái|cải|cãi|chính|việt|cháy|chảy|đợi|đời|đối|đội|đôi|đói|sữa|thèm)(?![\p{L}\p{N}_])/giu, ' _ ');
3235
+ }
3236
+ // Position rule for the closed set of verbs that tone-fold onto an order verb but are ordinary
3237
+ // aspect/nominal words in progress talk: ch\u1ea1y (run / is running), t\u1ea1o (create / the creation of),
3238
+ // c\u1ea3i/c\u00e0i (improve / install). Input is folded (accent-free, lowercase) text. A verb is an ORDER when it
3239
+ // has an object or an imperative particle; it is NOT an order after a nominaliser/preposition/copula/
3240
+ // aspect marker (PREV = cua, viec, su, khi, dang) or when only a stative/degree complement follows
3241
+ // (co ve + lau, mai, hoai, cham, nhanh, xong, roi, duoc, qua, rat, hoi, ne, then end of clause or a conjunction).
3242
+ // Imperative particles (di, luon, ngay, giup, gium, ho, nhe) within 3 tokens always keep it an order.
3243
+ // Non-orders become " _ "; orders are untouched. English: a mutation word right after a determiner/possessive is
3244
+ // a noun ("the build"), unless a light verb stands before the determiner ("do the build", "finish that update").
3245
+ // Destructive verbs (x\u00f3a, delete, drop, reset) are deliberately not in this set.
3246
+ // Three copies (taskRouting.js, route-task.mjs, skill-router.sh) \u2014 keep them identical.
3247
+ function softenEnglishNouns(text = '') {
3248
+ return String(text).replace(/(?<!\b(?:do|does|doing|perform|finish|complete|handle|start|get|try)\s+)\b(the|a|an|any|this|that|these|those|my|our|your|its|their|his|her)\s+(?:implement|apply|update|modify|add|create|ship|deliver|fix|refactor|rename|change|write|build|make|install|run|deploy|execute|edit)\b/gi, '$1 _ ');
3249
+ }
3250
+ function softenAmbiguousVerbs(folded = '') {
3251
+ const PREV = new Set(['cua', 'viec', 'su', 'khi', 'dang']);
3252
+ const PARTICLE = new Set(['di', 'luon', 'ngay', 'giup', 'gium', 'ho', 'nhe']);
3253
+ const COMPLEMENT = new Set(['lau', 'mai', 'hoai', 'cham', 'nhanh', 'xong', 'roi', 'duoc', 'qua', 'rat', 'hoi', 'ne']);
3254
+ const CONJ = new Set(['ma', 'nhung', 'va', 'thi', 'hay', 'nen', 'khong', 'chua', 'but', 'and', 'so']);
3255
+ // Each occurrence is judged on its own (a clause can hold several: "tạo ra Ukit là cải tiến ...").
3256
+ // English: a mutation token right after a determiner/possessive is a noun ("the build", "my fix"), never an
3257
+ // order. Only that token is softened, so "run the build" / "fix the build" still order through the verb.
3258
+ // delete/remove are never softened.
3259
+ return softenEnglishNouns(folded).replace(/\b(chay|tao|cai)\b/g, (match, verb, offset, whole) => {
3260
+ const prev = whole.slice(0, offset).trimEnd().split(/\s+/).pop() || '';
3261
+ const tokens = (whole.slice(offset + match.length).split(/[.,;!?\n]/)[0] || '').split(/\s+/).filter(Boolean);
3262
+ if (tokens.slice(0, 3).some((token) => PARTICLE.has(token))) return match;
3263
+ if (PREV.has(prev)) return ' _ ';
3264
+ let index = 0;
3265
+ let consumed = 0;
3266
+ while (index < tokens.length) {
3267
+ if (tokens[index] === 'co' && tokens[index + 1] === 've') { index += 2; consumed += 1; continue; }
3268
+ if (COMPLEMENT.has(tokens[index])) { index += 1; consumed += 1; continue; }
3269
+ break;
3270
+ }
3271
+ if (consumed > 0 && (index >= tokens.length || CONJ.has(tokens[index]))) return ' _ ';
3272
+ return match;
3273
+ });
3274
+ }
3275
+ // The shared predicate: does any ambiguous verb in this text still stand as an order?
3276
+ function ambiguousVerbOrder(text = '') {
3277
+ const folded = maskTonedNonVerbs(text).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/\u0111/g, 'd');
3278
+ return /\b(?:chay|tao|cai)\b/.test(softenAmbiguousVerbs(folded));
3040
3279
  }
3041
3280
  function hasMutationOrder({ promptText = '', commandText = '' } = {}) {
3042
3281
  const folded = `${publicationScope(maskTonedNonVerbs(promptText)).text}\n${commandText ?? ''}`
@@ -3044,7 +3283,7 @@ function applyTaskSemantics(contract, semantic) {
3044
3283
  .normalize('NFD')
3045
3284
  .replace(/[\u0300-\u036f]/g, '')
3046
3285
  .replace(/\u0111/g, 'd');
3047
- const trimmed = folded.trim();
3286
+ const trimmed = softenAmbiguousVerbs(folded.trim());
3048
3287
  if (!trimmed) return false;
3049
3288
  if (ordersPublication(promptText)) return true;
3050
3289
  if (!String(commandText ?? '').trim() && (declaredReadOnly(promptText, classifyTaskSemantics({ promptText }).releasePolicy)
@@ -3272,7 +3511,6 @@ function applyTaskSemantics(contract, semantic) {
3272
3511
  // it with hasMutationOrder keeps "sửa file cho tôi?" mutating while
3273
3512
  // "lỗi này chưa nhỉ" / "should I fix the hook?" consult. A targetFile
3274
3513
  // still vetoes.
3275
- const consultationImplementWords = /(?<![A-Za-z0-9_])(?:implement|apply|update|modify|add|create|ship|deliver|fix|refactor|remove|delete|rename|change|write|build|make|install|run|deploy|execute|sửa|thêm|tạo|xóa|đổi|thay thế|cập nhật|viết|chạy|cài)(?![A-Za-z0-9_])/.test(trimmedPromptText);
3276
3514
  const consultationOnlySignal = questionShapedPrompt
3277
3515
  && !hasMutationOrder({ promptText, commandText })
3278
3516
  && !targetFile;
@@ -4486,7 +4724,36 @@ function applyTaskSemantics(contract, semantic) {
4486
4724
  }
4487
4725
  }
4488
4726
  let expectedRouteVersion;
4727
+ // Set only while a fresh owner prompt over an armed contract has not yet published (see the gate before
4728
+ // promptText); cleared once the provisional publication commits. Null = a kill behaves as before.
4729
+ let deadlineMarkerGate = null;
4730
+ deadlineHandler = async () => {
4731
+ const gate = deadlineMarkerGate;
4732
+ if (!gate || !sessionRoutePath) return;
4733
+ const lockModule = path.join(process.env.HOOK_DIR || path.join(projectRoot, '.claude', 'hooks'), '..', 'ukit', 'runtime', 'async-lock.mjs');
4734
+ const { withAsyncLock } = await import(pathToFileURL(lockModule).href);
4735
+ await withAsyncLock(sessionRoutePath, { deadlineMs: 300 }, async () => {
4736
+ // Same compare as persistRouteState: skip when the session route moved since this hook read it.
4737
+ // Compare against the version captured at gate time (never a fresh read, never the live
4738
+ // expectedRouteVersion that a committing publication advances): another process that published
4739
+ // since the gate, or our own publication having committed, makes this a skip.
4740
+ const bytes = await readRouteVersion();
4741
+ if (bytes !== gate.routeVersion || deadlineMarkerGate !== gate) return;
4742
+ let committedStop = null;
4743
+ try {
4744
+ const committed = bytes === null ? null : JSON.parse(bytes);
4745
+ if (committed?.ownerControl?.kind === 'stop' && committed.sessionId === sessionId) committedStop = committed.ownerControl;
4746
+ } catch {}
4747
+ await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({
4748
+ sessionId, taskInstanceId: gate.taskInstanceId, routeGeneration: gate.routeGeneration,
4749
+ routePersistenceRevision: crypto.randomUUID(), routePublicationIncomplete: true,
4750
+ ...(committedStop ? { ownerControl: committedStop } : {}),
4751
+ }));
4752
+ });
4753
+ };
4489
4754
  async function persistRouteState(text, recoveryOwner = null) {
4755
+ // After the deadline fired the only permitted write is the kill marker above.
4756
+ if (deadlineReached) throw new Error('hook deadline reached before route publication');
4490
4757
  if (sessionId) {
4491
4758
  // The lock primitive ships beside this hook; resolve it from the hook's own install dir so a
4492
4759
  // workspace whose runtime copy is absent/partial still takes the same lock (never unlocked).
@@ -4505,6 +4772,7 @@ function applyTaskSemantics(contract, semantic) {
4505
4772
  } else if (!handoffSkill && !handoffExpansion && await readRouteVersion() !== expectedRouteVersion) {
4506
4773
  throw new Error('session route changed before write');
4507
4774
  }
4775
+ if (deadlineReached) throw new Error('hook deadline reached before route publication');
4508
4776
  const persisted = await persistRouteStateLocked(text);
4509
4777
  expectedRouteVersion = await readRouteVersion();
4510
4778
  return persisted;
@@ -4537,7 +4805,7 @@ function applyTaskSemantics(contract, semantic) {
4537
4805
  // its own: mutationOrder recomputed from a file path / the word "continue" / guidance
4538
4806
  // wording says nothing about what the user ordered, so the original prompt's stamp
4539
4807
  // stays authoritative.
4540
- if ((!extractPrompt(payload) || continuationPrompt || systemOriginTurn || guidanceTurn) && typeof previous.routingContext.mutationOrder === 'boolean') {
4808
+ if ((!extractPrompt(payload) || continuationPrompt || embeddedContinuationPrompt || systemOriginTurn || guidanceTurn) && typeof previous.routingContext.mutationOrder === 'boolean') {
4541
4809
  persisted.routingContext.mutationOrder = previous.routingContext.mutationOrder;
4542
4810
  }
4543
4811
  }
@@ -4606,6 +4874,7 @@ function applyTaskSemantics(contract, semantic) {
4606
4874
  const informationalTurn = !continuingTask && !semantic.statusReport
4607
4875
  && (semantic.taskKind === 'CODE_IMPLEMENTATION' || answerQuestion)
4608
4876
  && (isInformationalPrompt({ promptText: turnPrompt })
4877
+ || isStandingPolicyPrompt(turnPrompt)
4609
4878
  || isPureGreetingPrompt({ promptText: turnPrompt }));
4610
4879
  // A system-injected turn (wakeup / compaction summary) resumes the previous task; when that task holds
4611
4880
  // no contract (the owner's last turn was a question), the injected wording must not mint one: it was
@@ -4742,6 +5011,10 @@ function applyTaskSemantics(contract, semantic) {
4742
5011
  } catch { return null; }
4743
5012
  })();
4744
5013
  const markerControl = persisted.ownerControl ?? committedStop;
5014
+ // Re-check under the sidecar lock, right before the first write: if the kill marker already landed (or the
5015
+ // deadline fired) this publication must abort, never overwrite the marker. A publication that passed this
5016
+ // point has written its own pending marker first, so a hard exit mid-way still fails closed.
5017
+ if (deadlineReached) throw new Error('hook deadline reached before route publication');
4745
5018
  if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true, ...(markerControl ? { ownerControl: markerControl } : {}) }));
4746
5019
  try {
4747
5020
  await writeJsonFileAtomic(statePath, text);
@@ -5009,6 +5282,26 @@ function applyTaskSemantics(contract, semantic) {
5009
5282
  coordinationTurn = true;
5010
5283
  return false;
5011
5284
  }
5285
+ // Idle-session peer delivery (real host shape, host 2.1.322): queue-operation enqueue + dequeue (no
5286
+ // content/origin) then ONE meta user entry stamped origin.kind 'peer' / turnOrigin 'peer' /
5287
+ // promptSource 'system'. The hook payload prompt is the bare envelope block; the transcript entry
5288
+ // holds the host's banner line + block + one-paragraph trailer. The branch requires the same
5289
+ // session, the current turn (the assistant boundary above already cleared deliveryCurrent), the
5290
+ // prompt occurring exactly once in the entry text, only the known banner line (or nothing) before
5291
+ // it, and only a known single-line trailer (or nothing) after it. Any other extra text is not
5292
+ // proof. A human paste leaves origin.kind 'human' / promptSource 'typed' and never matches.
5293
+ if (deliveryCurrent && entry.isMeta === true && entry.promptSource === 'system' && entry.turnOrigin === 'peer'
5294
+ && entry.origin?.kind === 'peer' && sessionId && entry.sessionId === sessionId) {
5295
+ const at = text.indexOf(promptTrim);
5296
+ const before = at < 0 ? null : text.slice(0, at).trim();
5297
+ const after = at < 0 ? null : text.slice(at + promptTrim.length).trim();
5298
+ if (at >= 0 && text.indexOf(promptTrim, at + 1) < 0
5299
+ && (before === '' || before === 'Another Claude session sent a message:')
5300
+ && (after === '' || (!after.includes('\n') && /^(?:This came from another Claude session|That "other Claude session" is an agent)\b/.test(after)))) {
5301
+ coordinationTurn = true;
5302
+ return false;
5303
+ }
5304
+ }
5012
5305
  if (entry.isMeta === true && entry.turnOrigin === 'scheduled'
5013
5306
  && entry.promptSource === 'system' && entry.scheduledTaskId
5014
5307
  && entry.sessionId === sessionId && text === promptTrim
@@ -5016,6 +5309,9 @@ function applyTaskSemantics(contract, semantic) {
5016
5309
  coordinationTurn = true;
5017
5310
  return false;
5018
5311
  }
5312
+ // A peer-stamped record is delivery proof only inside this session; another session's record
5313
+ // (or a stale one) never exempts this prompt.
5314
+ if (entry.turnOrigin === 'peer' || entry.origin?.kind === 'peer') return false;
5019
5315
  return entry.isMeta === true && (entry.turnOrigin === 'scheduled' || entry.promptSource === 'system')
5020
5316
  && text === promptTrim;
5021
5317
  }
@@ -5192,7 +5488,45 @@ function applyTaskSemantics(contract, semantic) {
5192
5488
  const owned = targets(previous.routingContext?.lastExplicitUserPromptText);
5193
5489
  return wanted.size > 0 && [...wanted].every((target) => owned.has(target));
5194
5490
  })();
5195
- const continuingTask = Boolean(previous.taskInstanceId && (payload.tool_name || handoffExpansion || continuationPrompt || ownerResumeTurn || systemOriginTurn || guidanceTurn));
5491
+ // Clause-level continuation ("nếu có tiến triển thì tiếp tục làm", "tiếp tục. không dừng, nhớ check ..."):
5492
+ // at least one clause is a bare continuation (optionally behind a conditional head) and EVERY other
5493
+ // clause is a non-order by the same predicate that stamps mutationOrder. It binds only to a LIVE contract
5494
+ // of this session (never to suspendedContract: only the whole-string explicit continuation restores that),
5495
+ // mints nothing when there is none, and never overrides an owner STOP. Any ordering clause -> fresh task.
5496
+ const embeddedContinuationPrompt = (() => {
5497
+ if (explicitContinuationPrompt || payload.tool_name || ownerControlTurn || !sessionId || !previous.taskInstanceId) return false;
5498
+ if (!previous.routeSummary?.executionContract?.completionEvidence?.length || previous.routeSummary.executionContract.statusReport) return false;
5499
+ const raw = extractPrompt(payload);
5500
+ if (!raw.trim() || raw.length > 1200) return false;
5501
+ const fold = (text) => String(text ?? '').normalize('NFD').replace(/\p{M}+/gu, '').replace(/đ/gi, 'd').toLowerCase();
5502
+ const CONT ='(?:continue|resume|keep going|go on|proceed|tiep tuc|lam tiep)(?:\\s+(?:lam|viec|di|nhe|nao|nua|a|ha|please|pls|now|then|it|that|going|on|working))*';
5503
+ // Group 1 = the conditional head. A head that itself carries an order ("neu xong thi sua ham login roi
5504
+ // tiep tuc") is not a bare continuation: the head is checked WITHOUT the conditional strip hasMutationOrder applies.
5505
+ const bare = new RegExp(`^(?:(?:neu|if|khi|when)\\s+(.{1,80}?)\\s+(?:(?:thi|then)\\s+)?)?${CONT}\\s*$`);
5506
+ const clauses = raw.split(/[.!?;\n,]+/).map((clause) => clause.trim()).filter(Boolean);
5507
+ if (clauses.length < 2 && !clauses.some((clause) => !new RegExp(`^${CONT}\\s*$`).test(fold(clause)) && bare.test(fold(clause)))) return false;
5508
+ let continuation = false;
5509
+ // Any mutation verb in the head disqualifies it (hasMutationOrder would strip a conditional tail, and reads
5510
+ // "xong thi sua ham login roi" as already done). Ambiguous verbs go through the same position rule.
5511
+ // The head is a CONDITION only: a consequent inside it ("thi ..."/"then ...") is an action riding the old task,
5512
+ // and publication/operation verbs (push, commit, publish, release, merge, tag, restart) count as orders too.
5513
+ const HEAD_VERB = /\b(?:implement|apply|update|modify|add|create|ship|deliver|fix|refactor|remove|delete|rename|change|write|build|make|install|run|deploy|execute|edit|push|commit|publish|release|merge|tag|rebase|restart|sua|them|tao|xoa|doi|cap\s+nhat|viet|chay|cai|chinh|trien\s+khai|cau\s+hinh|dang\s+len)\b/;
5514
+ // ONE predicate for "this text carries an order": a mutation order, a publication order, or an operation verb.
5515
+ // It judges the head AND every non-continuation clause (a plain "push luon" is OPERATIONAL, not a bare continuation).
5516
+ const OP_VERB = /\b(?:push|commit|publish|release|merge|tag|rebase|restart|dang\s+len)\b/;
5517
+ const carriesOrder = (text) => hasMutationOrder({ promptText: text, commandText: '' }) || ordersPublication(text) || OP_VERB.test(softenAmbiguousVerbs(fold(text)));
5518
+ for (const clause of clauses) {
5519
+ const match = bare.exec(fold(maskTonedNonVerbs(clause)));
5520
+ if (match) {
5521
+ if (match[1] && (/\b(?:thi|then)\b/.test(match[1]) || HEAD_VERB.test(softenAmbiguousVerbs(match[1])) || carriesOrder(match[1]))) return false;
5522
+ continuation = true;
5523
+ continue;
5524
+ }
5525
+ if (carriesOrder(clause)) return false;
5526
+ }
5527
+ return continuation && !carriesOrder(raw);
5528
+ })();
5529
+ const continuingTask = Boolean(previous.taskInstanceId && (payload.tool_name || handoffExpansion || continuationPrompt || embeddedContinuationPrompt || ownerResumeTurn || systemOriginTurn || guidanceTurn));
5196
5530
  // An owner prompt that explicitly resumes the previous checkpoint (names its background job id or commit)
5197
5531
  // still mints a fresh task id - the contract may legitimately differ (e.g. a new deploy authorization) -
5198
5532
  // but records a bounded single-hop predecessor link so the ledger can reconcile current evidence. A
@@ -5427,6 +5761,14 @@ function applyTaskSemantics(contract, semantic) {
5427
5761
  : String(transcriptPathCandidate).trim() || null;
5428
5762
 
5429
5763
  const promptText = extractPrompt(payload);
5764
+ // Kill-marker gate: a fresh owner prompt (not a tool event, continuation, system turn, guidance or
5765
+ // handoff-bound task) over an armed previous contract. Past this point only the provisional publication
5766
+ // can replace that contract; a deadline kill before it commits must not leave the old contract live.
5767
+ if (!payload.tool_name && sessionId && promptText && !continuingTask && !systemOriginTurn && !guidanceTurn
5768
+ && !handoffExpansion && !handoffSkill && !previous.handoffRunId && previous.taskInstanceId && expectedRouteVersion !== undefined
5769
+ && previous.routeSummary?.executionContract?.completionEvidence?.length) {
5770
+ deadlineMarkerGate = { taskInstanceId: previous.taskInstanceId, routeGeneration: previous.routeGeneration || previous.taskInstanceId, routeVersion: expectedRouteVersion };
5771
+ }
5430
5772
  const commandText = payload.tool_input?.command || payload.command || '';
5431
5773
  const filePath = normalizeRelativeFile(projectRoot, payload.tool_input?.file_path || payload.file_path || '');
5432
5774
  const { buildRouteSignalText } = await loadLanguageTools(projectRoot);
@@ -5520,6 +5862,11 @@ function applyTaskSemantics(contract, semantic) {
5520
5862
  && !filePath;
5521
5863
 
5522
5864
  if (active.length === 0 || informationalNoTargetPrompt) {
5865
+ // This branch deliberately carries the previous contract forward (see the persist below), so a kill here
5866
+ // must not strand a marker that drops it. deliveryOnlyNoRoute drops the contract on its normal write, so the
5867
+ // gate stays armed there. With the gate null the deadline handler returns at once and the process exits in
5868
+ // the same microtask drain, before any pending import (the advisory below) can resume and print.
5869
+ if (previous?.routeSummary && !deliveryOnlyNoRoute) deadlineMarkerGate = null;
5523
5870
  const lastExplicitUserPromptText = promptText.trim()
5524
5871
  || previous?.routingContext?.lastExplicitUserPromptText
5525
5872
  || '';
@@ -5714,6 +6061,7 @@ function applyTaskSemantics(contract, semantic) {
5714
6061
  provisionalState.fingerprint = buildRouteStateFingerprint(provisionalState);
5715
6062
  await ensureDir(statePath);
5716
6063
  await persistRouteState(JSON.stringify(provisionalState));
6064
+ deadlineMarkerGate = null;
5717
6065
 
5718
6066
  let cacheUtils = null;
5719
6067
  if (await pathExists(cacheUtilsPath)) {
@@ -5970,6 +6318,9 @@ function applyTaskSemantics(contract, semantic) {
5970
6318
  process.stdout.write(`[ukit-skill-router] Helper: ${routeSummary.helperHint}\n`);
5971
6319
  }
5972
6320
  })().catch((error) => {
6321
+ // Once the self-deadline fired, only the deadline timer's own path (marker write, then exit; or the 400 ms
6322
+ // hard exit) may end the process or write to stdout: a refused publication here is the deadline, not a crash.
6323
+ if (deadlineReached) return;
5973
6324
  const detail = error?.message || String(error);
5974
6325
  process.stderr.write(`[ukit-skill-router] ${detail}\n`);
5975
6326
  // BUG-C23-07: a crashed router abandons configured routing work — announce the
@@ -201,6 +201,11 @@ const GENERIC_STOPWORDS = new Set([
201
201
  'neu', 'nhung', 'nua', 'roi', 'toi', 'tren', 'truoc', 'va', 'voi',
202
202
  ]);
203
203
  const VIETNAMESE_PHRASE_ALIASES = [
204
+ // Bigrams only: the unigrams "trien"/"khai" also fold "tiến triển" (progress) / "khai" in unrelated
205
+ // words onto implement/build/ship, which selected the delivery skill for progress questions (3.5.8).
206
+ { regex: /\btrien khai\b/gu, expansions: ['implement', 'deploy', 'ship'] },
207
+ { regex: /\bphat trien\b/gu, expansions: ['develop', 'build'] },
208
+ { regex: /\bkhai bao\b/gu, expansions: ['declare'] },
204
209
  { regex: /\bbo nho dem\b/gu, expansions: ['cache'] },
205
210
  { regex: /\bduong dan\b/gu, expansions: ['route', 'path'] },
206
211
  { regex: /\bxac thuc\b/gu, expansions: ['auth', 'authentication'] },
@@ -272,8 +277,6 @@ const VIETNAMESE_TOKEN_ALIASES = new Map([
272
277
  ['component', ['component']],
273
278
  ['test', ['test', 'testing']],
274
279
  ['soat', ['review', 'audit']],
275
- ['trien', ['implement', 'build', 'ship']],
276
- ['khai', ['implement', 'build', 'ship']],
277
280
  ['kho', ['store', 'storage']],
278
281
  ['ghi', ['write', 'record']],
279
282
  ['doc', ['read']],
@@ -263,7 +263,15 @@ export function fuseSemantic({ ranked, candidates, rrfK = 5, weight = 1, depth =
263
263
  candidates.slice(0, depth).forEach((c, i) => rrf.set(c.filePath, (rrf.get(c.filePath) ?? 0) + weight / (rrfK + i + 1)));
264
264
  const byPath = new Map(ranked.map((e) => [e.filePath, e]));
265
265
  const floor = ranked.length ? ranked[ranked.length - 1].score : 0.01;
266
+ // The printed `score` is the fused (RRF) value the order was sorted by, so it is monotonic
267
+ // with rank; the pre-fusion lexical score is kept as `lexicalScore`.
266
268
  return [...rrf.entries()]
267
269
  .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
268
- .map(([filePath]) => byPath.get(filePath) ?? { filePath, score: Math.min(0.01, floor), reasons: ['semantic:vector'], tests: [] });
270
+ .map(([filePath, fusedScore]) => {
271
+ const lexical = byPath.get(filePath);
272
+ const score = Number(fusedScore.toFixed(4));
273
+ return lexical
274
+ ? { ...lexical, score, lexicalScore: lexical.score }
275
+ : { filePath, score, lexicalScore: Math.min(0.01, floor), reasons: ['semantic:vector'], tests: [] };
276
+ });
269
277
  }
@@ -22,6 +22,7 @@ import path from 'node:path';
22
22
  import { fileURLToPath } from 'node:url';
23
23
 
24
24
  import { isRunAllRequest } from '../runtime/handoff-intent.mjs';
25
+ import { isStandingPolicyPrompt } from './publication-intent.mjs';
25
26
  import { deriveEscalationTriggers, deriveRiskFloor } from './route-resolver.mjs';
26
27
 
27
28
  const PLAYBOOK_NAME_RE = /\.md$/i;
@@ -223,7 +224,7 @@ export const PLAYBOOK_ROUTING_TABLE = Object.freeze([
223
224
  fastPath: 'bug-fix',
224
225
  // T-026 review fix: a skill-ask that happens to mention a fix ("make this
225
226
  // repeated fix flow a skill") is skill-authoring, not a defect order.
226
- discriminator: (s) => !s.explanationAsk && !s.questionAsk && !s.forensicsSignal && !s.checkFirst && !s.skillAsk,
227
+ discriminator: (s) => !s.explanationAsk && !s.questionAsk && !s.forensicsSignal && !s.checkFirst && !s.skillAsk && !s.standingPolicy,
227
228
  },
228
229
  {
229
230
  workGroup: 'investigation',
@@ -397,6 +398,7 @@ function matchFirst(text, regexes) {
397
398
 
398
399
  async function buildRouteSignals({
399
400
  signalText,
401
+ rawPromptText = '',
400
402
  executionMode,
401
403
  escalationTriggers,
402
404
  projectRoot,
@@ -480,6 +482,8 @@ async function buildRouteSignals({
480
482
  // BL-026 review fix: ask to convert/author a skill — beats defect verbs in
481
483
  // the same sentence ("make this repeated fix flow a skill").
482
484
  skillAsk: SKILL_ASK_RE.test(signalText),
485
+ // A standing owner policy about bugs in general names no defect: it must not mint the bug-fix floor.
486
+ standingPolicy: isStandingPolicyPrompt(rawPromptText || signalText),
483
487
  };
484
488
  }
485
489
 
@@ -676,6 +680,7 @@ export async function resolvePlaybookId({
676
680
  ])];
677
681
  const signals = await buildRouteSignals({
678
682
  signalText,
683
+ rawPromptText: String(promptText || ''),
679
684
  executionMode,
680
685
  escalationTriggers: mergedTriggers,
681
686
  projectRoot,