@ngockhoale/ukit 3.4.75 → 3.4.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ukit",
3
- "version": "3.4.75",
3
+ "version": "3.4.76",
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",
@@ -36,6 +36,14 @@
36
36
  "!scripts/measure-decision-gateway.mjs",
37
37
  "!scripts/probe/codex-capability-probe.mjs",
38
38
  "!scripts/install/generate-semantic-engine.mjs",
39
+ "!scripts/install/sync-installed-mirror.mjs",
40
+ "!scripts/test/run-handoff-isolated.mjs",
41
+ "!scripts/docs/render-instructions.mjs",
42
+ "!scripts/index/build-index.mjs",
43
+ "!scripts/index/query-index.mjs",
44
+ "!scripts/index/refresh-index.mjs",
45
+ "!scripts/bug/triage.mjs",
46
+ "!scripts/skill/audit-skill.mjs",
39
47
  "!scripts/release/progress-reporter.mjs",
40
48
  "!scripts/release/publish-guard-core.mjs",
41
49
  "!scripts/audit/c100/attribution-gap.mjs",
@@ -51,10 +59,9 @@
51
59
  "template_user/",
52
60
  "!template_project/**/.smbdelete*",
53
61
  "!template_project/.smbdelete*",
62
+ "!template_project/.ukit/**",
63
+ "!template_project/**/skill-router-state.json",
54
64
  "CHANGELOG.md",
55
- "LICENSE",
56
- "template_project/CLAUDE.md",
57
- "template_project/AGENTS.md",
58
65
  "template_project/.gitignore",
59
66
  "manifests/"
60
67
  ],
@@ -0,0 +1,15 @@
1
+ import { migrateMarkerStore } from '../../core/markerStoreMigration.js';
2
+
3
+ export async function runMarkerStore({ projectRoot, argv = [] }) {
4
+ if (argv[0] !== 'migrate' || argv.includes('--help')) {
5
+ console.log('Usage: ukit marker-store migrate [--apply --writers-stopped]');
6
+ console.log('');
7
+ console.log('Plan (default) or apply the OMP bridge UNKNOWN marker-store migration. Apply needs --writers-stopped');
8
+ console.log('(you closed every OMP/bridge session of this project); UKit verifies, refuses when unverifiable,');
9
+ console.log('never kills processes and keeps the original store in a quarantine directory.');
10
+ return;
11
+ }
12
+ const result = await migrateMarkerStore({ projectRoot, apply: argv.includes('--apply'), attestWritersStopped: argv.includes('--writers-stopped') });
13
+ console.log(JSON.stringify(result, null, 2));
14
+ if (!result.ok) process.exitCode = 2;
15
+ }
package/src/cli/index.js CHANGED
@@ -14,6 +14,7 @@ import { runPlaybook } from './commands/playbook.js';
14
14
  import { runDecision } from './commands/decision.js';
15
15
  import { runSelfImproveCommand } from './commands/selfImprove.js';
16
16
  import { runVm } from './commands/vm.js';
17
+ import { runMarkerStore } from './commands/markerStore.js';
17
18
  const GLOBAL_FLAGS = new Set(['--help', '-h', '--version', '-v']);
18
19
 
19
20
  export async function runCli({ argv, packageRoot, projectRoot, packageVersion }) {
@@ -106,6 +107,11 @@ export async function runCli({ argv, packageRoot, projectRoot, packageVersion })
106
107
  return;
107
108
  }
108
109
 
