@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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,34 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.5.8 - 2026-11-16
6
+
7
+ Bug-fix release: one defect seen right after 3.5.7 shipped, 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 (prompt router, evidence recorder, Stop gate) in a temporary project.
8
+
9
+ - **Fix: asking how the work is going is no longer treated as an order to change code.** A prompt such as "Chạy có vẻ lâu rồi nè, không biết có tiến triển gì không … nếu có tiến triển thì tiếp tục làm, nếu lặp lại vô nghĩa thì báo tôi" was routed as a code task, and when it arrived after the task had finished, the Stop gate refused a correct progress report and asked for an edit and a test run. Two things caused it and both are fixed:
10
+ - The Vietnamese syllables "triển" and "khai" on their own were expanded to implement/build/ship, so "tiến triển" (progress) selected the delivery skill. Only the full words are expanded now: "triển khai" (implement/deploy/ship), "phát triển" (develop/build), "khai báo" (declare).
11
+ - "chạy", "tạo" and "cài/cải" counted as orders wherever they appeared. They now count only in an order position — with an object or an imperative particle ("chạy lại test", "tạo file x", "cài lodash đi") — and not as a description ("chạy có vẻ lâu rồi", "đang chạy", "mục tiêu của tạo ra UKit là cải tiến …"). In English, a change word used as a noun after the/a/this/my/… ("How is the progress on the build?", "Any update on the fix?") is no longer an order either; "fix the build", "run the build and fix failures", "do that update now" and "do the fix" behave as in 3.5.7. Delete/remove words are never softened.
12
+ - **Fix: "tiếp tục …" with a remark attached keeps the running task.** "tiếp tục. không dừng, nhớ check cái idle cho tôi" or "nếu có tiến triển thì tiếp tục làm, …" sent while a task was in flight started a new task and parked the running one's obligations. A continuation clause inside a longer prompt now binds to the live task, the same as a bare "tiếp tục". It never revives a parked task, and it does not apply when any part of the prompt orders something: "tiếp tục, push luôn", "tiếp tục, commit đi" or "nếu ok thì push rồi tiếp tục" start a new task with the checks that order needs, as in 3.5.7.
13
+ - **Known limits, not fixed here.**
14
+ - Some plain statements that order nothing ("Đã làm phải có hiệu quả.") still print a code-task route line, because the classifier's default kind is "code change". The Stop gate does not demand an edit for them when nothing was ordered and nothing was written.
15
+ - Some English questions whose change word is not behind the/a/this/… as a noun — "did you get the build?", "when did you start the build?" — are still read as an order, and the Stop gate asks for edit and test evidence, exactly as in 3.5.7.
16
+ - "để chạy test" on its own is not counted as an order (the purpose-clause rule strips it) although it still owes test evidence; "tiếp tục push lên main" written as one clause starts a new task that asks for edit evidence instead of push evidence. Both behave exactly as in 3.5.7.
17
+ - A noun that is also an operation word ("cái tag v3.5.7", "release notes", "giá đang lên") after "tiếp tục," starts a new task instead of continuing — the same result as 3.5.7, and it never drops an obligation.
18
+ - A prompt with no skill match can still be labelled a broader edit mode than it deserves (a tie between zero scores is pushed upward); the routed and the no-route paths use two slightly different "is this informational" checks.
19
+
20
+ ## 3.5.7 - 2026-11-16
21
+
22
+ 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.
23
+
24
+ - **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.
25
+ - **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.
26
+ - **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.
27
+ - **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.
28
+ - **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.
29
+ - **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.
30
+ - **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.
31
+ - **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.
32
+
5
33
  ## 3.5.6 - 2026-11-15
6
34
 
7
35
  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.8",
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;
@@ -6,6 +6,11 @@ const GENERIC_STOPWORDS = new Set([
6
6
  ]);
7
7
 
8
8
  const VIETNAMESE_PHRASE_ALIASES = [
9
+ // Bigrams only: the unigrams "trien"/"khai" also fold "tiến triển" (progress) / "khai" in unrelated
10
+ // words onto implement/build/ship, which selected the delivery skill for progress questions (3.5.8).
11
+ { regex: /\btrien khai\b/gu, expansions: ['implement', 'deploy', 'ship'] },
12
+ { regex: /\bphat trien\b/gu, expansions: ['develop', 'build'] },
13
+ { regex: /\bkhai bao\b/gu, expansions: ['declare'] },
9
14
  { regex: /\bbo nho dem\b/gu, expansions: ['cache'] },
10
15
  { regex: /\bduong dan\b/gu, expansions: ['route', 'path'] },
11
16
  { regex: /\bxac thuc\b/gu, expansions: ['auth', 'authentication'] },
@@ -78,8 +83,6 @@ const VIETNAMESE_TOKEN_ALIASES = new Map([
78
83
  ['component', ['component']],
79
84
  ['test', ['test', 'testing']],
80
85
  ['soat', ['review', 'audit']],
81
- ['trien', ['implement', 'build', 'ship']],
82
- ['khai', ['implement', 'build', 'ship']],
83
86
  ['kho', ['store', 'storage']],
84
87
  ['ghi', ['write', 'record']],
85
88
  ['doc', ['read']],
@@ -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
  }
@@ -1017,7 +1017,9 @@ function isInformationalPrompt({
1017
1017
  }
1018
1018
  // C85-019: consult-shape also overrides the vocabulary vetoes — the
1019
1019
  // mutation/debug/lỗi words are the question's SUBJECT, not the ask.
1020
- 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);
1020
+ // chạy/tạo/cài are judged by the shared position rule (ambiguousVerbOrder), not by bare presence.
1021
+ 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))
1022
+ || ambiguousVerbOrder(raw);
1021
1023
  if (implementWords && !consultShape) return false;
