@ngockhoale/ukit 3.5.6 → 3.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.5.7 - 2026-11-16
6
+
7
+ Bug-fix release: eight defects found while shipping 3.5.6, each fixed at its cause. No host (Claude Code, Codex, omp) was run live and nothing was run on Windows; the checks are unit tests and real hook processes on this repository.
8
+
9
+ - **Fix: a message from a teammate or subagent is no longer treated as a new task from you.** In Claude Code, a message delivered from another agent of the same session was routed like an owner prompt: it minted a new task and the completion gate then demanded edits and test runs for it. The router now exempts such a message only on the host's own delivery record: a transcript entry of the current turn and the same session that Claude Code stamped as a peer delivery and that carries exactly the delivered block (with at most the host's banner line before it and its one-line trailer after it). For the router, the text of a message is never proof on its own: the same block pasted by you, a record from another session or an earlier turn, or a block with any words of yours around it is routed as your prompt. A peer record stamped in a different session no longer exempts a prompt (in 3.5.6 it could). The stop coordinator never treats an entry the host stamped as typed by you as a peer message, whatever its text; host-stamped peer deliveries were already skipped. Entries without host stamps (older Claude Code versions) are still recognised there by their message envelope. Limits: Claude Code only, so omp and Codex behave as in 3.5.6. The hook-input shape was inferred from the recorded prompt fingerprints of seven single-block deliveries, not from a live capture. Any other shape (several blocks, changed trailer wording, a record outside the transcript tail) falls back to routing the prompt as yours. Teammate messages that Claude Code injects without a stamped delivery record never run the prompt hook and were never affected; only the stamped deliveries did.
10
+ - **Fix: stating a rule about bugs is not an order to fix one.** A prompt such as "luôn nhớ: có bug là phải fix ngay" or "always remember: any bug must be fixed at its root cause" names no defect, yet it was routed as a bug fix and owed a reproduction and a root cause. It is now advisory. The rule is deliberately narrow: only a prompt made entirely of the recognised generic rule sentences is advisory. A prompt that names a target, a symptom or a specific bug, or adds any other request in any language ("…, fix cái login đi", "… Trang thanh toán không chạy được", "… Fix checkout") stays a bug fix with its full evidence duty, and a task already in progress keeps its own duties. A rule worded differently from the recognised sentences is treated as a bug fix too (more evidence asked, never less). One limit: Vietnamese typed without accents is read as the rule wording, so an unaccented sentence that spells exactly a rule sentence (e.g. "thay bug la phai fix ngay", which could also mean "replace the bug…") is taken as the rule; with accents the two are told apart.
11
+ - **Fix: managed-template merge — two limits of 3.5.6 removed.** (1) A heading you only quoted inside a code block no longer stops the real template section of that name from being added. (2) A section you deleted stays deleted. What decides both is now the record of what UKit wrote, not a scan of the text. The record written by 3.5.6 cannot be trusted for this (it listed sections it had skipped), so on the first install after upgrading — from 3.5.6 or from anything older — every template section missing from your file is added once, including one you had deleted on purpose; delete it again and it stays gone. One case is held back: if your file has a code fence that is never closed, new sections are not added and install names them once; close the fence and the next install adds them. Still true from 3.5.6: on the first install after upgrading from 3.5.5 or older, a section that differs from the current template is kept as if you had edited it. A project that goes back to 3.5.6 reads the new record without change (tested against the shipped 3.5.6 code). **Correction to the 3.5.6 notes:** they described `docs/AI_HANDOFF/queued/README.md` copies older than 3.4.66 ending up with renamed sections side by side. No shipped template ever had the old headings (the file first shipped in 3.4.66 with the current ones), so that case does not exist. The merge can now follow a heading rename (an untouched section is renamed in place; an edited one is kept and reported once), but no rename is registered in this release.
12
+ - **Fix: index search with the vector lane on printed scores out of order.** The list was ordered by the fused rank but printed the older lexical score, so a lower line could show a higher number. `score` is now the value the list is sorted by; the lexical score is kept as `lexicalScore`. With the lane off the output is byte-identical to 3.5.6.
13
+ - **Fix: a decision call that ran out of time was logged as "could not start".** When the local decision adapter was killed at its time limit (seen under heavy CPU load), the decision log said `adapter-spawn-failed`; it now says `deadline-exceeded`. A non-zero exit or a missing adapter still says `adapter-spawn-failed`. Routing was never affected: the built-in fallback decided in both cases.
14
+ - **Fix: a very long prompt could leave the previous task in force.** The prompt hook stops itself at its time limit so it can never hang the host. On a long prompt (about 15,000 characters) on a busy machine the analysis alone took longer than that limit, so the hook ended before recording the new task and the previous task's duties stayed live. The cause was repeated work: the same text was analysed 20 times and one sub-check ran 295 times. Results are now reused within the run (identical output on 13,844 compared strings); in one development measurement the same prompt went from about 5.2 s to about 2.0 s under the same load — a single measurement, not a benchmark. The time limit itself is unchanged.
15
+ - **Fix: a prompt hook that runs out of time no longer leaves the previous task looking current.** If the hook still reaches its time limit after a new prompt of yours was accepted but before its task was recorded, it now records that the task switch did not finish. The stop check then blocks with "route publication incomplete" instead of judging your new prompt by the previous task's duties (or printing nothing), and the next prompt starts a new task. A standing stop order of yours is kept. Limits: the record is written only for a new prompt of yours that starts a task while a task that still owes evidence is current, outside a handoff run (a short reply that keeps the current task is left as it was); the time limit can only act between two steps of the hook, so if the host kills the hook during one long uninterrupted step, nothing is recorded and the behaviour is as in 3.5.6; if another write holds the state at that moment the record is skipped. Hint lines printed after a task is recorded can still be cut off between whole lines by a kill, as before.
16
+ - **Test fix: the router latency test measured machine load, not the hook.** The failure seen during the 3.5.6 release check was reproduced: with CPU load applied to only one of the two measured blocks, the old test fails (113 ms and 522 ms against a 100 ms limit) while every receipt still arrives. The paired test shipped in 3.5.6 holds under the same load (19–29 ms); its time limit is raised so heavy load cannot end it before its checks run. No check was loosened. Three more router tests had a time limit that measured the machine: two stopped the hook after 1 s to detect a hang (a healthy hook needs up to 0.9 s on a busy machine; a hook with the defect never exits, so the limit is now 10 s), and one killed the hook after a fixed 0.5 s and then expected its early record on disk (it now waits for the record, then kills). Each was shown to still fail on a deliberately broken hook.
17
+
5
18
  ## 3.5.6 - 2026-11-15
6
19
 
7
20
  Cleanup release: unused modules and flags removed, the `.ukit-new` files are gone, most design fonts moved out of the package, the two learning ideas rebuilt as one small, measured step, and an opt-in vector lane for index search. Every number below was measured on this repository only. No host (Claude Code, Codex, omp) was run live and nothing was run on Windows.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ukit",
3
- "version": "3.5.6",
3
+ "version": "3.5.7",
4
4
  "description": "Install/update an index-first AI workspace for Claude Code, OpenAI Codex and omp (Oh My Pi).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -143,6 +143,18 @@ export async function applyDiffResults(diffResults, { backupRoot, projectRoot, r