110
+ if (command === 'marker-store') {
111
+ await runMarkerStore({ projectRoot, argv: commandArgv });
112
+ return;
113
+ }
114
+
109
115
  if (command === 'vm') {
110
116
  await runVm({ projectRoot, argv: commandArgv });
111
117
  return;
@@ -145,6 +151,7 @@ export async function runCli({ argv, packageRoot, projectRoot, packageVersion })
145
151
  console.log(' feedback Record or list wrong-route feedback labels');
146
152
  console.log(' self-improve Run the automatic learn/tune/collect pass now (hooks run it)');
147
153
  console.log(' vm Agent VM driver (list/show/status/shadow-run/evidence)');
154
+ console.log(' marker-store Plan/apply the OMP bridge UNKNOWN marker-store migration (refuses unless writers are verified stopped)');
148
155
  console.log(' update Upgrade the global UKit CLI to the latest version');
149
156
  console.log(' version Show UKit version');
150
157
  console.log('');
@@ -0,0 +1,122 @@
1
+ // Migration of the OMP bridge UNKNOWN repeat-marker store (.ukit/storage/cache/omp-bridge-unknown-markers).
2
+ // Writers are bridge processes with no registry/lock, so a rewrite is only allowed when the owner attests the old
3
+ // writers are stopped AND this tool finds no process with the project as cwd and an unchanged store. Otherwise it
4
+ // refuses. Never kills processes, never deletes: the original store is renamed to a quarantine directory.
5
+ // Every block marker becomes a sticky release marker (a dead writer's block would only ever release on repeat);
6
+ // release markers are kept byte-for-byte, so STOP, session and task isolation (hashed names) are untouched.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import crypto from 'node:crypto';
10
+ import { spawnSync } from 'node:child_process';
11
+
12
+ export const STORE_REL = path.join('.ukit', 'storage', 'cache', 'omp-bridge-unknown-markers');
13
+ const NAME = /^([0-9a-f]{64})\.([0-9a-f]{64})\.(block|release)$/;
14
+ const refuse = (reason, extra = {}) => ({ ok: false, reason, ...extra });
15
+
16
+ export function scanStore(store) {
17
+ const entries = [];
18
+ const invalid = [];
19
+ for (const name of fs.readdirSync(store)) {
20
+ const m = NAME.exec(name);
21
+ let body = null;
22
+ try { body = JSON.parse(fs.readFileSync(path.join(store, name), 'utf8')); } catch { /* invalid */ }
23
+ const ok = m && body && body.v === 2 && typeof body.p === 'string' && Number.isInteger(body.k);
24
+ if (ok) entries.push({ name, kind: m[3], stem: `${m[1]}.${m[2]}`, text: fs.readFileSync(path.join(store, name), 'utf8') });
25
+ else invalid.push(name);
26
+ }
27
+ return { entries, invalid };
28
+ }
29
+
30
+ // Processes (other than this one) whose cwd is inside the project. null = could not be enumerated.
31
+ export function liveProjectProcesses(projectRoot) {
32
+ const root = fs.realpathSync(projectRoot);
33
+ const inside = (cwd) => cwd === root || cwd.startsWith(root + path.sep);
34
+ const found = [];
35
+ try {
36
+ if (process.platform === 'linux') {
37
+ for (const pid of fs.readdirSync('/proc').filter((n) => /^\d+$/.test(n) && Number(n) !== process.pid)) {
38
+ try { if (inside(fs.readlinkSync(`/proc/${pid}/cwd`))) found.push(pid); } catch { /* exited or not ours */ }
39
+ }
40
+ return found;
41
+ }
42
+ if (process.platform === 'win32') return null;
43
+ const ps = spawnSync('ps', ['-axo', 'pid=,command='], { encoding: 'utf8', timeout: 20000 });
44
+ if (ps.error || ps.status !== 0) return null;
45
+ for (const line of ps.stdout.split('\n')) {
46
+ const m = /^\s*(\d+)\s+(.*)$/.exec(line);
47
+ if (m && Number(m[1]) !== process.pid && Number(m[1]) !== process.ppid && m[2].includes(root) && !m[2].includes('marker-store')) found.push(m[1]);
48
+ }
49
+ const r = spawnSync('lsof', ['-a', '-d', 'cwd', '-Fpn'], { encoding: 'utf8', timeout: 20000 });
50
+ if (r.error || !r.stdout) return null;
51
+ let pid = '';
52
+ for (const line of r.stdout.split('\n')) {
53
+ if (line[0] === 'p') pid = line.slice(1);
54
+ else if (line[0] === 'n' && Number(pid) !== process.pid && Number(pid) !== process.ppid && inside(line.slice(1))) found.push(pid);
55
+ }
56
+ return found;
57
+ } catch { return null; }
58
+ }
59
+
60
+ const fingerprint = (store) => crypto.createHash('sha256').update(fs.readdirSync(store).sort().map((n) => {
61
+ const s = fs.statSync(path.join(store, n));
62
+ return `${n}:${s.size}:${s.mtimeMs}`;
63
+ }).join('\n')).digest('hex');
64
+
65
+ export async function migrateMarkerStore({ projectRoot, apply = false, attestWritersStopped = false, observeMs = 2000, hooks = {} }) {
66
+ const store = path.join(projectRoot, STORE_REL);
67
+ const journal = `${store}.migration.json`;
68
+ const stat = fs.existsSync(store) ? fs.statSync(store) : null;
69
+ const pending = fs.existsSync(journal) ? JSON.parse(fs.readFileSync(journal, 'utf8')) : null;
70
+ if (!pending && !stat) return { ok: true, status: 'no-store' };
71
+ if (!pending && !stat.isDirectory()) return refuse('marker store path is not a directory');
72
+
73
+ const plan = !pending ? scanStore(store) : { entries: [], invalid: [] };
74
+ const blocks = plan.entries.filter((e) => e.kind === 'block').length;
75
+ const summary = { releases: plan.entries.length - blocks, blocks, invalid: plan.invalid.length, tempFiles: plan.invalid.filter((n) => n.includes('.tmp-')).length };
76
+ if (!pending && blocks === 0 && plan.invalid.length === 0) return { ok: true, status: 'already-migrated', ...summary };
77
+ if (!apply) return { ok: true, status: 'plan', ...summary };
78
+
79
+ if (!attestWritersStopped) return refuse('owner attestation missing: close every OMP/bridge session that uses this project, then pass --writers-stopped', summary);
80
+ const live = liveProjectProcesses(projectRoot);
81
+ if (live === null) return refuse('cannot verify that no process is using this project on this platform; migration refused (no automatic reclaim)', summary);
82
+ if (live.length) return refuse(`processes still use this project (pids ${live.join(', ')}); close them yourself, UKit never stops processes`, summary);
83
+
84
+ const id = pending?.id ?? crypto.randomBytes(6).toString('hex');
85
+ const quarantine = `${store}.migrated-${id}`;
86
+ const fresh = `${store}.new-${id}`;
87
+ const step = (name) => { try { hooks.step?.(name); } catch (e) { e.fromHook = true; throw e; } };
88
+
89
+ if (!pending) {
90
+ if (summary.tempFiles) return refuse('writer temp files present (a writer may be active); retry after all sessions are closed', summary);
91
+ const before = fingerprint(store);
92
+ await new Promise((r) => setTimeout(r, observeMs));
93
+ if (fingerprint(store) !== before) return refuse('marker store changed during the observation window; a writer is still active', summary);
94
+ try { fs.mkdirSync(fresh); } catch (error) { return refuse(`cannot create the fresh marker directory (${error.code ?? error.message}); nothing was changed`, summary); }
95
+ // A stem that already has a release keeps it byte-for-byte; its block adds nothing (a release is sticky).
96
+ const released = new Set(plan.entries.filter((e) => e.kind === 'release').map((e) => e.stem));
97
+ for (const e of plan.entries) {
98
+ if (e.kind === 'block' && released.has(e.stem)) continue;
99
+ fs.writeFileSync(path.join(fresh, `${e.stem}.release`), e.text, { flag: 'wx' });
100
+ }
101
+ // Last check before the store is touched: a writer arriving after the observation window aborts the run.
102
+ if (fingerprint(store) !== before) { fs.rmSync(fresh, { recursive: true, force: true }); return refuse('marker store changed just before the swap; a writer is still active', summary); }
103
+ fs.writeFileSync(journal, JSON.stringify({ v: 1, id }), { flag: 'wx' });
104
+ }
105
+ step('journaled');
106
+ // Recovery-safe sequence: quarantine -> fence file at the store path -> unlink fence -> publish new directory.
107
+ // A journal without its fresh directory is only valid after the final rename (quarantine kept, store a directory).
108
+ if (pending && !fs.existsSync(fresh) && !(fs.existsSync(quarantine) && stat?.isDirectory())) return refuse('migration journal has no fresh directory to resume from; nothing was changed, keep the files and contact the maintainer', summary);
109
+ try {
110
+ if (!fs.existsSync(fresh) && fs.existsSync(quarantine)) { fs.rmSync(journal, { force: true }); return { ok: true, status: 'migrated', ...summary, quarantine }; }
111
+ if (fs.existsSync(store) && fs.statSync(store).isDirectory()) { fs.renameSync(store, quarantine); step('quarantined'); }
112
+ if (!fs.existsSync(store)) fs.writeFileSync(store, 'ukit marker store migrating', { flag: 'wx' });
113
+ step('fenced');
114
+ if (fs.statSync(store).isFile()) fs.unlinkSync(store);
115
+ fs.renameSync(fresh, store);
116
+ } catch (error) {
117
+ if (error.fromHook) throw error;
118
+ return refuse(`migration did not complete (${error.code ?? error.message}); rerun the same command to resume, nothing was deleted`, { ...summary, quarantine });
119
+ }
120
+ fs.rmSync(journal, { force: true });
121
+ return { ok: true, status: 'migrated', ...summary, quarantine };
122
+ }
@@ -201,9 +201,9 @@ const HOOK_DEADLINE_MS = Number.parseInt(process.env.UKIT_HOOK_DEADLINE_MS || ''
201
201
  setTimeout(() => process.exit(0), HOOK_DEADLINE_MS).unref();
202
202
 
203
203
  (async () => {
204
- // BEGIN GENERATED SEMANTIC ENGINE sha256=f574f585962b045968832191d0a086cb6625965b80b751a893e663fba12b085d
204
+ // BEGIN GENERATED SEMANTIC ENGINE sha256=d125c6ef30c4bec1e3065148855cfd0b90c1af5acd90de2020de02607a4e0adf
205
205
  // Canonical task semantics; intent never grants authorization or proves completion.
206
- const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:d2c70fa8c68d50f31917ee7befd16f6df36a441a2aae79a0de879f5b0a09edf1';
206
+ const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:d54a8c14f321c1eeba4832e4461cd6d0c2231b2f7a80932ac3129f1e8dd792f9';
207
207
 
208
208
  function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
209
209
  return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
@@ -247,8 +247,8 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
247
247
  const text = foldIntent(raw);
248
248
  const quoted = Boolean(marker || fence || /^\s*>/.test(raw));
249
249
  const context = quoted ? 'quotation' : description && bullet ? 'description' : 'instruction';
250
- const polarity = /\b(?:do not|don't|never|must not|no|khong|chua)\b|đừng/i.test(raw) || /\b(?:prohibited|forbidden|banned)\b/.test(text) ? 'prohibited' : 'affirmative';
251
- const condition = text.match(/\b(?:if|neu|only if|only when|only after|only once)\b[^,;.\n]*/)?.[0] || null;
250
+ const polarity = /\b(?:do not|don't|never|must not|no|khong|chua|prohibited|forbidden|banned)\b/.test(text) || /đừng/i.test(raw) ? 'prohibited' : 'affirmative';
251
+ const condition = text.match(/\b(?:if|neu|sau khi|only if|only when|only after|only once)\b[^,;.\n]*/)?.[0] || null;
252
252
  spans.push({ start: offset + part.index, end: offset + part.index + raw.length, raw,
253
253
  context, polarity, condition, activation: condition ? 'pending' : context !== 'instruction' || polarity === 'prohibited' ? 'inactive' : 'eligible' });
254
254
  }
@@ -274,6 +274,9 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
274
274
  && ordersPublicationText(foldIntent(span.raw).replace(/^[^,]*,\s*/, ''))));
275
275
  spans.forEach((span, index) => {
276
276
  const folded = foldIntent(span.raw);
277
+ if (span.context === 'instruction' && span.polarity === 'affirmative' && span.condition
278
+ && /\b(?:phat hanh|xuat ban)\s+npm\b/.test(folded)
279
+ && /\b(?:neu|sau khi)\b/.test(span.condition) && !nativeReleasePolicy) deferredSpans.add(span);
277
280
  const verb = folded.match(CONDITIONAL_RUNTIME_VERB);
278
281
  const cond = span.condition ? folded.indexOf(span.condition) : -1;
279
282
  if (!verb || cond < 0 || span.context !== 'instruction' || span.polarity !== 'affirmative' || nativeReleasePolicy
@@ -302,8 +305,12 @@ function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstanceId =
302
305
  if (span.context === 'quotation' || span.context === 'description' || approvalPending || deferredSpans.has(span) || evidenceStatement) {
303
306
  // Retain the prefix before a comma-introduced postfix repair condition.
304
307
  // Leading conditions and otherwise consequences are masked in full.
305
- const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|only after|only once|otherwise)\b/.test(foldIntent(span.raw))
306
- ? span.raw.match(/^[^,]*,/)?.[0] || '' : '';
308
+ const folded = foldIntent(span.raw);
309
+ const coordinatedRelease = folded.match(/\b(?:va|roi)\s+(?:phat hanh|xuat ban)\s+npm\b/);
310
+ const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|only after|only once|otherwise)\b/.test(folded)
311
+ ? coordinatedRelease && /\b(?:neu|sau khi)\b/.test(span.condition || '')
312
+ ? span.raw.slice(0, coordinatedRelease.index)
313
+ : span.raw.match(/^[^,]*,/)?.[0] || '' : '';
307
314
  const masked = prefix + span.raw.slice(prefix.length).replace(/[^\r\n]/g, ' ');
308
315
  semanticInput = semanticInput.slice(0, span.start) + masked + semanticInput.slice(span.end);
309
316
  }
@@ -350,7 +357,7 @@ const VERIFICATION_LEAD = /^[-*+\u2022>\d.)\s]*(?:(?:please|hay|vui long|now|als
350
357
  const PAST_RELEASE_SOURCE = 'release(?:\\s+\\S+)?\\s+(?:(?:(?:was|were|is|are|has been|have been|had been|just been)(?:\\s+already)?|already)\\s+(?:published|shipped|released|on npm|live|deployed|out)|da\\s+(?:publish|phat hanh|release|deploy))\\b';
351
358
  const PAST_RELEASE_ITEM = new RegExp(`^(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}`);
352
359
  const PUBLISH_ORDER_NEGATOR = /\b(?:do not|don't|dont|never|without|not yet|no|not|avoid|skip|exclud\w*|forbid\w*|prohibit\w*|khong|chua)\b|--dry-run/;
353
- const PUBLISH_ORDER_IMPERATIVE = /^(?:please\s+|just\s+|now\s+|also\s+)*(?:run|do|execute|perform|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/;
360
+ const PUBLISH_ORDER_IMPERATIVE = /^(?:please\s+|just\s+|now\s+|also\s+)*(?:run|do|execute|perform|thuc hien|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/;
354
361
  const PUBLISH_ORDER_HEADER = /prohibit|forbidden|out of scope|non-goal|scope control/;
355
362
  function defectRepairBranches(text) {
356
363
  return [...text.matchAll(/(?:^|\n|\.\s+)[ \t]*(?:[-*]|\d+[.)])?\s*((?:neu\s+(?:gap|phat hien|tim thay|co)|if\b)[^.!?]*(?:\.(?!\w)|$))/g)]
@@ -470,10 +477,11 @@ function ordersPublicationText(promptText = '') {
470
477
  if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
471
478
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
472
479
  const commandItem = item.replace(/^(?:please|just|now|also|then)\s+/, '');
473
- const publication = /\bnpm\s+publish\b/.test(commandItem) && /^(?:npm\s+publish|run|do|execute|perform|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/.test(commandItem);
480
+ const publication = /\bnpm\s+publish\b/.test(commandItem) && /^(?:npm\s+publish|run|do|execute|perform|thuc hien|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/.test(commandItem);
474
481
  const releaseOrder = !PAST_RELEASE_ITEM.test(item) && /^(?:please\s+|just\s+|now\s+|also\s+)*(?:release|ship|publish)\s+(?!instructions?\b|obligations?\b|policies\b|boundary\b|safety\b|progress\b|candidate\s+review\b|readiness\b|verifier\b|verification\b|evidence\b|policy\b|intent\b|notes\b|terminology\b)\S/.test(item);
475
482
  const politeItem = item.replace(/^(?:(?:please|just|now|also|then|vui long|hay)\s+)+/, '');
476
- const viPublish = /^(?:(?:su dung|phat hanh bang)\s+`?npm\s+publish\b|(?:dua|phat hanh|xuat ban|deploy|day)\b(?:[^.;\n]|\.(?=\d)){0,60}\b(?:len|to|vao)\s+npm\b)/.test(politeItem);
483
+ const viPublish = /^(?:(?:su dung(?: lenh)?|phat hanh bang)\s+`?npm\s+publish\b|(?:dua|phat hanh|xuat ban|deploy|day)\b(?:[^.;\n]|\.(?=\d)){0,60}\b(?:len|to|vao)\s+npm\b)/.test(politeItem)
484
+ || /^(?:(?:sua|kiem thu|hoan tat)\b[^.;\n]*\b(?:va|roi)\s+|(?:va|roi)\s+)(?:phat hanh|xuat ban)\s+npm\b/.test(politeItem);
477
485
  if (!negated && (releaseOrder || viPublish || (publication && (
478
486
  (/^npm\s+publish\b/.test(politeItem) && (/^(?:[\s*•-]|\d+[.)])*(?:(?:please|just|now|also)\s+)*(?:npm\s+publish|run|execute|perform|commit|push|tag)\b/.test(hard.trim()) || /\bcontinue the release workflow:/.test(hard))) || PUBLISH_ORDER_IMPERATIVE.test(item)
479
487
  || /\b(?:chay|run)\s+`?npm\s+publish\b/.test(item)
@@ -543,6 +551,11 @@ function neutralizeNonOrders(text) {
543
551
  .replace(/^[ \t]*(?:[-*+\u2022]|\d+[.)])[ \t]*(?:negative|positive)\s+controls?\b[^\n]*(?:\n(?![ \t]*(?:[-*+\u2022]|\d+[.)])|[ \t]*\n)[^\n]*)*/gm, ' ')
544
552
  .replace(/(?:^|(?<=[.;][ \t]))[^.;\n]*\b(?:khong\s+(?:cho\s+phep|duoc|lam)|(?:does|do|did|is|are)\s+not\s+(?:allow|permit|authori[sz]e)\w*|not\s+(?:allowed|permitted|authori[sz]ed)|prohibitions?|prohibited(?:\s+actions?)?|forbidden(?:\s+actions?)?|banned|must\s+not\s+do)\s*:[ \t]*(?:\n[ \t]*(?:[-*+\u2022]|\d+[.)])[^\n]*)+/gm, ' ')
545
553
  .replace(new RegExp(`\\b(?:do\\s+not|don't|dont|must\\s+not|never|shall\\s+not)\\s+[^.;\\n]*?(?=\\s+(?:and|va)\\s+(?:${NON_ORDER_VERBS})\\b|\\s+(?:but|nhung|then|however)\\b|[.;\\n]|$)`, 'g'), ' ')
554
+ // Negated sufficiency ("git commit/tag/release chua du de ban giao", "a git commit is not enough /
555
+ // insufficient"): the negation sits AFTER the operation enumeration, so the khong/chua span strip
556
+ // below would remove only the predicate tail and leave the bare "git commit/tag/release" fragment
557
+ // standing as a phantom imperative. Consume the enumeration together with its negated predicate.
558
+ .replace(new RegExp(`\\b(?:(?:git|npm)\\s+)?(?:commit|push|tag|release|deploy(?:ment)?|redeploy|restart|publish|phat\\s+hanh|trien\\s+khai)(?:\\s*/\\s*(?:commit|push|tag|release|deploy(?:ment)?|redeploy|restart|publish|phat\\s+hanh|trien\\s+khai))*\\s+(?:(?:(?:is|are|was|were)\\s+)?(?:not\\s+(?:enough|sufficient)|insufficient)\\b|(?:(?:tuyet\\s+doi\\s+)?khong|chua)\\b)[^.;\\n]*`, 'g'), ' ')
546
559
  .replace(new RegExp(`\\b(?:(?:tuyet\\s+doi\\s+)?khong|chua)\\s+[^.;\\n]*?(?=\\s+(?:nhung|tuy nhien)\\b|[.;\\n]|$)`, 'g'), ' ')
547
560
  .replace(/"[^"\n]*\s[^"\n]*"|`[^`\n]*\s[^`\n]*`|\u201c[^\u201d\n]*\u201d/g, ' ')
548
561
  .replace(/\b(?:uu tien|prefer(?:red)?)\s+(?:a\s+|an\s+)?(?:configuration|config|cau hinh)\s+(?:change|changes|update|thay doi)\b/g, ' ')
@@ -567,7 +580,7 @@ function neutralizeNonOrders(text) {
567
580
  });
568
581
  }
569
582
 
570
- const READ_ONLY_DECLARATION = /\breviewer\s*[,—:-]?\s+read[\s_-]*only\b|\bread[\s_-]*only(?:\s+\w+){0,3}?\s+(?:audit|investigation|review|analysis|inspection|inventory|task|request|session|pass|check|diagnos\w+|verification|forensics?|reports?)\b|(?:^|\n)[\s*#>_-]*read[\s_-]*only\s*[.:!—-]|\b(?:audit|investigation|review|analysis|inventory)[\s-]*only\b|[(,]\s*read[\s_-]*only\s*[).]|\bchi\s+(?:doc|audit|kiem tra|kiem ke|phan tich|dieu tra)\b|\bkhong\s+sua\b|\b(?:make|with)\s+no\s+(?:source\s+|code\s+|file\s+)?(?:changes|edits|modifications)\b|\b(?:do\s+not|don't|dont|never)\s+(?:\w+\s+){0,2}edits?\b/;
583
+ const READ_ONLY_DECLARATION = /\breviewer\s*[,—:-]?\s+read[\s_-]*only\b|\bread[\s_-]*only(?:\s+\w+){0,3}?\s+(?:audit|investigation|review|analysis|inspection|inventory|task|request|session|pass|check|diagnos\w+|verification|forensics?|reports?)\b|(?:^|\n)[\s*#>_-]*read[\s_-]*only\s*[.:!—-]|\b(?:audit|investigation|review|analysis|inventory)[\s-]*only\b|[(,]\s*read[\s_-]*only\s*[).]|\bchi\s+(?:doc|audit|kiem tra|kiem ke|phan tich|dieu tra)\b|\bkhong\s+sua\b(?=\s*(?:$|[.,;:!?)\n])|\s+(?:code|file|files|source|repo|repository|gi|bat|moi|them|lai|nua|du\s+an|tai\s+lieu|test|tests|mot|nao|ca|ledger|gate|receipts?|worklog)\b)|\b(?:make|with)\s+no\s+(?:source\s+|code\s+|file\s+)?(?:changes|edits|modifications)\b|\b(?:do\s+not|don't|dont|never)\s+(?:\w+\s+){0,2}edits?\b/;
571
584
  const ORDER_VERBS = 'implement|fix|apply|refactor|modify|edit|write|update|add|create|build|install|deploy|redeploy|restart|push|commit|rename|remove|delete|replace|change|sua|viet|chinh|them|bo sung|tao|xoa|enable|disable|set|toggle|configure|migrate|upgrade|publish|release|trien khai|khoi dong lai|(?:run|execute)\\s+(?:git\\s+(?:push|clean|commit|reset|rebase|merge|tag|stash|checkout|restore|cherry-pick)|(?:npm|yarn)\\s+publish)|git\\s+(?:push|clean|commit|reset|rebase|merge|tag|stash|checkout|restore|cherry-pick)';
572
585
  const IMPERATIVE_ORDER = new RegExp(`^(?:[-*+\\u2022>\\d.)\\s]*)(?:(?:please|hay|vui long|now|also|first|then)\\s+)*(?:${ORDER_VERBS})\\b\\s+\\S`);
573
586
  const MODAL_ORDER = new RegExp(`\\b(?:please|hay|vui long|need to|needs to|must|should|want(?:\\s+you)? to|toi muon|can phai|yeu cau)\\s+(?:[\\w-]+\\s+){0,2}(?:${ORDER_VERBS})\\b`);
@@ -690,6 +703,9 @@ function isStateOperationRequest(promptText = '') {
690
703
  return plain.split(/[;!?\n]+|[.:](?=\s|$)/).some((clause) => {
691
704
  const lead = clause.match(STATE_LEAD);
692
705
  if (!lead) return false;
706
+ // A clause whose verb is negated ("khong tu kill process", "do not stop the job") states a boundary, not an
707
+ // order to inspect or stop state. Only a negator BEFORE the verb counts: "stop X; do not ..." stays an order.
708
+ if (/\b(?:khong|do not|don't|never|not)\b/.test(clause.slice(0, lead.index))) return false;
693
709
  const after = clause.slice(lead.index + lead[0].length);
694
710
  const near = after.match(/^(?:\s+[\p{L}\p{N}_-]+){0,5}?\s+/u);
695
711
  const window = after.split(/\s+/).slice(0, 7).join(' ');
@@ -4470,7 +4486,16 @@ function applyTaskSemantics(contract, semantic) {
4470
4486
  const readOrNull = async (file) => { try { return await fsp.readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
4471
4487
  const priorSidecar = sessionId ? await readOrNull(sessionRoutePath) : null;
4472
4488
  const priorShared = sessionId ? await readOrNull(statePath) : null;
4473
- if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true }));
4489
+ // The pending marker is the only session record while the publication is in flight: it carries the owner STOP
4490
+ // (from this publication, else the committed sidecar it replaces) so an interrupted publication cannot lift it.
4491
+ const committedStop = (() => {
4492
+ try {
4493
+ const committed = priorSidecar === null ? null : JSON.parse(priorSidecar);
4494
+ return committed?.ownerControl?.kind === 'stop' && committed.sessionId === sessionId ? committed.ownerControl : null;
4495
+ } catch { return null; }
4496
+ })();
4497
+ const markerControl = persisted.ownerControl ?? committedStop;
4498
+ if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true, ...(markerControl ? { ownerControl: markerControl } : {}) }));
4474
4499
  try {
4475
4500
  await writeJsonFileAtomic(statePath, text);
4476
4501
  } catch (error) {
@@ -4590,18 +4615,38 @@ function applyTaskSemantics(contract, semantic) {
4590
4615
  const buf = Buffer.alloc(len);
4591
4616
  fs.readSync(fd, buf, 0, len, size - len);
4592
4617
  const lines = buf.toString('utf8').split('\n');
4618
+ // Host-authored proof of a PEER delivery: a queued_command attachment whose origin the host
4619
+ // stamped as 'peer', bound to this session and to the exact prompt text. The envelope text
4620
+ // alone is never proof (a human can paste it); only the host's attachment counts.
4621
+ const peerDeliveryIds = new Set();
4622
+ for (const l of lines) {
4623
+ if (!l || !l.includes('queued_command')) continue;
4624
+ let a; try { a = JSON.parse(l); } catch { continue; }
4625
+ const at = a?.attachment;
4626
+ if (a.type === 'attachment' && at?.type === 'queued_command' && at.origin?.kind === 'peer'
4627
+ && typeof at.delivery_id === 'string' && sessionId && a.sessionId === sessionId
4628
+ && typeof at.prompt === 'string' && at.prompt.trim() === promptTrim) {
4629
+ peerDeliveryIds.add(at.delivery_id);
4630
+ }
4631
+ }
4632
+ let deliveryCurrent = true;
4593
4633
  for (let i = lines.length - 1; i >= 0; i -= 1) {
4594
4634
  const line = lines[i];
4595
4635
  if (!line) continue;
4596
4636
  let entry; try { entry = JSON.parse(line); } catch { continue; }
4597
- // Cross-session delivery is queued, not a user order. Require the host's
4598
- // consumed delivery record, exact content and this session's owner. An
4599
- // enqueue, a foreign delivery or a human-pasted envelope is not proof.
4600
- if (entry.type === 'queue-operation' && entry.operation === 'remove'
4637
+ // A response after a queued delivery means that delivery belongs to an earlier turn;
4638
+ // never let its text exempt a later owner prompt. Host hook metadata may follow the
4639
+ // delivery before this hook runs, but an assistant message is a turn boundary.
4640
+ if (entry.type === 'assistant' && entry.isSidechain !== true) deliveryCurrent = false;
4641
+ // Queued deliveries are not user orders. Require the host's consumed delivery record, exact
4642
+ // content and this session's owner. An enqueue, a foreign delivery or a human-pasted envelope
4643
+ // is not proof. A peer agent-message counts only with the host's peer attachment for that delivery.
4644
+ if (deliveryCurrent && entry.type === 'queue-operation' && entry.operation === 'remove'
4601
4645
  && entry.reason === 'absorbed_mid_turn' && entry.deliveryId
4602
4646
  && sessionId && entry.sessionId === sessionId
4603
4647
  && typeof entry.content === 'string' && entry.content.trim() === promptTrim
4604
- && /^<cross-session-message\s/.test(promptTrim)) {
4648
+ && (/^<cross-session-message\s/.test(promptTrim)
4649
+ || (/^<agent-message\s/.test(promptTrim) && peerDeliveryIds.has(entry.deliveryId)))) {
4605
4650
  coordinationTurn = true;
4606
4651
  return false;
4607
4652
  }
@@ -4747,6 +4792,34 @@ function applyTaskSemantics(contract, semantic) {
4747
4792
  if (GUIDANCE_MUTATION_VERB.test(guidanceResidue)) return false;
4748
4793
  if (GUIDANCE_LOOKUP_ORDER.test(guidanceResidue.replace(/\b(?:sau|after)\s+[a-z]+/g, (temporal, offset, text) => (GUIDANCE_TEMPORAL_ORDER_HEAD.test(text.slice(offset)) ? temporal : ' ')))) return false;
4749
4794
  }
4795
+ // Re-anchored linkage: "keep this work on the X" names X as the NOTE's topic. X binds only
4796
+ // when EVERY content word of X matches the task's own explicit prompt. Scope reading is
4797
+ // deterministic, not semantic: the phrase may contain slashes, ampersands, dotted FILE
4798
+ // names (punctuation followed by an alphanumeric stays inside the scope, so
4799
+ // "package.json" is one name, never truncated to "package") and quoted or parenthesized
4800
+ // parts (parentheticals are asides and are stripped); it ends at punctuation, a NEWLINE
4801
+ // or end of text. Words of 2-3 chars (API, CLI, MCP) count by EXACT equality; longer
4802
+ // words match only as prefix + bound morphology suffix ("deployment" ~ "deploy"), so a
4803
+ // prefix share alone never binds ("contractor" is not "contract", "production backlog"
4804
+ // is not "deploy to production"). Quantifier and temporal fragments (only/just/also/
4805
+ // for now/...) are never scope words. All this keeps the P0 isolation: receipt or
4806
+ // backlog reading never inherits a deploy order.
4807
+ const reanchoredScope = folded.match(/\b(?:this|current)\s+(?:work|task|change|one)\s+(?:on|for|about|regarding|within|inside)\s+(?:the\s+|this\s+|our\s+)?([a-z0-9][a-z0-9 .\/_()&'-]*?)(?=[!?:;,]|\.(?![a-z0-9])|\r|\n|$)/);
4808
+ if (reanchoredScope) {
4809
+ const priorPrompt = String(previous.routingContext?.lastExplicitUserPromptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase();
4810
+ if (priorPrompt) {
4811
+ const scopeWords = reanchoredScope[1].replace(/[()]/g, ' ').replace(/\.(?![a-z0-9])/g, ' ').split(/[^a-z0-9]+/).filter((w) => w.length >= 2
4812
+ && !['work', 'task', 'this', 'that', 'scope', 'current', 'focus', 'focused', 'change', 'note', 'plan', 'only', 'just', 'also', 'too', 'still', 'again', 'first', 'next', 'then', 'now', 'later', 'the', 'and', 'for', 'our', 'its', 'with', 'into', 'from', 'of', 'to', 'in', 'on', 'at', 'by', 'or'].includes(w));
4813
+ const priorWords = priorPrompt.split(/[^a-z0-9]+/).filter((w) => w.length >= 2);
4814
+ const wordMatches = (w) => priorWords.some((p) => {
4815
+ if (p === w) return true;
4816
+ if (w.length < 4 || p.length < 4) return false;
4817
+ const [short, long] = w.length <= p.length ? [w, p] : [p, w];
4818
+ return long.startsWith(short) && ['s', 'es', 'ed', 'ing', 'ment', 'ments', 'ion', 'ions', 'ly', 'er', 'ers', 'ation', 'ations'].includes(long.slice(short.length));
4819
+ });
4820
+ if (scopeWords.length > 0 && !scopeWords.every(wordMatches)) return false;
4821
+ }
4822
+ }
4750
4823
  if (!previous.taskInstanceId) return false;
4751
4824
  const contract = previous.routeSummary?.executionContract;
4752
4825
  if (!contract?.taskKind) return false;
@@ -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:d2c70fa8c68d50f31917ee7befd16f6df36a441a2aae79a0de879f5b0a09edf1';
3
+ export const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:d54a8c14f321c1eeba4832e4461cd6d0c2231b2f7a80932ac3129f1e8dd792f9';
4
4
 
5
5
  export function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
6
6
  return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
@@ -44,8 +44,8 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
44
44
  const text = foldIntent(raw);
45
45
  const quoted = Boolean(marker || fence || /^\s*>/.test(raw));
46
46
  const context = quoted ? 'quotation' : description && bullet ? 'description' : 'instruction';
47
- const polarity = /\b(?:do not|don't|never|must not|no|khong|chua)\b|đừng/i.test(raw) || /\b(?:prohibited|forbidden|banned)\b/.test(text) ? 'prohibited' : 'affirmative';
48
- const condition = text.match(/\b(?:if|neu|only if|only when|only after|only once)\b[^,;.\n]*/)?.[0] || null;
47
+ const polarity = /\b(?:do not|don't|never|must not|no|khong|chua|prohibited|forbidden|banned)\b/.test(text) || /đừng/i.test(raw) ? 'prohibited' : 'affirmative';
48
+ const condition = text.match(/\b(?:if|neu|sau khi|only if|only when|only after|only once)\b[^,;.\n]*/)?.[0] || null;
49
49
  spans.push({ start: offset + part.index, end: offset + part.index + raw.length, raw,
50
50
  context, polarity, condition, activation: condition ? 'pending' : context !== 'instruction' || polarity === 'prohibited' ? 'inactive' : 'eligible' });
51
51
  }
@@ -71,6 +71,9 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
71
71
  && ordersPublicationText(foldIntent(span.raw).replace(/^[^,]*,\s*/, ''))));
72
72
  spans.forEach((span, index) => {
73
73
  const folded = foldIntent(span.raw);
74
+ if (span.context === 'instruction' && span.polarity === 'affirmative' && span.condition
75
+ && /\b(?:phat hanh|xuat ban)\s+npm\b/.test(folded)
76
+ && /\b(?:neu|sau khi)\b/.test(span.condition) && !nativeReleasePolicy) deferredSpans.add(span);
74
77
  const verb = folded.match(CONDITIONAL_RUNTIME_VERB);
75
78
  const cond = span.condition ? folded.indexOf(span.condition) : -1;
76
79
  if (!verb || cond < 0 || span.context !== 'instruction' || span.polarity !== 'affirmative' || nativeReleasePolicy
@@ -99,8 +102,12 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
99
102
  if (span.context === 'quotation' || span.context === 'description' || approvalPending || deferredSpans.has(span) || evidenceStatement) {
100
103
  // Retain the prefix before a comma-introduced postfix repair condition.
101
104
  // Leading conditions and otherwise consequences are masked in full.
102
- const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|only after|only once|otherwise)\b/.test(foldIntent(span.raw))
103
- ? span.raw.match(/^[^,]*,/)?.[0] || '' : '';
105
+ const folded = foldIntent(span.raw);
106
+ const coordinatedRelease = folded.match(/\b(?:va|roi)\s+(?:phat hanh|xuat ban)\s+npm\b/);
107
+ const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|only after|only once|otherwise)\b/.test(folded)
108
+ ? coordinatedRelease && /\b(?:neu|sau khi)\b/.test(span.condition || '')
109
+ ? span.raw.slice(0, coordinatedRelease.index)
110
+ : span.raw.match(/^[^,]*,/)?.[0] || '' : '';
104
111
  const masked = prefix + span.raw.slice(prefix.length).replace(/[^\r\n]/g, ' ');
105
112
  semanticInput = semanticInput.slice(0, span.start) + masked + semanticInput.slice(span.end);
106
113
  }
@@ -147,7 +154,7 @@ const VERIFICATION_LEAD = /^[-*+\u2022>\d.)\s]*(?:(?:please|hay|vui long|now|als
147
154
  const PAST_RELEASE_SOURCE = 'release(?:\\s+\\S+)?\\s+(?:(?:(?:was|were|is|are|has been|have been|had been|just been)(?:\\s+already)?|already)\\s+(?:published|shipped|released|on npm|live|deployed|out)|da\\s+(?:publish|phat hanh|release|deploy))\\b';
148
155
  const PAST_RELEASE_ITEM = new RegExp(`^(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}`);
149
156
  const PUBLISH_ORDER_NEGATOR = /\b(?:do not|don't|dont|never|without|not yet|no|not|avoid|skip|exclud\w*|forbid\w*|prohibit\w*|khong|chua)\b|--dry-run/;
150
- const PUBLISH_ORDER_IMPERATIVE = /^(?:please\s+|just\s+|now\s+|also\s+)*(?:run|do|execute|perform|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/;
157
+ const PUBLISH_ORDER_IMPERATIVE = /^(?:please\s+|just\s+|now\s+|also\s+)*(?:run|do|execute|perform|thuc hien|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/;
151
158
  const PUBLISH_ORDER_HEADER = /prohibit|forbidden|out of scope|non-goal|scope control/;
152
159
  function defectRepairBranches(text) {
153
160
  return [...text.matchAll(/(?:^|\n|\.\s+)[ \t]*(?:[-*]|\d+[.)])?\s*((?:neu\s+(?:gap|phat hien|tim thay|co)|if\b)[^.!?]*(?:\.(?!\w)|$))/g)]
@@ -267,10 +274,11 @@ function ordersPublicationText(promptText = '') {
267
274
  if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
268
275
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
269
276
  const commandItem = item.replace(/^(?:please|just|now|also|then)\s+/, '');
270
- const publication = /\bnpm\s+publish\b/.test(commandItem) && /^(?:npm\s+publish|run|do|execute|perform|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/.test(commandItem);
277
+ const publication = /\bnpm\s+publish\b/.test(commandItem) && /^(?:npm\s+publish|run|do|execute|perform|thuc hien|go|ship|publish|release|push|tag|commit|verify|make|cut|chay)\b/.test(commandItem);
271
278
  const releaseOrder = !PAST_RELEASE_ITEM.test(item) && /^(?:please\s+|just\s+|now\s+|also\s+)*(?:release|ship|publish)\s+(?!instructions?\b|obligations?\b|policies\b|boundary\b|safety\b|progress\b|candidate\s+review\b|readiness\b|verifier\b|verification\b|evidence\b|policy\b|intent\b|notes\b|terminology\b)\S/.test(item);
272
279
  const politeItem = item.replace(/^(?:(?:please|just|now|also|then|vui long|hay)\s+)+/, '');
273
- const viPublish = /^(?:(?:su dung|phat hanh bang)\s+`?npm\s+publish\b|(?:dua|phat hanh|xuat ban|deploy|day)\b(?:[^.;\n]|\.(?=\d)){0,60}\b(?:len|to|vao)\s+npm\b)/.test(politeItem);
280
+ const viPublish = /^(?:(?:su dung(?: lenh)?|phat hanh bang)\s+`?npm\s+publish\b|(?:dua|phat hanh|xuat ban|deploy|day)\b(?:[^.;\n]|\.(?=\d)){0,60}\b(?:len|to|vao)\s+npm\b)/.test(politeItem)
281
+ || /^(?:(?:sua|kiem thu|hoan tat)\b[^.;\n]*\b(?:va|roi)\s+|(?:va|roi)\s+)(?:phat hanh|xuat ban)\s+npm\b/.test(politeItem);
274
282
  if (!negated && (releaseOrder || viPublish || (publication && (
275
283
  (/^npm\s+publish\b/.test(politeItem) && (/^(?:[\s*•-]|\d+[.)])*(?:(?:please|just|now|also)\s+)*(?:npm\s+publish|run|execute|perform|commit|push|tag)\b/.test(hard.trim()) || /\bcontinue the release workflow:/.test(hard))) || PUBLISH_ORDER_IMPERATIVE.test(item)
276
284
  || /\b(?:chay|run)\s+`?npm\s+publish\b/.test(item)
@@ -340,6 +348,11 @@ function neutralizeNonOrders(text) {
340
348
  .replace(/^[ \t]*(?:[-*+\u2022]|\d+[.)])[ \t]*(?:negative|positive)\s+controls?\b[^\n]*(?:\n(?![ \t]*(?:[-*+\u2022]|\d+[.)])|[ \t]*\n)[^\n]*)*/gm, ' ')
341
349
  .replace(/(?:^|(?<=[.;][ \t]))[^.;\n]*\b(?:khong\s+(?:cho\s+phep|duoc|lam)|(?:does|do|did|is|are)\s+not\s+(?:allow|permit|authori[sz]e)\w*|not\s+(?:allowed|permitted|authori[sz]ed)|prohibitions?|prohibited(?:\s+actions?)?|forbidden(?:\s+actions?)?|banned|must\s+not\s+do)\s*:[ \t]*(?:\n[ \t]*(?:[-*+\u2022]|\d+[.)])[^\n]*)+/gm, ' ')
342
350
  .replace(new RegExp(`\\b(?:do\\s+not|don't|dont|must\\s+not|never|shall\\s+not)\\s+[^.;\\n]*?(?=\\s+(?:and|va)\\s+(?:${NON_ORDER_VERBS})\\b|\\s+(?:but|nhung|then|however)\\b|[.;\\n]|$)`, 'g'), ' ')
351
+ // Negated sufficiency ("git commit/tag/release chua du de ban giao", "a git commit is not enough /
352
+ // insufficient"): the negation sits AFTER the operation enumeration, so the khong/chua span strip
353
+ // below would remove only the predicate tail and leave the bare "git commit/tag/release" fragment
354
+ // standing as a phantom imperative. Consume the enumeration together with its negated predicate.
355
+ .replace(new RegExp(`\\b(?:(?:git|npm)\\s+)?(?:commit|push|tag|release|deploy(?:ment)?|redeploy|restart|publish|phat\\s+hanh|trien\\s+khai)(?:\\s*/\\s*(?:commit|push|tag|release|deploy(?:ment)?|redeploy|restart|publish|phat\\s+hanh|trien\\s+khai))*\\s+(?:(?:(?:is|are|was|were)\\s+)?(?:not\\s+(?:enough|sufficient)|insufficient)\\b|(?:(?:tuyet\\s+doi\\s+)?khong|chua)\\b)[^.;\\n]*`, 'g'), ' ')
343
356
  .replace(new RegExp(`\\b(?:(?:tuyet\\s+doi\\s+)?khong|chua)\\s+[^.;\\n]*?(?=\\s+(?:nhung|tuy nhien)\\b|[.;\\n]|$)`, 'g'), ' ')
344
357
  .replace(/"[^"\n]*\s[^"\n]*"|`[^`\n]*\s[^`\n]*`|\u201c[^\u201d\n]*\u201d/g, ' ')
345
358
  .replace(/\b(?:uu tien|prefer(?:red)?)\s+(?:a\s+|an\s+)?(?:configuration|config|cau hinh)\s+(?:change|changes|update|thay doi)\b/g, ' ')
@@ -364,7 +377,7 @@ function neutralizeNonOrders(text) {
364
377
  });
365
378
  }
366
379
 
367
- const READ_ONLY_DECLARATION = /\breviewer\s*[,—:-]?\s+read[\s_-]*only\b|\bread[\s_-]*only(?:\s+\w+){0,3}?\s+(?:audit|investigation|review|analysis|inspection|inventory|task|request|session|pass|check|diagnos\w+|verification|forensics?|reports?)\b|(?:^|\n)[\s*#>_-]*read[\s_-]*only\s*[.:!—-]|\b(?:audit|investigation|review|analysis|inventory)[\s-]*only\b|[(,]\s*read[\s_-]*only\s*[).]|\bchi\s+(?:doc|audit|kiem tra|kiem ke|phan tich|dieu tra)\b|\bkhong\s+sua\b|\b(?:make|with)\s+no\s+(?:source\s+|code\s+|file\s+)?(?:changes|edits|modifications)\b|\b(?:do\s+not|don't|dont|never)\s+(?:\w+\s+){0,2}edits?\b/;
380
+ const READ_ONLY_DECLARATION = /\breviewer\s*[,—:-]?\s+read[\s_-]*only\b|\bread[\s_-]*only(?:\s+\w+){0,3}?\s+(?:audit|investigation|review|analysis|inspection|inventory|task|request|session|pass|check|diagnos\w+|verification|forensics?|reports?)\b|(?:^|\n)[\s*#>_-]*read[\s_-]*only\s*[.:!—-]|\b(?:audit|investigation|review|analysis|inventory)[\s-]*only\b|[(,]\s*read[\s_-]*only\s*[).]|\bchi\s+(?:doc|audit|kiem tra|kiem ke|phan tich|dieu tra)\b|\bkhong\s+sua\b(?=\s*(?:$|[.,;:!?)\n])|\s+(?:code|file|files|source|repo|repository|gi|bat|moi|them|lai|nua|du\s+an|tai\s+lieu|test|tests|mot|nao|ca|ledger|gate|receipts?|worklog)\b)|\b(?:make|with)\s+no\s+(?:source\s+|code\s+|file\s+)?(?:changes|edits|modifications)\b|\b(?:do\s+not|don't|dont|never)\s+(?:\w+\s+){0,2}edits?\b/;
368
381
  const ORDER_VERBS = 'implement|fix|apply|refactor|modify|edit|write|update|add|create|build|install|deploy|redeploy|restart|push|commit|rename|remove|delete|replace|change|sua|viet|chinh|them|bo sung|tao|xoa|enable|disable|set|toggle|configure|migrate|upgrade|publish|release|trien khai|khoi dong lai|(?:run|execute)\\s+(?:git\\s+(?:push|clean|commit|reset|rebase|merge|tag|stash|checkout|restore|cherry-pick)|(?:npm|yarn)\\s+publish)|git\\s+(?:push|clean|commit|reset|rebase|merge|tag|stash|checkout|restore|cherry-pick)';
369
382
  const IMPERATIVE_ORDER = new RegExp(`^(?:[-*+\\u2022>\\d.)\\s]*)(?:(?:please|hay|vui long|now|also|first|then)\\s+)*(?:${ORDER_VERBS})\\b\\s+\\S`);
370
383
  const MODAL_ORDER = new RegExp(`\\b(?:please|hay|vui long|need to|needs to|must|should|want(?:\\s+you)? to|toi muon|can phai|yeu cau)\\s+(?:[\\w-]+\\s+){0,2}(?:${ORDER_VERBS})\\b`);
@@ -487,6 +500,9 @@ export function isStateOperationRequest(promptText = '') {
487
500
  return plain.split(/[;!?\n]+|[.:](?=\s|$)/).some((clause) => {
488
501
  const lead = clause.match(STATE_LEAD);
489
502
  if (!lead) return false;
503
+ // A clause whose verb is negated ("khong tu kill process", "do not stop the job") states a boundary, not an
504
+ // order to inspect or stop state. Only a negator BEFORE the verb counts: "stop X; do not ..." stays an order.
505
+ if (/\b(?:khong|do not|don't|never|not)\b/.test(clause.slice(0, lead.index))) return false;
490
506
  const after = clause.slice(lead.index + lead[0].length);
491
507
  const near = after.match(/^(?:\s+[\p{L}\p{N}_-]+){0,5}?\s+/u);
492
508
  const window = after.split(/\s+/).slice(0, 7).join(' ');
@@ -1284,6 +1284,38 @@ export function isGuidanceOnlySupplementText(text) {
1284
1284
  return true;
1285
1285
  }
1286
1286
 
1287
+ // A linkage phrase re-anchored to a NAMED scope ("keep this work on the X") names X as the
1288
+ // NOTE's topic, not necessarily the open task's. X is FOREIGN unless EVERY content word of X
1289
+ // matches the task's own explicit prompt. Scope reading is deterministic, not semantic: the
1290
+ // phrase may contain slashes, ampersands, dotted FILE names (punctuation followed by an
1291
+ // alphanumeric stays inside the scope, so "package.json" is one name, never truncated to
1292
+ // "package") and quoted or parenthesized parts (parentheticals are asides and are stripped);
1293
+ // it ends at punctuation, a NEWLINE or end of text. Words of 2-3 chars (API, CLI, MCP) count
1294
+ // by EXACT equality; longer words match only as prefix + bound morphology suffix
1295
+ // ("deployment" ~ "deploy"), so a prefix share alone never binds ("contractor" is not
1296
+ // "contract", "production backlog" is not "deploy to production"). Quantifier and temporal
1297
+ // fragments (only/just/also/for now/...) are never scope words. All this preserves the P0
1298
+ // isolation: receipt/backlog reading never inherits a deploy order. No stored prompt never
1299
+ // blocks.
1300
+ export function guidanceReanchorsForeignScope(promptText, storedPrompt) {
1301
+ const match = String(promptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()
1302
+ .match(/\b(?:this|current)\s+(?:work|task|change|one)\s+(?:on|for|about|regarding|within|inside)\s+(?:the\s+|this\s+|our\s+)?([a-z0-9][a-z0-9 .\/_()&'-]*?)(?=[!?:;,]|\.(?![a-z0-9])|\r|\n|$)/);
1303
+ if (!match) return false;
1304
+ const prior = String(storedPrompt ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase();
1305
+ if (!prior) return false;
1306
+ const scopeWords = match[1].replace(/[()]/g, ' ').replace(/\.(?![a-z0-9])/g, ' ').split(/[^a-z0-9]+/).filter((w) => w.length >= 2
1307
+ && !['work', 'task', 'this', 'that', 'scope', 'current', 'focus', 'focused', 'change', 'note', 'plan', 'only', 'just', 'also', 'too', 'still', 'again', 'first', 'next', 'then', 'now', 'later', 'the', 'and', 'for', 'our', 'its', 'with', 'into', 'from', 'of', 'to', 'in', 'on', 'at', 'by', 'or'].includes(w));
1308
+ if (scopeWords.length === 0) return false;
1309
+ const priorWords = prior.split(/[^a-z0-9]+/).filter((w) => w.length >= 2);
1310
+ const wordMatches = (w) => priorWords.some((p) => {
1311
+ if (p === w) return true;
1312
+ if (w.length < 4 || p.length < 4) return false;
1313
+ const [short, long] = w.length <= p.length ? [w, p] : [p, w];
1314
+ return long.startsWith(short) && ['s', 'es', 'ed', 'ing', 'ment', 'ments', 'ion', 'ions', 'ly', 'er', 'ers', 'ation', 'ations'].includes(long.slice(short.length));
1315
+ });
1316
+ return !scopeWords.every(wordMatches);
1317
+ }
1318
+
1287
1319
  export function reuseOrMintTaskInstanceId({ previousState = {}, promptText = '', commandText = '', targetFile = null, explicitId = null, continuingTask = false } = {}) {
1288
1320
  const explicit = typeof explicitId === 'string' ? explicitId.trim() : '';
1289
1321
  if (explicit && TASK_INSTANCE_ID_SHAPE.test(explicit)) return { id: explicit, origin: null };
@@ -1301,6 +1333,7 @@ export function reuseOrMintTaskInstanceId({ previousState = {}, promptText = '',
1301
1333
  const guidanceOnly = !targetFile && !commandText
1302
1334
  && Boolean(stored) && Boolean(previousState?.routeSummary?.executionContract?.taskKind)
1303
1335
  && isGuidanceOnlySupplementText(promptText)
1336
+ && !guidanceReanchorsForeignScope(promptText, stored)
1304
1337
  && Array.isArray(previousState?.routeSummary?.executionContract?.completionEvidence)
1305
1338
  && previousState.routeSummary.executionContract.completionEvidence.length > 0
1306
1339
  && previousState?.routeSummary?.continuationState?.required !== false;
@@ -6477,7 +6510,17 @@ export async function persistSharedRouteState(filePath, state, { expectedRouteBy
6477
6510
  // This is a persistence revision, not handoff ownership or generation.
6478
6511
  // Stamp every publication so an A → B → A route cannot recreate its old bytes.
6479
6512
  const published = sidecar ? { ...state, routePersistenceRevision: crypto.randomUUID() } : state;
6480
- if (sidecar) await writeJsonAtomic(sidecar, { sessionId: owner, taskInstanceId: state.taskInstanceId, routeGeneration: state.routeGeneration, routePersistenceRevision: published.routePersistenceRevision, routePublicationIncomplete: true });
6513
+ // The pending marker is the only record of this session while the publication is in flight, so it must carry
6514
+ // the owner STOP. A standing STOP on the committed sidecar survives an interrupted publication unless the new
6515
+ // publication itself carries a control. Fail-closed: a stranded marker keeps the STOP, never drops it.
6516
+ const committedControl = (() => {
6517
+ try {
6518
+ const committed = current === null ? null : JSON.parse(current);
6519
+ return committed?.ownerControl?.kind === 'stop' && committed.sessionId === owner ? committed.ownerControl : null;
6520
+ } catch { return null; }
6521
+ })();
6522
+ const markerControl = state.ownerControl ?? committedControl;
6523
+ if (sidecar) await writeJsonAtomic(sidecar, { sessionId: owner, taskInstanceId: state.taskInstanceId, routeGeneration: state.routeGeneration, routePersistenceRevision: published.routePersistenceRevision, routePublicationIncomplete: true, ...(markerControl ? { ownerControl: markerControl } : {}) });
6481
6524
  // The sidecar lock is held, so no other route writer can publish meanwhile. When the shared write
6482
6525
  // did not happen (lock busy/failed) and the shared slot is provably unchanged, restore the previous
6483
6526
  // committed sidecar instead of stranding a pending marker over a still-valid route.
@@ -2258,7 +2258,10 @@ export async function ownerStopState({ projectRoot, payload = {} } = {}) {
2258
2258
  try {
2259
2259
  const route = JSON.parse(await fs.readFile(path.join(projectRoot, '.ukit/storage/cache/route-state', `${safe}.json`), 'utf8'));
2260
2260
  if (String(route?.sessionId || '').trim() !== String(sessionId).trim()) return { active: false };
2261
- if (route.routePublicationIncomplete === true) return { active: false };
2261
+ // An incomplete publication fails closed for COMPLETION (no task identity is trusted), but the owner STOP it
2262
+ // carries is honoured: the pending marker is written with the standing STOP so an interrupted publication
2263
+ // cannot lift it. Only a marker that itself carries the STOP keeps it active.
2264
+ if (route.routePublicationIncomplete === true && route?.ownerControl?.kind !== 'stop') return { active: false };
2262
2265
  return route?.ownerControl?.kind === 'stop' ? { active: true, control: route.ownerControl } : { active: false };
2263
2266
  } catch {
2264
2267
  return { active: false };