1022
1024
  const investigationWords = /\b(why|debug|triage|root cause|investigate|tại sao)\b/.test(raw);
1023
1025
  if (investigationWords && !consultShape) return false;
@@ -1211,7 +1213,51 @@ export function classifyAdvisorRequest({ promptText = '', commandText = '' } = {
1211
1213
  // folding, so "Cái này là gì, tại sao…" is not read as an install order (3.4.81 telemetry audit).
1212
1214
  function maskTonedNonVerbs(text = '') {
1213
1215
  return String(text ?? '').normalize('NFC')
1214
- .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, ' _ ');
1216
+ .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, ' _ ');
1217
+ }
1218
+ // Position rule for the closed set of verbs that tone-fold onto an order verb but are ordinary
1219
+ // aspect/nominal words in progress talk: ch\u1ea1y (run / is running), t\u1ea1o (create / the creation of),
1220
+ // c\u1ea3i/c\u00e0i (improve / install). Input is folded (accent-free, lowercase) text. A verb is an ORDER when it
1221
+ // has an object or an imperative particle; it is NOT an order after a nominaliser/preposition/copula/
1222
+ // aspect marker (PREV = cua, viec, su, khi, dang) or when only a stative/degree complement follows
1223
+ // (co ve + lau, mai, hoai, cham, nhanh, xong, roi, duoc, qua, rat, hoi, ne, then end of clause or a conjunction).
1224
+ // Imperative particles (di, luon, ngay, giup, gium, ho, nhe) within 3 tokens always keep it an order.
1225
+ // Non-orders become " _ "; orders are untouched. English: a mutation word right after a determiner/possessive is
1226
+ // a noun ("the build"), unless a light verb stands before the determiner ("do the build", "finish that update").
1227
+ // Destructive verbs (x\u00f3a, delete, drop, reset) are deliberately not in this set.
1228
+ // Three copies (taskRouting.js, route-task.mjs, skill-router.sh) \u2014 keep them identical.
1229
+ function softenEnglishNouns(text = '') {
1230
+ 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 _ ');
1231
+ }
1232
+ function softenAmbiguousVerbs(folded = '') {
1233
+ const PREV = new Set(['cua', 'viec', 'su', 'khi', 'dang']);
1234
+ const PARTICLE = new Set(['di', 'luon', 'ngay', 'giup', 'gium', 'ho', 'nhe']);
1235
+ const COMPLEMENT = new Set(['lau', 'mai', 'hoai', 'cham', 'nhanh', 'xong', 'roi', 'duoc', 'qua', 'rat', 'hoi', 'ne']);
1236
+ const CONJ = new Set(['ma', 'nhung', 'va', 'thi', 'hay', 'nen', 'khong', 'chua', 'but', 'and', 'so']);
1237
+ // Each occurrence is judged on its own (a clause can hold several: "tạo ra Ukit là cải tiến ...").
1238
+ // English: a mutation token right after a determiner/possessive is a noun ("the build", "my fix"), never an
1239
+ // order. Only that token is softened, so "run the build" / "fix the build" still order through the verb.
1240
+ // delete/remove are never softened.
1241
+ return softenEnglishNouns(folded).replace(/\b(chay|tao|cai)\b/g, (match, verb, offset, whole) => {
1242
+ const prev = whole.slice(0, offset).trimEnd().split(/\s+/).pop() || '';
1243
+ const tokens = (whole.slice(offset + match.length).split(/[.,;!?\n]/)[0] || '').split(/\s+/).filter(Boolean);
1244
+ if (tokens.slice(0, 3).some((token) => PARTICLE.has(token))) return match;
1245
+ if (PREV.has(prev)) return ' _ ';
1246
+ let index = 0;
1247
+ let consumed = 0;
1248
+ while (index < tokens.length) {
1249
+ if (tokens[index] === 'co' && tokens[index + 1] === 've') { index += 2; consumed += 1; continue; }
1250
+ if (COMPLEMENT.has(tokens[index])) { index += 1; consumed += 1; continue; }
1251
+ break;
1252
+ }
1253
+ if (consumed > 0 && (index >= tokens.length || CONJ.has(tokens[index]))) return ' _ ';
1254
+ return match;
1255
+ });
1256
+ }
1257
+ // The shared predicate: does any ambiguous verb in this text still stand as an order?
1258
+ function ambiguousVerbOrder(text = '') {
1259
+ const folded = maskTonedNonVerbs(text).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/\u0111/g, 'd');
1260
+ return /\b(?:chay|tao|cai)\b/.test(softenAmbiguousVerbs(folded));
1215
1261
  }
1216
1262
  function hasMutationOrder({ promptText = '', commandText = '' } = {}) {
1217
1263
  const folded = `${maskTonedNonVerbs(promptText)}\n${commandText ?? ''}`
@@ -1219,7 +1265,7 @@ function hasMutationOrder({ promptText = '', commandText = '' } = {}) {
1219
1265
  .normalize('NFD')
1220
1266
  .replace(/[\u0300-\u036f]/g, '')
1221
1267
  .replace(/\u0111/g, 'd');
1222
- const trimmed = folded.trim();
1268
+ const trimmed = softenAmbiguousVerbs(folded.trim());
1223
1269
  if (!trimmed) return false;
1224
1270
  // C85-019c: clause strips must stop BEFORE a conjunction-joined imperative
1225
1271
  // — "giữ nguyên header và sửa lỗi login" keeps 'và sửa lỗi' as a surviving