143
143
  entry.templateRender ?? entry.renderedContent,
144
144
  );
145
145
  for (const notice of entry.mergeNotices ?? []) {
146
+ if (notice.held) {
147
+ console.log(
148
+ `[UKit] ${path.basename(entry.targetPath)}: did not add the UKit section "${notice.heading}" because your file has an unclosed code fence (a line starting with \`\`\` or ~~~ that is never closed). Close it and run install again, or add the section by hand from the template.`,
149
+ );
150
+ continue;
151
+ }
152
+ if (notice.renamedTo) {
153
+ console.log(
154
+ `[UKit] ${path.basename(entry.targetPath)}: your section "${notice.heading}" was renamed to "${notice.renamedTo}" upstream; kept yours unchanged and did not add the new one. Merge them by hand if you want the new text.`,
155
+ );
156
+ continue;
157
+ }
146
158
  console.log(
147
159
  `[UKit] ${path.basename(entry.targetPath)}: kept your edited section "${notice.heading}"; the UKit template for it changed${packageVersion ? ` in ${packageVersion}` : ''}.`,
148
160
  );
@@ -3,7 +3,7 @@ import fs from 'node:fs/promises';
3
3
  import YAML from 'yaml';
4
4
  import { isSymlinkTo } from './fileOps.js';
5
5
  import { GATEWAY_RESILIENCE_ENV_DEFAULTS } from './gatewayResilienceEnv.js';
6
- import { mergeManagedTemplate, sectionHashes } from './managedTemplateMerge.js';
6
+ import { mergeManagedTemplate, recordFor, renamesFor } from './managedTemplateMerge.js';
7
7
  import { isOmpConfigTarget, mergeOmpConfig } from './ompConfigMerge.js';
8
8
  import { mergeOmpProjectConfig } from './ompProjectConfig.js';
9
9
  import { mergeRuntimeConfigText } from './runtimeConfigMerge.js';
@@ -46,7 +46,7 @@ async function resolveManagedTemplateAction(entry, recordedHashes, recordedSecti
46
46
  // ONLY a confirmed absence permits create; unreadable must never overwrite.
47
47
  return {
48
48
  ...entry, exists: false, action: 'create', existingContent: null, managedHash: templateHash,
49
- managedSections: sectionHashes(template.toString('utf8'), { markdown: /\.md$/i.test(entry.targetPath) }),
49
+ managedSections: recordFor(template.toString('utf8'), { markdown: /\.md$/i.test(entry.targetPath) }),
50
50
  };
51
51
  }
52
52
  if (read.status !== 'ok') {
@@ -56,7 +56,7 @@ async function resolveManagedTemplateAction(entry, recordedHashes, recordedSecti
56
56
  const installedHash = sha256(installed);
57
57
  const markdown = /\.md$/i.test(entry.targetPath);
58
58
  const templateText = template.toString('utf8');
59
- const managedSections = sectionHashes(templateText, { markdown });
59
+ const managedSections = recordFor(templateText, { markdown });
60
60
  if (installedHash === templateHash) {
61
61
  return { ...entry, exists: true, action: 'unchanged', existingContent: installed, managedHash: templateHash, managedSections };
62
62
  }
@@ -69,6 +69,7 @@ async function resolveManagedTemplateAction(entry, recordedHashes, recordedSecti
69
69
  template: templateText,
70
70
  recorded: recordedSections?.get(entry.targetPath) ?? null,
71
71
  markdown,
72
+ renames: renamesFor(entry.targetPath),
72
73
  });
73
74
  const base = { ...entry, exists: true, existingContent: installed, managedSections: merged.sections, mergeNotices: merged.notices };
74
75
  if (!merged.changed) {
@@ -68,24 +68,81 @@ export function sectionHashes(text, { markdown = true } = {}) {
68
68
 
69
69
  const trailingWs = (raw) => raw.slice(raw.trimEnd().length);
70
70
 
71
- export function mergeManagedTemplate({ existing, template, recorded = null, markdown = true }) {
71
+ // Record to store when the whole template was placed verbatim (create / unchanged / whole-file
72
+ // update): every key was really offered and placed, so the record is trusted (`@format: 2`).
73
+ export function recordFor(text, opts) {
74
+ return { ...sectionHashes(text, opts), '@format': '2' };
75
+ }
76
+
77
+ // Heading renames UKit ships, per managed file (matched by path suffix). Add an entry here in
78
+ // the same release that renames a heading in a managed template:
79
+ // { file: 'docs/AI_HANDOFF/<x>.md', renames: [{ from: '## Old', to: '## New', fromHashes: [...] }] }
80
+ // `fromHashes` = section hashes of every body ever shipped under the old heading: an old section
81
+ // whose hash is listed (or equals the recorded baseline) was never edited by the owner and is
82
+ // safe to rewrite or drop. Empty today: no shipped template has renamed a heading yet (the old
83
+ // `queued/README.md` headings only ever existed in this repo's own docs copy, never in a
84
+ // shipped template).
85
+ export const MANAGED_RENAMES = [];
86
+
87
+ export function renamesFor(targetPath) {
88
+ const p = String(targetPath).replace(/\\/g, '/');
89
+ return MANAGED_RENAMES.find((m) => p.endsWith(`/${m.file}`) || p === m.file)?.renames ?? [];
90
+ }
91
+
92
+ // A record is usable only if it is a plain object of string hashes; anything else (lost or
93
+ // corrupt) is "no record". Ack and marker keys live in the same map: they can never equal a
94
+ // `## ` heading key, so older UKit versions ignore them.
95
+ // `@format: 2` marks a record written by this merge. A record WITHOUT it (3.5.6 or older) still
96
+ // serves for the edited-vs-untouched decision, but not for "this key was already offered and
97
+ // placed": 3.5.6 recorded every template key, including one it skipped because its heading sat
98
+ // in a fence. For append decisions a legacy record is treated like no record.
99
+ const FORMAT_KEY = '@format';
100
+ const FORMAT = '2';
101
+ const ACK = (heading) => `@renamed ${heading}`;
102
+ const HELD = (heading) => `@held ${heading}`;
103
+ const validRecord = (r) => (r && typeof r === 'object' && !Array.isArray(r) && Object.values(r).every((v) => typeof v === 'string') && Object.keys(r).length > 0 ? r : null);
104
+
105
+ export function mergeManagedTemplate({ existing, template, recorded: rawRecorded = null, markdown = true, renames = [] }) {
72
106
  sectioned = markdown;
107
+ const recorded = validRecord(rawRecorded);
108
+ const trusted = recorded?.[FORMAT_KEY] === FORMAT; // written by this merge: key presence means "offered"
73
109
  const bom = existing.startsWith('');
74
110
  const eol = existing.includes('\r\n') ? '\r\n' : '\n';
75
111
  const existingLf = normalizeEol(existing.replace(/^/, ''));
76
112
  const templateSections = parseSections(normalizeEol(template.replace(/^/, '')));
77
113
  const tplByKey = new Map(templateSections.map((s) => [s.key, s]));
78
114
  const sections = Object.fromEntries(templateSections.map((s) => [s.key, hashOf(s.raw)]));
115
+ sections[FORMAT_KEY] = FORMAT;
79
116
  const notices = [];
117
+ const skipAppend = new Set(); // template keys already represented by a renamed owner section
118
+ const acks = new Set(); // old headings whose rename notice was already shown
80
119
 
81
120
  const parts = [];
82
121
  const existingSections = parseSections(existingLf);
122
+ const existingKeys = new Set(existingSections.map((s) => s.key));
83
123
  let removedTail = null;
84
124
  for (const [idx, e] of existingSections.entries()) {
85
125
  const t = tplByKey.get(e.key);
86
126
  const base = recorded?.[e.key];
87
- if (e.suspect) {
88
- parts.push({ key: e.key, raw: e.raw });
127
+ const ren = !e.suspect && !t ? renames.find((r) => r.from === e.key && tplByKey.has(r.to) && !tplByKey.has(r.from)) : null;
128
+ if (ren) {
129
+ const eh = hashOf(e.raw);
130
+ if (eh === base || (ren.fromHashes ?? []).includes(eh)) {
131
+ // Never edited by the owner: drop it if the new heading is already there, else rename in place.
132
+ if (existingKeys.has(ren.to)) {
133
+ if (idx === existingSections.length - 1) removedTail = trailingWs(e.raw);
134
+ } else {
135
+ parts.push({ key: ren.to, raw: tplByKey.get(ren.to).raw.trimEnd() + trailingWs(e.raw) });
136
+ }
137
+ } else {
138
+ // Owner-edited old section: keep it, never add the renamed one next to it, say so once.
139
+ skipAppend.add(ren.to);
140
+ acks.add(e.key);
141
+ if (recorded?.[ACK(e.key)] === undefined) notices.push({ heading: e.key, renamedTo: ren.to });
142
+ parts.push({ key: e.key, raw: e.raw });
143
+ }
144
+ } else if (e.suspect) {
145
+ parts.push({ key: e.key, raw: e.raw, suspect: true });
89
146
  } else if (t) {
90
147
  const eh = hashOf(e.raw);
91
148
  const th = sections[e.key];
@@ -111,18 +168,41 @@ export function mergeManagedTemplate({ existing, template, recorded = null, mark
111
168
  last.raw = last.raw.trimEnd() + removedTail;
112
169
  }
113
170
 
114
- const have = new Set(parts.map((p) => p.key));
115
- // Idempotence guard: a template section whose exact heading line already appears as ANY line
116
- // of the existing text (fenced or not) is never appended again. Fence pairing in an
117
- // owner-edited file is ambiguous: an owner's unclosed opener pairs with the first fence of a
118
- // template-added section's own code block, shifting every later pairing, so headings that sit
119
- // "inside closed fences" cannot be trusted to be quoted text. Fenced lines must therefore
120
- // count, otherwise the file grows on every run. Limit: a heading the owner merely quoted in a
121
- // code block blocks the real template section of that name.
122
- const existingLines = new Set(existingLf.split('\n').map((l) => l.trimEnd()));
171
+ // A suspect section (heading-shaped line after an unclosed fence) is not proof the template
172
+ // section is present: it is held below instead of counted.
173
+ const have = new Set(parts.filter((p) => !p.suspect).map((p) => p.key));
174
+ // Idempotence comes from RECORDED STATE, not from scanning the text: every template key that
175
+ // was ever merged is in `recorded`, and a recorded key is never appended again. That makes the
176
+ // result independent of how fences pair in an owner-edited file (unclosed fences cannot grow
177
+ // the file) and keeps a deliberately deleted section deleted. A heading the owner merely quoted
178
+ // in a code block therefore no longer blocks a new template section of that name.
179
+ // A key that is not recorded (no record, a lost/corrupt record, or a section new in this
180
+ // version) is appended, even if its heading is merely quoted in a CLOSED fence: the appended
181
+ // section parses as a real section next run, and its balanced fences cannot shift pairing.
182
+ // Only when the owner's file holds an UNCLOSED fence can an appended section's own fence pair
183
+ // with it, close it, and shift every later pairing (F1 growth, and a held section flipping to
184
+ // appended on run 2). So when such a section exists, NOTHING unrecorded is appended: each is
185
+ // HELD: removed from the recorded section hashes (so it is not recorded as present), and
186
+ // acked once under `@held <heading>` so the owner is told once and the notice is not repeated.
187
+ // When the owner closes the fence the key is no longer held and the next run appends it once.
188
+ const unclosed = fenceMap(existingLf.split('\n')).unclosedFrom !== undefined;
189
+ const existingLines = unclosed ? new Set(existingLf.split('\n').map((l) => l.trimEnd())) : null;
190
+ const offered = (key) => trusted && recorded[key] !== undefined;
191
+ const pending = (t) => t.key !== '' && !have.has(t.key) && !skipAppend.has(t.key) && !offered(t.key);
192
+ // If any pending section is held, hold every pending one: appending a sibling whose own fence
193
+ // closes the owner's unclosed opener would change the pairing and release the held one on run 2.
194
+ const holdAll = unclosed && templateSections.some((t) => pending(t) && existingLines.has(t.key.replace(/#\d+$/, '')));
123
195
  templateSections.forEach((t, i) => {
124
- if (have.has(t.key)) return;
125
- if (t.key !== '' && existingLines.has(t.key.replace(/#\d+$/, ''))) return;
196
+ if (have.has(t.key) || skipAppend.has(t.key)) return;
197
+ if (t.key !== '') {
198
+ if (offered(t.key)) return;
199
+ if (holdAll) {
200
+ if (recorded?.[HELD(t.key)] === undefined) notices.push({ heading: t.key, held: true });
201
+ delete sections[t.key];
202
+ sections[HELD(t.key)] = sha256(t.key);
203
+ return;
204
+ }
205
+ }
126
206
  let at = parts.length;
127
207
  for (let j = i - 1; j >= 0; j -= 1) {
128
208
  const idx = parts.findIndex((p) => p.key === templateSections[j].key);
@@ -139,6 +219,11 @@ export function mergeManagedTemplate({ existing, template, recorded = null, mark
139
219
  if (prev && prev.raw !== '' && !prev.raw.endsWith('\n\n')) prev.raw = `${prev.raw.trimEnd()}\n\n`;
140
220
  });
141
221
 
222
+ for (const h of acks) sections[ACK(h)] = sha256(h);
223
+ for (const r of renames) {
224
+ if (recorded?.[ACK(r.from)] !== undefined && have.has(r.from)) sections[ACK(r.from)] = sha256(r.from);
225
+ }
226
+
142
227
  const mergedLf = parts.map((p) => p.raw).join('');
143
228
  if (mergedLf === existingLf) return { content: existing, changed: false, notices, sections };
144
229
  const body = eol === '\r\n' ? mergedLf.replace(/\n/g, '\r\n') : mergedLf;
@@ -23,6 +23,7 @@ import path from 'node:path';
23
23
  import { fileURLToPath } from 'node:url';
24
24
 
25
25
  import { isRunAllRequest } from '../../template_project/.claude/ukit/runtime/handoff-intent.mjs';
26
+ import { isStandingPolicyPrompt } from '../../template_project/.claude/ukit/index/publication-intent.mjs';
26
27
  import { deriveEscalationTriggers, deriveRiskFloor } from './routeResolver.js';
27
28
 
28
29
  const PLAYBOOK_NAME_RE = /\.md$/i;
@@ -224,7 +225,7 @@ export const PLAYBOOK_ROUTING_TABLE = Object.freeze([
224
225
  fastPath: 'bug-fix',
225
226
  // T-026 review fix: a skill-ask that happens to mention a fix ("make this
226
227
  // repeated fix flow a skill") is skill-authoring, not a defect order.
227
- discriminator: (s) => !s.explanationAsk && !s.questionAsk && !s.forensicsSignal && !s.checkFirst && !s.skillAsk,
228
+ discriminator: (s) => !s.explanationAsk && !s.questionAsk && !s.forensicsSignal && !s.checkFirst && !s.skillAsk && !s.standingPolicy,
228
229
  },
229
230
  {
230
231
  workGroup: 'investigation',
@@ -398,6 +399,7 @@ function matchFirst(text, regexes) {
398
399
 
399
400
  async function buildRouteSignals({
400
401
  signalText,
402
+ rawPromptText = '',
401
403
  executionMode,
402
404
  escalationTriggers,
403
405
  projectRoot,
@@ -481,6 +483,8 @@ async function buildRouteSignals({
481
483
  // BL-026 review fix: ask to convert/author a skill — beats defect verbs in
482
484
  // the same sentence ("make this repeated fix flow a skill").
483
485
  skillAsk: SKILL_ASK_RE.test(signalText),
486
+ // A standing owner policy about bugs in general names no defect: it must not mint the bug-fix floor.
487
+ standingPolicy: isStandingPolicyPrompt(rawPromptText || signalText),
484
488
  };
485
489
  }
486
490
 
@@ -677,6 +681,7 @@ export async function resolvePlaybookId({
677
681
  ])];
678
682
  const signals = await buildRouteSignals({
679
683
  signalText,
684
+ rawPromptText: String(promptText || ''),
680
685
  executionMode,
681
686
  escalationTriggers: mergedTriggers,
682
687
  projectRoot,
@@ -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
  }
@@ -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;
@@ -2964,6 +3155,8 @@ function applyTaskSemantics(contract, semantic) {
2964
3155
  }
2965
3156
 
2966
3157
  function hasAdvisoryOnlyAssertion({ promptText = '', commandText = '' } = {}) {
3158
+ // A standing owner policy about bugs in general is advisory: no defect is named, nothing to repro.
3159
+ if (!String(commandText || '').trim() && isStandingPolicyPrompt(promptText)) return true;
2967
3160
  const folded = `${promptText ?? ''}\n${commandText ?? ''}`
2968
3161
  .toLowerCase()
2969
3162
  .normalize('NFD')
@@ -4486,7 +4679,36 @@ function applyTaskSemantics(contract, semantic) {
4486
4679
  }
4487
4680
  }
4488
4681
  let expectedRouteVersion;
4682
+ // Set only while a fresh owner prompt over an armed contract has not yet published (see the gate before
4683
+ // promptText); cleared once the provisional publication commits. Null = a kill behaves as before.
4684
+ let deadlineMarkerGate = null;
4685
+ deadlineHandler = async () => {
4686
+ const gate = deadlineMarkerGate;
4687
+ if (!gate || !sessionRoutePath) return;
4688
+ const lockModule = path.join(process.env.HOOK_DIR || path.join(projectRoot, '.claude', 'hooks'), '..', 'ukit', 'runtime', 'async-lock.mjs');
4689
+ const { withAsyncLock } = await import(pathToFileURL(lockModule).href);
4690
+ await withAsyncLock(sessionRoutePath, { deadlineMs: 300 }, async () => {
4691
+ // Same compare as persistRouteState: skip when the session route moved since this hook read it.
4692
+ // Compare against the version captured at gate time (never a fresh read, never the live
4693
+ // expectedRouteVersion that a committing publication advances): another process that published
4694
+ // since the gate, or our own publication having committed, makes this a skip.
4695
+ const bytes = await readRouteVersion();
4696
+ if (bytes !== gate.routeVersion || deadlineMarkerGate !== gate) return;
4697
+ let committedStop = null;
4698
+ try {
4699
+ const committed = bytes === null ? null : JSON.parse(bytes);
4700
+ if (committed?.ownerControl?.kind === 'stop' && committed.sessionId === sessionId) committedStop = committed.ownerControl;
4701
+ } catch {}
4702
+ await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({
4703
+ sessionId, taskInstanceId: gate.taskInstanceId, routeGeneration: gate.routeGeneration,
4704
+ routePersistenceRevision: crypto.randomUUID(), routePublicationIncomplete: true,
4705
+ ...(committedStop ? { ownerControl: committedStop } : {}),
4706
+ }));
4707
+ });
4708
+ };
4489
4709
  async function persistRouteState(text, recoveryOwner = null) {
4710
+ // After the deadline fired the only permitted write is the kill marker above.
4711
+ if (deadlineReached) throw new Error('hook deadline reached before route publication');
4490
4712
  if (sessionId) {
4491
4713
  // The lock primitive ships beside this hook; resolve it from the hook's own install dir so a
4492
4714
  // workspace whose runtime copy is absent/partial still takes the same lock (never unlocked).
@@ -4505,6 +4727,7 @@ function applyTaskSemantics(contract, semantic) {
4505
4727
  } else if (!handoffSkill && !handoffExpansion && await readRouteVersion() !== expectedRouteVersion) {
4506
4728
  throw new Error('session route changed before write');
4507
4729
  }
4730
+ if (deadlineReached) throw new Error('hook deadline reached before route publication');
4508
4731
  const persisted = await persistRouteStateLocked(text);
4509
4732
  expectedRouteVersion = await readRouteVersion();
4510
4733
  return persisted;
@@ -4606,6 +4829,7 @@ function applyTaskSemantics(contract, semantic) {
4606
4829
  const informationalTurn = !continuingTask && !semantic.statusReport
4607
4830
  && (semantic.taskKind === 'CODE_IMPLEMENTATION' || answerQuestion)
4608
4831
  && (isInformationalPrompt({ promptText: turnPrompt })
4832
+ || isStandingPolicyPrompt(turnPrompt)
4609
4833
  || isPureGreetingPrompt({ promptText: turnPrompt }));
4610
4834
  // A system-injected turn (wakeup / compaction summary) resumes the previous task; when that task holds
4611
4835
  // no contract (the owner's last turn was a question), the injected wording must not mint one: it was
@@ -4742,6 +4966,10 @@ function applyTaskSemantics(contract, semantic) {
4742
4966
  } catch { return null; }
4743
4967
  })();
4744
4968
  const markerControl = persisted.ownerControl ?? committedStop;
4969
+ // Re-check under the sidecar lock, right before the first write: if the kill marker already landed (or the
4970
+ // deadline fired) this publication must abort, never overwrite the marker. A publication that passed this
4971
+ // point has written its own pending marker first, so a hard exit mid-way still fails closed.
4972
+ if (deadlineReached) throw new Error('hook deadline reached before route publication');
4745
4973
  if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true, ...(markerControl ? { ownerControl: markerControl } : {}) }));
4746
4974
  try {
4747
4975
  await writeJsonFileAtomic(statePath, text);
@@ -5009,6 +5237,26 @@ function applyTaskSemantics(contract, semantic) {
5009
5237
  coordinationTurn = true;
5010
5238
  return false;
5011
5239
  }
5240
+ // Idle-session peer delivery (real host shape, host 2.1.322): queue-operation enqueue + dequeue (no
5241
+ // content/origin) then ONE meta user entry stamped origin.kind 'peer' / turnOrigin 'peer' /
5242
+ // promptSource 'system'. The hook payload prompt is the bare envelope block; the transcript entry
5243
+ // holds the host's banner line + block + one-paragraph trailer. The branch requires the same
5244
+ // session, the current turn (the assistant boundary above already cleared deliveryCurrent), the
5245
+ // prompt occurring exactly once in the entry text, only the known banner line (or nothing) before
5246
+ // it, and only a known single-line trailer (or nothing) after it. Any other extra text is not
5247
+ // proof. A human paste leaves origin.kind 'human' / promptSource 'typed' and never matches.
5248
+ if (deliveryCurrent && entry.isMeta === true && entry.promptSource === 'system' && entry.turnOrigin === 'peer'
5249
+ && entry.origin?.kind === 'peer' && sessionId && entry.sessionId === sessionId) {
5250
+ const at = text.indexOf(promptTrim);
5251
+ const before = at < 0 ? null : text.slice(0, at).trim();
5252
+ const after = at < 0 ? null : text.slice(at + promptTrim.length).trim();
5253
+ if (at >= 0 && text.indexOf(promptTrim, at + 1) < 0
5254
+ && (before === '' || before === 'Another Claude session sent a message:')
5255
+ && (after === '' || (!after.includes('\n') && /^(?:This came from another Claude session|That "other Claude session" is an agent)\b/.test(after)))) {
5256
+ coordinationTurn = true;
5257
+ return false;
5258
+ }
5259
+ }
5012
5260
  if (entry.isMeta === true && entry.turnOrigin === 'scheduled'
5013
5261
  && entry.promptSource === 'system' && entry.scheduledTaskId
5014
5262
  && entry.sessionId === sessionId && text === promptTrim
@@ -5016,6 +5264,9 @@ function applyTaskSemantics(contract, semantic) {
5016
5264
  coordinationTurn = true;
5017
5265
  return false;
5018
5266
  }
5267
+ // A peer-stamped record is delivery proof only inside this session; another session's record
5268
+ // (or a stale one) never exempts this prompt.
5269
+ if (entry.turnOrigin === 'peer' || entry.origin?.kind === 'peer') return false;
5019
5270
  return entry.isMeta === true && (entry.turnOrigin === 'scheduled' || entry.promptSource === 'system')
5020
5271
  && text === promptTrim;
5021
5272
  }
@@ -5427,6 +5678,14 @@ function applyTaskSemantics(contract, semantic) {
5427
5678
  : String(transcriptPathCandidate).trim() || null;
5428
5679
 
5429
5680
  const promptText = extractPrompt(payload);
5681
+ // Kill-marker gate: a fresh owner prompt (not a tool event, continuation, system turn, guidance or
5682
+ // handoff-bound task) over an armed previous contract. Past this point only the provisional publication
5683
+ // can replace that contract; a deadline kill before it commits must not leave the old contract live.
5684
+ if (!payload.tool_name && sessionId && promptText && !continuingTask && !systemOriginTurn && !guidanceTurn
5685
+ && !handoffExpansion && !handoffSkill && !previous.handoffRunId && previous.taskInstanceId && expectedRouteVersion !== undefined
5686
+ && previous.routeSummary?.executionContract?.completionEvidence?.length) {
5687
+ deadlineMarkerGate = { taskInstanceId: previous.taskInstanceId, routeGeneration: previous.routeGeneration || previous.taskInstanceId, routeVersion: expectedRouteVersion };
5688
+ }
5430
5689
  const commandText = payload.tool_input?.command || payload.command || '';
5431
5690
  const filePath = normalizeRelativeFile(projectRoot, payload.tool_input?.file_path || payload.file_path || '');
5432
5691
  const { buildRouteSignalText } = await loadLanguageTools(projectRoot);
@@ -5520,6 +5779,11 @@ function applyTaskSemantics(contract, semantic) {
5520
5779
  && !filePath;
5521
5780
 
5522
5781
  if (active.length === 0 || informationalNoTargetPrompt) {
5782
+ // This branch deliberately carries the previous contract forward (see the persist below), so a kill here
5783
+ // must not strand a marker that drops it. deliveryOnlyNoRoute drops the contract on its normal write, so the
5784
+ // gate stays armed there. With the gate null the deadline handler returns at once and the process exits in
5785
+ // the same microtask drain, before any pending import (the advisory below) can resume and print.
5786
+ if (previous?.routeSummary && !deliveryOnlyNoRoute) deadlineMarkerGate = null;
5523
5787
  const lastExplicitUserPromptText = promptText.trim()
5524
5788
  || previous?.routingContext?.lastExplicitUserPromptText
5525
5789
  || '';
@@ -5714,6 +5978,7 @@ function applyTaskSemantics(contract, semantic) {
5714
5978
  provisionalState.fingerprint = buildRouteStateFingerprint(provisionalState);
5715
5979
  await ensureDir(statePath);
5716
5980
  await persistRouteState(JSON.stringify(provisionalState));
5981
+ deadlineMarkerGate = null;
5717
5982
 
5718
5983
  let cacheUtils = null;
5719
5984
  if (await pathExists(cacheUtilsPath)) {
@@ -5970,6 +6235,9 @@ function applyTaskSemantics(contract, semantic) {
5970
6235
  process.stdout.write(`[ukit-skill-router] Helper: ${routeSummary.helperHint}\n`);
5971
6236
  }
5972
6237
  })().catch((error) => {
6238
+ // Once the self-deadline fired, only the deadline timer's own path (marker write, then exit; or the 400 ms
6239
+ // hard exit) may end the process or write to stdout: a refused publication here is the deadline, not a crash.
6240
+ if (deadlineReached) return;
5973
6241
  const detail = error?.message || String(error);
5974
6242
  process.stderr.write(`[ukit-skill-router] ${detail}\n`);
5975
6243
  // BUG-C23-07: a crashed router abandons configured routing work — announce the
@@ -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,
@@ -1,6 +1,6 @@
1
1
  // Canonical task semantics; intent never grants authorization or proves completion.
2
2
  import crypto from 'node:crypto';
3
- export const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:86afd8b71e068da6a63a85fcf003f79be262881f6c203fa44682853cf8acb4f7';
3
+ export const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:02b15877348961e92a6d682beeb94b0dde7e116fb2b2ba9b5c419147772732f8';
4
4
 
5
5
  export function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
6
6
  return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
@@ -23,7 +23,24 @@ export function compareSemanticContracts({ stored, fresh, previousIdentity, iden
23
23
  }
24
24
  const foldIntent = (text) => String(text).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
25
25
 
26
+ // The analysers are pure functions of their arguments but one hook run asks the same question about the same
27
+ // prompt dozens of times. Memoise per exact input (bounded, insertion-order eviction) and hand every caller its
28
+ // own structuredClone, so no caller can mutate the cache or another caller's result.
29
+ const SEMANTIC_MEMO_LIMIT = 16;
30
+ const memoCloned = (cache, key, compute) => {
31
+ const hit = cache.get(key);
32
+ if (hit !== undefined) return structuredClone(hit);
33
+ const value = compute();
34
+ if (cache.size >= SEMANTIC_MEMO_LIMIT) cache.delete(cache.keys().next().value);
35
+ cache.set(key, structuredClone(value));
36
+ return value;
37
+ };
38
+ const analyzeMemo = new Map();
26
39
  export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId = null, sessionId = null } = {}) {
40
+ return memoCloned(analyzeMemo, JSON.stringify([String(promptText), targetFile, taskInstanceId, sessionId]),
41
+ () => analyzeTaskIntentUncached({ promptText, targetFile, taskInstanceId, sessionId }));
42
+ }
43
+ function analyzeTaskIntentUncached({ promptText = '', targetFile = '', taskInstanceId = null, sessionId = null } = {}) {
27
44
  const original = String(promptText);
28
45
  const spans = [];
29
46
  let fence = null;
@@ -212,7 +229,11 @@ function classifyProhibitionItem(item, authorized, proper) {
212
229
  return null;
213
230
  }
214
231
 
232
+ const scopeMemo = new Map();
215
233
  export function publicationScope(promptText = '') {
234
+ return memoCloned(scopeMemo, String(promptText), () => publicationScopeUncached(promptText));
235
+ }
236
+ function publicationScopeUncached(promptText = '') {
216
237
  const plain = String(promptText).normalize('NFC')
217
238
  .replace(/\bdùng\b/giu, 'su dung').replace(/đừng/giu, 'khong')
218
239
  .replace(/(^|[\n;.]\s*)([ \t]*(?:[-*+•]|\d+[.)])?[ \t]*)dung(?=\s+(?:publish|release|npm|git|run|fix|sua)\b)/gi, '$1$2khong')
@@ -533,8 +554,139 @@ const OWNER_STOP_EN = /^(?:please\s+)?(?:stop|halt|pause|cancel|abort)(?:\s+(?:a
533
554
  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))*$/;
534
555
  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.-]+/;
535
556
  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/;
557
+ // A STANDING POLICY states how the owner wants bugs handled in general ("luôn nhớ: có bug là phải fix ngay",
558
+ // "always remember: any bug must be fixed immediately, at its root cause"). It names no defect, so it owes no
559
+ // repro/root-cause contract. CLOSED GRAMMAR: the prompt is split into clauses and returns true ONLY if EVERY
560
+ // non-empty clause, whole and anchored (^...$), is one of the enumerated forms below, and at least one clause is
561
+ // a defect rule. No clause is skipped (only clauses of pure whitespace/punctuation are empty), no clause passes
562
+ // by "all its words are in a set", and no script is exempt: text in any alphabet that matches no form is an
563
+ // order. Any doubt returns false (a real bug order keeps its full evidence duty; a wrong release is the worse
564
+ // error). Global rejects first: concrete referent (path/identifier/quote/version/URL/exit code), a symptom
565
+ // statement, a deictic aimed at a present defect, no policy marker anywhere. The splitter (SP_CLAUSE_SPLIT)
566
+ // cuts on punctuation/newline ONLY and never contains a letter, so no connector word is dropped unjudged;
567
+ // "và" exists only inside form RC. Clause forms (judged on raw NFC text, accents exact, see below):
568
+ // F1 MARK a marker phrase alone ("luôn nhớ", "from now on", "nguyên tắc của tôi")
569
+ // R1 [MARK] (có|thấy|gặp|phát hiện) DEF (là|thì) [phải|luôn] FIX ADV*
570
+ // R2 [MARK] mọi DEF [là|đều] phải FIX ADV*
571
+ // R3 [MARK] (any|every|each|all) DEF (must|should|shall|needs to|has to|gets) [be] FIX ADV*
572
+ // R4 [MARK] bare-plural-DEF (must|should|shall|get) [be] FIX ADV*
573
+ // 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)
574
+ // RC (R1|R2|R3|R4) và R6 (rule và purpose)
575
+ // R6 [phải] [tận root cause] để không (tái hiện|xảy ra|lặp lại) DEF nữa (purpose)
576
+ // F3 MARK [vẫn] là phải FIX ADV* (marker REQUIRED; no defect word, no scope word anywhere)
577
+ // 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)
578
+ // F4 fix [trên ukit] không phải chỉ để pass [thôi] [đâu] (negated purpose)
579
+ // F5 one fixed adverb phrase [nhé], or "nhé" alone ("ngay lập tức", "at its root cause", ...); reachable only after punctuation
580
+ // 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" ...)
581
+ // ADV* is ONE closed whole-phrase adverb (SP_PHRASE: "ngay lập tức", "triệt để", "at its root cause", ...),
582
+ // optionally followed by "nhé"; never a run of loose words.
583
+ // ACCENTS ARE NEVER FOLDED BEFORE MATCHING. The grammar is written once, in canonical accented spelling; spw()
584
+ // compiles each Vietnamese word to an exact alternation of (its fully unaccented form | its ONE canonical
585
+ // spelling). So "lập" and "lắp"/"lấp"/"lặp", "để" and "đè"/"đẻ", "thấy" and "thay"/"thầy", "nữa" and "nửa" are
586
+ // different words: an accented token that is not the canonical spelling matches nothing. A token with no
587
+ // diacritic still stands for the canonical word (unaccented typing keeps working). English words are ASCII
588
+ // literals, so "FİXED" or "fíx" match nothing. SP_CANONICAL lists every accented word the grammar uses.
589
+ const SP_FOLD = (s) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd');
590
+ const SP_ACCENTED = new Set();
591
+ const spw = (token) => {
592
+ const t = token.normalize('NFC');
593
+ const f = SP_FOLD(t);
594
+ if (f === t) return t;
595
+ SP_ACCENTED.add(t);
596
+ return `(?:${f}|${t})`;
597
+ };
598
+ const sp = (phrase) => phrase.trim().split(/\s+/).map(spw).join('\\s+');
599
+ const spAny = (...phrases) => `(?:${phrases.map(sp).join('|')})`;
600
+ const SP_DEF = `(?:bugs?|${sp('lỗi')}|defects?|crash(?:es)?|errors?|exceptions?|broken|regressions?|failures?|failing|fails?)`;
601
+ const SP_DEF_PLURAL = `(?:bugs|${sp('lỗi')}|defects|crashes|errors|exceptions|regressions|failures)`;
602
+ const SP_FIXV = `(?:fix|fixed|fixes|fixing|${sp('sửa')}|${sp('khắc phục')}|${sp('xử lý')}|resolved?)`;
603
+ // Adverbs are a closed list of whole PHRASES, never a run of words: one primary phrase, then optionally "nhé".
604
+ 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',
605
+ 'at its root cause', 'at the root cause', 'at its root', 'immediately', 'right away', 'at once', 'properly', 'fully', 'completely', 'thoroughly');
606
+ const SP_ADVRUN = `(?:\\s+${SP_PHRASE})?(?:\\s+${sp('nhé')})?`;
607
+ 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',
608
+ 'always remember', 'from now on', 'as a rule', 'my rule is', 'my policy is', 'my principle is')})(?:\\s+${sp('của tôi')})?`;
609
+ const SP_MARK_PFX = `(?:${SP_MARK}\\s+)?`;
610
+ // The enumerated clause forms (see the header comment). Every one is anchored at both ends. Connector words
611
+ // (và ...) exist ONLY inside the compound form RC below; the clause splitter never consumes a word.
612
+ 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}`;
613
+ 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}`;
614
+ 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}`;
615
+ const SP_R4 = `${SP_MARK_PFX}${SP_DEF_PLURAL}\\s+(?:must|should|shall|get)\\s+(?:be\\s+)?${SP_FIXV}${SP_ADVRUN}`;
616
+ 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')}`;
617
+ const SP_CLAUSE_FORMS = [
618
+ new RegExp(`^${SP_MARK}$`), // F1
619
+ new RegExp(`^${SP_R1}$`), // R1
620
+ new RegExp(`^${SP_R2}$`), // R2
621
+ new RegExp(`^${SP_R3}$`), // R3
622
+ new RegExp(`^${SP_R4}$`), // R4
623
+ 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
624
+ new RegExp(`^(?:${SP_R1}|${SP_R2}|${SP_R3}|${SP_R4})\\s+${sp('và')}\\s+${SP_R6}$`), // RC: rule và purpose (owner's P2)
625
+ new RegExp(`^${SP_R6}$`), // R6
626
+ new RegExp(`^${SP_MARK}\\s+(?:${sp('vẫn')}\\s+)?${sp('là phải')}\\s+${SP_FIXV}${SP_ADVRUN}$`), // F3 (marker required)
627
+ 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
628
+ 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
629
+ new RegExp(`^(?:${SP_PHRASE}(?:\\s+${sp('nhé')})?|${sp('nhé')})$`), // F5 (reachable only after punctuation)
630
+ 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
631
+ new RegExp(`^${sp('ukit là sản phẩm quan trọng')}$`), // V2
632
+ new RegExp(`^${sp('ukit hỗ trợ rất nhiều sản phẩm khác')}$`), // V3
633
+ ];
634
+ // Folded key -> canonical accented spelling(s). One spelling per word; a word with two legitimate tone
635
+ // placements would list both here and in the grammar.
636
+ export const SP_CANONICAL = {};
637
+ for (const w of [...SP_ACCENTED].sort()) (SP_CANONICAL[SP_FOLD(w)] ||= []).push(w);
638
+ // The splitter splits on punctuation/newline ONLY. It must never contain a letter: a word consumed by a
639
+ // splitter is discarded unjudged. (Asserted by a test.)
640
+ export const SP_CLAUSE_SPLIT = /[.!?;:\n,]+/;
641
+ // Forms that state a defect rule: at least one clause must be one of them (R1-R5 and RC).
642
+ const SP_RULE_FORM_COUNT = 7;
643
+ 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/;
644
+ 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/;
645
+ 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/;
646
+ const STANDING_POLICY_DEICTIC_ANYWHERE = /\b(?:the above|above|vua roi|hien tai|current(?:ly)?|dang|failing|following|ben tren|o tren)\b/;
647
+ export function isStandingPolicyPrompt(promptText = '') {
648
+ const raw = String(promptText ?? '').trim();
649
+ if (!raw || raw.length > 800 || STANDING_POLICY_CONCRETE.test(raw)) return false;
650
+ // The global rejects (marker present, no symptom, no deictic) are deliberately lenient and run on a folded
651
+ // copy; the clause forms below run on the RAW lowercase NFC text, where accents are exact. Nothing but
652
+ // Latin combining marks and "đ" is ever removed from the folded copy, and the raw text is what is judged.
653
+ const text = raw.toLowerCase().normalize('NFC').replace(/\s+/g, ' ');
654
+ const folded = SP_FOLD(text);
655
+ if (!STANDING_POLICY_MARKER.test(folded) || STANDING_POLICY_DEICTIC_ANYWHERE.test(folded) || STANDING_POLICY_SYMPTOM.test(folded)) return false;
656
+ const clauses = text.split(SP_CLAUSE_SPLIT);
657
+ let ruleClauses = 0;
658
+ for (const clause of clauses) {
659
+ const norm = clause.replace(/\s+/g, ' ').trim();
660
+ // Only a clause that is empty after whitespace/ASCII punctuation is skipped. Anything else (a letter or
661
+ // digit of any script, an emoji, a symbol) must match an enumerated form, else the prompt is not a policy.
662
+ if (!norm.replace(/[\s!-/:-@[-`{-~]/g, '')) continue;
663
+ const form = SP_CLAUSE_FORMS.findIndex((re) => re.test(norm));
664
+ if (form < 0) return false;
665
+ if (form >= 1 && form < SP_RULE_FORM_COUNT) ruleClauses += 1;
666
+ }
667
+ return ruleClauses > 0;
668
+ }
669
+
670
+ // A host-delivered peer (teammate/subagent/other-session) message: optional banner line, one or more CLOSED
671
+ // peer blocks, then nothing or (banner required) the host's own single-paragraph trailer, recognised by its
672
+ // stable lead words. Owner words anywhere else make it an owner prompt. A host wording change falls back to
673
+ // "not a peer prompt" (old routing), never to dropping owner text. Mirrors the early-exit check in skill-router.sh.
674
+ export function isPeerMessagePrompt(promptText = '') {
675
+ const text = String(promptText ?? '').trim();
676
+ const banner = /^Another Claude session sent a message:[ \t]*\r?\n/i;
677
+ const bannered = banner.test(text);
678
+ let rest = text.replace(banner, '').trim();
679
+ const peerBlock = /^<(agent-message|teammate-message|cross-session-message)(?:\s[^>]*)?>[\s\S]*?<\/\1>\s*/;
680
+ let blocks = 0;
681
+ for (let m = peerBlock.exec(rest); m; m = peerBlock.exec(rest)) { rest = rest.slice(m[0].length); blocks += 1; }
682
+ 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;
683
+ return blocks > 0 && (rest === '' || (bannered && trailer.test(rest.trim())));
684
+ }
685
+
536
686
  export function classifyOwnerControl(promptText = '') {
537
687
  const raw = String(promptText ?? '').normalize('NFC').trim();
688
+ // Text shape is never provenance here: an envelope-first/banner-first text already yields kind null because
689
+ // OWNER_STOP_EN/VI are anchored on the first lead (proved 0 diffs vs the former isPeerMessagePrompt guard).
538
690
  if (!raw || OWNER_CONTROL_HOOK_TEXT.test(raw)) return { kind: null };
539
691
  const stripped = raw.replace(/^[\s*#_-]+/, '');
540
692
  if (/^[>"'`\u201c\u2018]/.test(stripped)) return { kind: null };
@@ -726,7 +878,13 @@ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
726
878
  const cronOperation = actionable.some((clause) => /\b(?:delete|remove|cancel|xoa|huy|ensure|dam bao)\b/.test(clause)
727
879
  && /\bcron\b|scheduled\s+(?:cron\s+)?(?:task|job)|tac vu\s+(?:cron|dinh ky)/.test(clause))
728
880
  && (!codeChangeVerb || hasOperationId);
881
+ // Pure per clause and asked once by runtimeClause and once by gitClause for every clause; compute each clause once.
882
+ const operationNotOrderedMemo = new Map();
729
883
  const operationNotOrdered = (clause) => {
884
+ if (!operationNotOrderedMemo.has(clause)) operationNotOrderedMemo.set(clause, operationNotOrderedUncached(clause));
885
+ return operationNotOrderedMemo.get(clause);
886
+ };
887
+ const operationNotOrderedUncached = (clause) => {
730
888
  const OP = '(?:restart|redeploy|deploy(?:ment)?|trien khai|khoi dong lai|git\\s+push|push\\s+(?:to\\s+)?origin|commit|push)';
731
889
  const BAN = '(?:bi\\s+(?:cam|chan)|forbidden|prohibited|banned|not\\s+allowed|not\\s+permitted|disallowed)';
732
890
  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;
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { classifyTaskSemantics, applyTaskSemantics } from './route-resolver.mjs';
3
- import { semanticContractIdentity, ordersAdditiveChange } from './publication-intent.mjs';
3
+ import { semanticContractIdentity, ordersAdditiveChange, isStandingPolicyPrompt } from './publication-intent.mjs';
4
4
  import fs from 'node:fs/promises';
5
5
  // `fsSync` aliases the SAME fs module — used ONLY by the process.on('exit')
6
6
  // audit-sidecar fold below (event loop is gone; async cannot run) and by the
@@ -2113,6 +2113,15 @@ async function appendPerQuestionShadowReceipts({
2113
2113
  * every failure degrades to a receipt with outcomeClass 'unavailable' —
2114
2114
  * never throws, never blocks the route.
2115
2115
  */
2116
+ // A spawnSync that hit its `timeout` was killed (error.code ETIMEDOUT, signal
2117
+ // SIGTERM): the adapter started but ran past its deadline. Label it with the
2118
+ // decision plane's own timeout code ('deadline-exceeded', same as client.js /
2119
+ // unic-decision.mjs) instead of claiming it could not start. Everything else
2120
+ // (spawn error, non-zero exit, empty stdout) stays 'adapter-spawn-failed'.
2121
+ function spawnFailureCode(spawned) {
2122
+ return spawned?.error?.code === 'ETIMEDOUT' ? 'deadline-exceeded' : 'adapter-spawn-failed';
2123
+ }
2124
+
2116
2125
  export async function runRouteDecisionShadow({
2117
2126
  rootDir = process.cwd(),
2118
2127
  config = null,
@@ -2232,7 +2241,7 @@ export async function runRouteDecisionShadow({
2232
2241
  if (spawned && !spawned.error && spawned.status === 0 && spawned.stdout) {
2233
2242
  result = JSON.parse(spawned.stdout);
2234
2243
  } else {
2235
- result = { status: 'unavailable', fallbackCode: 'adapter-spawn-failed' };
2244
+ result = { status: 'unavailable', fallbackCode: spawnFailureCode(spawned) };
2236
2245
  }
2237
2246
  } catch {
2238
2247
  result = { status: 'unavailable', fallbackCode: 'adapter-spawn-failed' };
@@ -2349,7 +2358,7 @@ async function askUnicDecisionBatch({
2349
2358
  if (spawned && !spawned.error && spawned.status === 0 && spawned.stdout) {
2350
2359
  return JSON.parse(spawned.stdout);
2351
2360
  }
2352
- return { status: 'unavailable', fallbackCode: 'adapter-spawn-failed', answers: [] };
2361
+ return { status: 'unavailable', fallbackCode: spawnFailureCode(spawned), answers: [] };
2353
2362
  } catch {
2354
2363
  return { status: 'unavailable', fallbackCode: 'adapter-spawn-failed', answers: [] };
2355
2364
  }
@@ -4724,6 +4733,8 @@ function isInformationalPrompt({
4724
4733
  // a bare "không biết…chưa" uncertainty is NOT an assertion and stays on the
4725
4734
  // plain question path.
4726
4735
  function hasAdvisoryOnlyAssertion({ promptText = '', commandText = '' } = {}) {
4736
+ // A standing owner policy about bugs in general is advisory: no defect is named, nothing to repro.
4737
+ if (!String(commandText || '').trim() && isStandingPolicyPrompt(promptText)) return true;
4727
4738
  const folded = `${promptText ?? ''}\n${commandText ?? ''}`
4728
4739
  .toLowerCase()
4729
4740
  .normalize('NFD')
@@ -26,6 +26,12 @@ import { withAsyncLock } from './async-lock.mjs';
26
26
  // the SAME selector filters the completion and blocked predicates below. Sandbox
27
27
  // runtimes that copy this file by an explicit sibling list must copy this module too.
28
28
  import { selectTaskScope } from './handoff-task-scope.mjs';
29
+ // Peer-message recogniser: ONE shared implementation (index/publication-intent.mjs). Loaded fail-open — a runtime
30
+ // without that sibling degrades to "never a peer prompt" (old behaviour), it must not break the Stop hook import.
31
+ let isPeerMessagePrompt = () => false;
32
+ try {
33
+ ({ isPeerMessagePrompt } = await import('../index/publication-intent.mjs'));
34
+ } catch { /* degrade: peer text then counts as user text, as before */ }
29
35
  // PreToolUse block-breaker cause matching for stop reconciliation — advisory and
30
36
  // fail-open: a missing/corrupt breaker module degrades to "no match" (a block then
31
37
  // stays a block; nothing is released), never to a changed stop verdict.
@@ -2614,6 +2620,11 @@ const RESUME_COMMAND_TAG = /^<command-name>\/?(?:ukit:)?handoff-(?:fullstack|imp
2614
2620
 
2615
2621
  function genuineUserText(entry) {
2616
2622
  if (!entry || entry.type !== 'user' || entry.isSidechain === true || entry.isMeta === true) return null;
2623
+ // Host stamps beat text shape: a peer-stamped entry is never the owner; an entry the host stamped as human
2624
+ // (origin.kind 'human' / promptSource 'typed') is the owner even if the text looks like a peer envelope.
2625
+ // Only an UNSTAMPED entry falls back to the envelope-shape check below.
2626
+ if (entry.origin?.kind === 'peer' || entry.turnOrigin === 'peer') return null;
2627
+ const hostStampedHuman = entry.origin?.kind === 'human' || entry.promptSource === 'typed';
2617
2628
  const msg = entry.message;
2618
2629
  if (!msg || msg.role !== 'user') return null;
2619
2630
  let text = '';
@@ -2629,7 +2640,7 @@ function genuineUserText(entry) {
2629
2640
  return null;
2630
2641
  }
2631
2642
  text = text.trim();
2632
- if (!text || SYNTHETIC_USER_PREFIX.test(text)) return null;
2643
+ if (!text || SYNTHETIC_USER_PREFIX.test(text) || (!hostStampedHuman && isPeerMessagePrompt(text))) return null;
2633
2644
  return text;
2634
2645
  }
2635
2646