@ngockhoale/ukit 3.4.75 → 3.4.77

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.
@@ -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=c04c341ecd5922273ac127ddd37adf9dccc6c3927f0149b96845bf991bff2014
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:a489851b01e95788d8a3e0a080b80c04d8161c734b6c0ed5c9758a765f5bc0a4';
207
207
 
208
208
  function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
209
209
  return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
@@ -211,7 +211,7 @@ function semanticContractIdentity({ promptText = '', targetFile = '', taskInstan
211
211
  }
212
212
 
213
213
  const semanticContractShape = (contract) => JSON.stringify([
214
- contract?.taskKind, contract?.publication === true, contract?.operationGoal ?? null,
214
+ contract?.taskKind, contract?.publication === true, contract?.operationGoal ?? null, contract?.operationGoals ?? null,
215
215
  contract?.configurationScope ?? null, contract?.releasePolicy ?? null, contract?.conditionalObligations ?? null,
216
216
  contract?.reportArtifact ?? null, contract?.verificationOnly === true, contract?.statusReport === true, contract?.stateVerification === true, contract?.stateAction === true, contract?.stateConditionalStop === true, (contract?.stateTargets || []).join(','),
217
217
  [...(contract?.completionEvidence || [])].sort(),
@@ -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
  }
@@ -348,9 +355,9 @@ const CONDITIONAL_RUNTIME_VERB = /\b(?:redeploy|deploy|restart|khoi dong lai|tri
348
355
  const CONDITIONAL_RUNTIME_EXCLUDED = /\b(?:publish|phat hanh|commit|push|tag|git|implement|fix|edit|modify|sua)\b/;
349
356
  const VERIFICATION_LEAD = /^[-*+\u2022>\d.)\s]*(?:(?:please|hay|vui long|now|also|first)\s+)*(?:verify|check|confirm|validate|inspect|kiem tra|xac nhan)\b/;
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
- const PAST_RELEASE_ITEM = new RegExp(`^(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}`);
358
+ const PAST_RELEASE_ITEM = new RegExp(`^(?:(?:please|just|now|also)\\s+)*(?:${PAST_RELEASE_SOURCE}|release(?:\\s+\\S+)?\\s+(?:(?:co the|may|might|could)\\b|da\\s+len\\b|(?:has|have)\\s+gone\\s+live\\b))`);
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)]
@@ -360,6 +367,54 @@ function defectRepairBranches(text) {
360
367
  && /\b(?:sua|fix|repair)\b/.test(branch));
361
368
  }
362
369
 
370
+ const REVOCATION_ITEM = /\b(?:thu hoi|revoke\w*|rescind\w*|withdraw\w*)\b[^.;\n]*\b(?:deploy|redeploy|publish|publication|release|trien khai|phat hanh)\b/;
371
+ // deploy words prohibit only as a direct ban ("do not deploy"), never as an object inside other prose.
372
+ const DIRECT_DEPLOY_BAN = /^(?:(?:please|hay|vui long)\s+)*(?:do not|don't|dont|never|khong|must not)\s+(?:npm\s+)?(?:re-?deploy|deploy|trien khai)\b/;
373
+ const GATE_QUOTE = /\b(?:prohibits? publication|publication blocked|ukit completion gate|ukit publication)\b|\b(?:bi bao|bao rang|reports?|reported|says?|said|message|thong bao)\b[^.;\n]*\b(?:prohibit\w*|blocked|chan|cam)\b/;
374
+ const GATE_ANCHOR = /\b(?:ukit|gates?|hooks?|logs?)\b|`/;
375
+ const CONTINUATION_NEGATION = /\b(?:do not|don't|dont|never|khong|chua)\s+(?:\w+\s+){0,2}?(?:dung|stop|end|finish|halt|ngung|ket thuc|quit|exit)\b/;
376
+ const PURPOSE_SCOPE = /\b(?:chi de|only to|just to|only for)\b/;
377
+ const CONDITION_LEAD = /\b(?:neu|if|khi|unless|in case|truong hop)\b/;
378
+ const NAME_STOP = new Set(['the', 'a', 'an', 'to', 'on', 'npm', 'if', 'khi', 'neu', 'again', 'now', 'production', 'prod', 'staging', 'artifact', 'image', 'build', 'candidate', 'lai', 'len', 'vao', 'nua', 'qua', 'via', 'tu', 'from', 'with', 'voi', 'any', 'moi', 'khac', 'other', 'another', 'nay', 'package', 'version', 'release', 'publish', 'sau', 'truoc', 'before', 'after', 'while', 'until', 'tren', 'cho', 'khong', 'not', 'and', 'or', 'anything', 'yet', 'this', 'that', 'today', 'packages', 'everything', 'nothing', 'something', 'it', 'them']);
379
+ function authorizedSubjects(promptText) {
380
+ const out = new Set();
381
+ const raw = String(promptText).normalize('NFC').replace(/đ/g, 'd').replace(/Đ/g, 'D').normalize('NFD').replace(/[̀-ͯ]/g, '');
382
+ for (const item of raw.split(/[;\n,]|\.\s+/)) {
383
+ if (PUBLISH_ORDER_NEGATOR.test(item.toLowerCase())) continue;
384
+ for (const m of item.matchAll(/\b(?:[Tt]rien khai|[Dd]eploy|[Rr]edeploy|[Rr]elease|[Pp]hat hanh|[Pp]ublish)\s+(?:the\s+)?([A-Z][A-Za-z0-9_-]{2,})/g)) {
385
+ const name = m[1].toLowerCase();
386
+ if (!NAME_STOP.has(name)) out.add(name);
387
+ }
388
+ }
389
+ return out;
390
+ }
391
+ // Returns null (fail closed: a direct in-scope prohibition) or a non-prohibiting verdict.
392
+ function properNames(promptText) {
393
+ const raw = String(promptText).normalize('NFC').replace(/đ/g, 'd').replace(/Đ/g, 'D').normalize('NFD').replace(/[̀-ͯ]/g, '');
394
+ const out = new Set();
395
+ for (const m of raw.matchAll(/(?<=[^\s.!?;:\n*#>\-\d)][ \t]+)([A-Z][A-Za-z0-9_-]{2,})\b/g)) out.add(m[1].toLowerCase());
396
+ return out;
397
+ }
398
+ const GATE_LEAD = /\b(?:bi bao|bao rang|reports?|reported|says?|said|shows?|showed|message|thong bao|log|logs|gate|gates|hook|hooks)\b/;
399
+ function classifyProhibitionItem(item, authorized, proper) {
400
+ const strongGate = /\b(?:prohibits? publication|publication blocked|ukit completion gate)\b/.test(item);
401
+ const quotedGate = GATE_QUOTE.test(item) && (item.includes('`') || GATE_LEAD.test(item)) && (strongGate || GATE_ANCHOR.test(item));
402
+ if (quotedGate) return { scope: 'quoted', conditional: false };
403
+ if (CONTINUATION_NEGATION.test(item)) {
404
+ // A continuation clause only neutralises itself; a publish ban in a sibling clause survives.
405
+ const rest = item.split(/\s*(?:,|\bva\b|\band\b)\s*/).filter((part) => !CONTINUATION_NEGATION.test(part)).join(' ');
406
+ if (!(PUBLISH_ORDER_NEGATOR.test(rest) && /\b(?:release|publish|publication|deploy)\b/.test(rest))) return { scope: 'continuation', conditional: false };
407
+ item = rest;
408
+ }
409
+ const neg = PUBLISH_ORDER_NEGATOR.exec(item);
410
+ const lead = CONDITION_LEAD.exec(item);
411
+ if (neg && lead && lead.index < neg.index) return { scope: 'workspace', conditional: true };
412
+ if (PURPOSE_SCOPE.test(item) || /\b(?:truoc khi|cho den khi|cho toi khi|until|before|while)\b/.test(item)) return { scope: 'workspace', conditional: true };
413
+ const target = item.match(/\b(?:npm\s+publish|publish|release|deploy|redeploy|trien khai|phat hanh)\s+(?:the\s+)?([a-z][a-z0-9_-]{2,})\b/)?.[1];
414
+ if (target && !NAME_STOP.has(target) && authorized.size && !authorized.has(target) && proper.has(target)) return { scope: 'other', conditional: false };
415
+ return null;
416
+ }
417
+
363
418
  function publicationScope(promptText = '') {
364
419
  const plain = String(promptText).normalize('NFC')
365
420
  .replace(/\bdùng\b/giu, 'su dung').replace(/đừng/giu, 'khong')
@@ -425,7 +480,9 @@ function publicationScope(promptText = '') {
425
480
  lines.push(line);
426
481
  }
427
482
  const text = lines.join('\n');
428
- let prohibited = false;
483
+ const authorized = authorizedSubjects(promptText);
484
+ const proper = properNames(promptText);
485
+ const prohibitions = [];
429
486
  let prohibitionBlock = false;
430
487
  for (const line of text.split('\n')) {
431
488
  if (!line.trim()) continue;
@@ -441,11 +498,18 @@ function publicationScope(promptText = '') {
441
498
  || /\b(?:publish|publication|release)\b[^,]*\b(?:must not|not yet)\b[^,]*\b(?:until|before|while)\b/.test(item)) continue;
442
499
  if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
443
500
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
444
- if (negated && /\b(?:release|publish|publication)\b/.test(item)) prohibited = true;
501
+ const revoked = REVOCATION_ITEM.test(item);
502
+ if (!revoked && !(negated && (/\b(?:release|publish|publication)\b/.test(item) || DIRECT_DEPLOY_BAN.test(item)))) continue;
503
+ let verdict = revoked ? null : classifyProhibitionItem(item, authorized, proper);
504
+ if (!verdict && !revoked && !/\b(?:release|publish|publication)\b/.test(item)) verdict = { scope: 'deploy', conditional: false };
505
+ if (prohibitions.length < 20) prohibitions.push({ span: item.slice(0, 160), line: line.trim().slice(0, 160), ...(verdict || { scope: 'workspace', conditional: false }) });
445
506
  }
446
507
  }
447
508
  }
448
- return { text, prohibited };
509
+ // A deploy-only ban does not prohibit an ordered npm publication; it stands only when no publication is ordered.
510
+ const prohibited = prohibitions.some((entry) => entry.scope === 'workspace' && !entry.conditional)
511
+ || (prohibitions.some((entry) => entry.scope === 'deploy') && !ordersPublicationFromText(text));
512
+ return { text, prohibited, prohibitions };
449
513
  }
450
514
 
451
515
  function ordersPublication(promptText = '') {
@@ -453,7 +517,11 @@ function ordersPublication(promptText = '') {
453
517
  }
454
518
 
455
519
  function ordersPublicationText(promptText = '') {
456
- let active = collapseInspectionSentences(publicationScope(promptText).text).replace(/```[^]*?```|~~~[^]*?~~~/g, '')
520
+ return ordersPublicationFromText(publicationScope(promptText).text);
521
+ }
522
+
523
+ function ordersPublicationFromText(scopedText = '') {
524
+ let active = collapseInspectionSentences(scopedText).replace(/```[^]*?```|~~~[^]*?~~~/g, '')
457
525
  .replace(/^[ \t]*>.*$/gm, '').replace(/[“"][^”"\n]*[”"]|‘[^’\n]*’/g, '');
458
526
  for (const branch of defectRepairBranches(active)) active = active.replace(branch, '');
459
527
  let ordered = false;
@@ -470,10 +538,11 @@ function ordersPublicationText(promptText = '') {
470
538
  if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
471
539
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
472
540
  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);
474
- 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);
541
+ 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);
542
+ 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|history\b|line\b|receipts?\b|lich\s+su\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
543
  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);
544
+ 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)
545
+ || /^(?:(?:sua|kiem thu|hoan tat)\b[^.;\n]*\b(?:va|roi)\s+|(?:va|roi)\s+)(?:phat hanh|xuat ban)\s+npm\b/.test(politeItem);
477
546
  if (!negated && (releaseOrder || viPublish || (publication && (
478
547
  (/^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
548
  || /\b(?:chay|run)\s+`?npm\s+publish\b/.test(item)
@@ -485,8 +554,16 @@ function ordersPublicationText(promptText = '') {
485
554
  return ordered;
486
555
  }
487
556
 
488
- const NOT_A_SERVICE = new Set(['only', 'if', 'unless', 'needed', 'necessary', 'unneeded', 'neu', 'khi', 'can', 'thiet', 'lai', 'len', 'vao', 'tren', 'di', 'nhe', 'nua', 'it', 'this', 'that', 'them', 'the', 'all', 'everything', 'service', 'services', 'again', 'now', 'to', 'and', 'then']);
489
- function nativeOperationGoal(domain, actionable, text) {
557
+ const NOT_A_SERVICE = new Set(['only', 'if', 'unless', 'needed', 'necessary', 'unneeded', 'neu', 'khi', 'can', 'thiet', 'lai', 'len', 'vao', 'tren', 'di', 'nhe', 'nua', 'it', 'this', 'that', 'them', 'the', 'all', 'everything', 'service', 'services', 'again', 'now', 'to', 'and', 'then', 'artifact', 'artifacts', 'image', 'images', 'build', 'qua', 'via', 'through', 'bang', 'tu', 'from', 'voi', 'with', 'toi', 'da', 'nhung', 'moi', 'khac',
558
+ // Vietnamese function words typed without diacritics ("restart rieng X", "trien khai phu hop", "kiem chung").
559
+ 'phu', 'hop', 'rieng', 'kiem', 'chung', 'tra', 'chinh', 'cac', 'mot', 'cua', 'cho', 'de', 'va', 'roi', 'sau', 'duoc', 'theo', 'ngay', 'luon', 'xong', 'het', 'ca', 'thu', 'that', 'dung', 'cung', 'nay', 'do', 'lan', 'tiep', 'thanh', 'cong', 'ban', 'bao', 'gom']);
560
+ // A required service target must be a name the owner actually typed: a word whose diacritics were stripped
561
+ // ("phù" -> "phu", "riêng" -> "rieng") is prose, not a service no native command could ever name.
562
+ function typedToken(name, rawPrompt) {
563
+ if (typeof rawPrompt !== 'string' || !rawPrompt) return true;
564
+ return rawPrompt.toLowerCase().split(/[^\p{L}\p{N}_.-]+/u).some((token) => token === name || token.replace(/[.,:;]+$/, '') === name);
565
+ }
566
+ function nativeOperationGoal(domain, actionable, text, rawPrompt = '') {
490
567
  const goal = { domain, target: null, desiredState: 'verified', completionSemantics: 'execute-and-verify', requiredTargets: [] };
491
568
  const clauses = actionable.join(' . ');
492
569
  if (domain === 'git-integrity') {
@@ -502,9 +579,31 @@ function nativeOperationGoal(domain, actionable, text) {
502
579
  return goal;
503
580
  }
504
581
  const services = [...clauses.matchAll(/\b(?:restart|redeploy|deploy|khoi dong lai|trien khai)\s+(?:the\s+|lai\s+)?([a-z0-9][\w.-]*)/g)]
505
- .map((m) => m[1]).filter((name) => !NOT_A_SERVICE.has(name));
582
+ .map((m) => m[1]).filter((name) => !NOT_A_SERVICE.has(name) && !/^\d+(?:\.\d+)+/.test(name) && !/^[a-z0-9_-]+\.[a-z]{1,5}$/.test(name)
583
+ && name.length >= 2 && typedToken(name, rawPrompt));
506
584
  goal.requiredTargets = [...new Set(services)];
507
- const probePath = text.match(/(?:^|\s)(\/[a-z0-9_.-]+(?:\/[a-z0-9_.-]+)*)/)?.[1] || null;
585
+ const deployScript = clauses.match(/\b(?:via|qua|through|bang)\s+(?:the\s+)?(?:\.\/|[\w./-]*\/)?([\w-]+\.sh)\b/)?.[1] || clauses.match(/(?:^|\s)(?:\.\/|[\w./-]*\/)?([\w-]+\.sh)\s+--deploy/)?.[1] || null;
586
+ // The owner-named deploy script is the single native mutation; project/service words around it are its
587
+ // subject, not separate commands, so they must not become targets no script invocation can ever name.
588
+ if (deployScript) {
589
+ goal.deployCommand = deployScript.slice(0, 64);
590
+ // Drop only the script's own subject: the name right after deploy/trien khai that sits before "via <script>".
591
+ const subject = clauses.match(/\b(?:redeploy|deploy|trien khai)\s+(?:the\s+)?([a-z0-9][\w.-]*)(?:\s+(?:production|prod|staging|artifact|image))*\s+(?:via|qua|through|bang)\s+(?:the\s+)?(?:\.\/|[\w./-]*\/)?[\w-]+\.sh\b/)?.[1];
592
+ goal.requiredTargets = goal.requiredTargets.filter((name) => name !== subject && !/^(?:production|prod|staging)$/.test(name));
593
+ }
594
+ const FS_PATH = /^\/(?:tmp|private|var|users|volumes|home|opt|etc)\b|\.[a-z0-9]{1,5}$/;
595
+ const urlPath = text.match(/\bhttps?:\/\/[^\s/]+(\/[a-z0-9_.\/-]*)/)?.[1];
596
+ const ctxPath = text.match(/\b(?:curl|get|endpoint|health|url)\b[^\n/]{0,20}\s(\/[a-z0-9_.-]+(?:\/[a-z0-9_.-]+)*)/)?.[1];
597
+ // A bare absolute path names the probe only next to a probe word ("verify /v1/models returns 200"); a path in a
598
+ // filesystem context (backup dir, "nam o", folder) never does. Trailing sentence punctuation is not part of it.
599
+ const PROBE_WORD = /\b(?:curl|get|endpoint|health|url|returns?|http|status)\b/;
600
+ const FS_CONTEXT = /\b(?:backups?|nam o|located|thu muc|directory|folder|duoi|under)\b/;
601
+ const barePaths = [...text.matchAll(/(?:^|\s)(\/[a-z0-9_.-]+(?:\/[a-z0-9_.-]+)*)/g)].filter((m) => {
602
+ const near = text.slice(Math.max(0, m.index - 40), m.index + m[0].length + 40);
603
+ return PROBE_WORD.test(near) && !FS_CONTEXT.test(near);
604
+ }).map((m) => m[1]);
605
+ const probePath = [urlPath, ctxPath, ...barePaths].map((candidate) => candidate?.replace(/[.,;:]+$/, ''))
606
+ .find((candidate) => candidate && !FS_PATH.test(candidate) && !FS_CONTEXT.test(candidate)) || null;
508
607
  const probeStatus = text.match(/\b(?:returns?|returning|responds?(?:\s+with)?|http|status(?:\s+code)?)\s+([1-5]\d\d)\b/)?.[1] || null;
509
608
  if (probePath || probeStatus) goal.probe = { path: probePath, status: probeStatus };
510
609
  return goal;
@@ -543,6 +642,11 @@ function neutralizeNonOrders(text) {
543
642
  .replace(/^[ \t]*(?:[-*+\u2022]|\d+[.)])[ \t]*(?:negative|positive)\s+controls?\b[^\n]*(?:\n(?![ \t]*(?:[-*+\u2022]|\d+[.)])|[ \t]*\n)[^\n]*)*/gm, ' ')
544
643
  .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
644
  .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'), ' ')
645
+ // Negated sufficiency ("git commit/tag/release chua du de ban giao", "a git commit is not enough /
646
+ // insufficient"): the negation sits AFTER the operation enumeration, so the khong/chua span strip
647
+ // below would remove only the predicate tail and leave the bare "git commit/tag/release" fragment
648
+ // standing as a phantom imperative. Consume the enumeration together with its negated predicate.
649
+ .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
650
  .replace(new RegExp(`\\b(?:(?:tuyet\\s+doi\\s+)?khong|chua)\\s+[^.;\\n]*?(?=\\s+(?:nhung|tuy nhien)\\b|[.;\\n]|$)`, 'g'), ' ')
547
651
  .replace(/"[^"\n]*\s[^"\n]*"|`[^`\n]*\s[^`\n]*`|\u201c[^\u201d\n]*\u201d/g, ' ')
548
652
  .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 +671,7 @@ function neutralizeNonOrders(text) {
567
671
  });
568
672
  }
569
673
 
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/;
674
+ 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
675
  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
676
  const IMPERATIVE_ORDER = new RegExp(`^(?:[-*+\\u2022>\\d.)\\s]*)(?:(?:please|hay|vui long|now|also|first|then)\\s+)*(?:${ORDER_VERBS})\\b\\s+\\S`);
573
677
  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 +794,9 @@ function isStateOperationRequest(promptText = '') {
690
794
  return plain.split(/[;!?\n]+|[.:](?=\s|$)/).some((clause) => {
691
795
  const lead = clause.match(STATE_LEAD);
692
796
  if (!lead) return false;
797
+ // A clause whose verb is negated ("khong tu kill process", "do not stop the job") states a boundary, not an
798
+ // order to inspect or stop state. Only a negator BEFORE the verb counts: "stop X; do not ..." stays an order.
799
+ if (/\b(?:khong|do not|don't|never|not)\b/.test(clause.slice(0, lead.index))) return false;
693
800
  const after = clause.slice(lead.index + lead[0].length);
694
801
  const near = after.match(/^(?:\s+[\p{L}\p{N}_-]+){0,5}?\s+/u);
695
802
  const window = after.split(/\s+/).slice(0, 7).join(' ');
@@ -736,6 +843,10 @@ function classifySemanticText(input = {}) {
736
843
  return { ...rest, stateVerification: true, ...(shape.action ? { stateAction: true } : shape.conditional ? { stateConditionalStop: true } : {}), ...(shape.targets.length ? { stateTargets: shape.targets } : {}) };
737
844
  }
738
845
 
846
+ // Clauses that order a plain change keep a git+deploy prompt a code task; history/receipt bookkeeping does not.
847
+ const PLAIN_CHANGE_VERB = /\b(?:add|change|remove|delete|bump|rename|update|fix(?:es)?|edit|modify|implement|refactor|create|write|replace|set|toggle|enable|disable|upgrade|install|them|bo sung|xoa|(?<!thay )doi(?!\s+chieu)|sua|tao|viet|chinh|cap nhat)\b/;
848
+ const HISTORY_OBJECT = /\b(?:release(?:\s+history)?|lich su release|receipts?|worklog|ledger|status)\b/;
849
+ const AUTH_EXCLUSION = /\b(?:khong cap phep|not authori[sz]e\w*|does not authori[sz]e|khong duoc phep)\b[^.]*\./g;
739
850
  function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
740
851
  promptText = publicationScope(promptText).text;
741
852
  const releaseText = String(promptText).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
@@ -786,11 +897,23 @@ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
786
897
  }
787
898
  return total > 0 && banned === total;
788
899
  };
789
- const gitOperation = actionable.some((clause) => !operationNotOrdered(clause)
790
- && (GIT_ORDER_LEAD.test(clause) || /\bgit\s+(?:push|clean|commit|reset|rebase|merge|tag|stash|checkout|restore|cherry-pick)\b|\bpush\s+(?:to\s+)?origin\b/.test(clause)));
791
- const runtimeOperation = actionable.some((clause) => !operationNotOrdered(clause) && /(?<!\b(?:process|crash|hard|soft|graceful|after|upon|during|across|following)\s)\b(?:restart|redeploy|deploy|khoi dong lai|trien khai\s+(?:len\s+)?(?:service|server|production|prod|staging|dich vu|may chu|moi truong))\b/.test(clause)
792
- && !/\.[cm]?[jt]sx?\b/.test(clause) && !/\bgit\b/.test(clause));
793
- const nativeDomain = cronOperation ? 'scheduled-job' : gitOperation !== runtimeOperation ? (gitOperation ? 'git-integrity' : 'service-runtime') : null;
900
+ // A status/report wrap-up ("check X and Y results; then docs, commit, report") lists a bare `commit` as
901
+ // bookkeeping next to the report it closes; it is not an ordered history operation with a remote proof.
902
+ const statusWrapUp = /^[\s*+•>\d.)-]*(?:(?:please|hay|vui long)\s+)*(?:check|status|report|show|summari[sz]e|kiem tra|bao cao)\b/.test(actionable[0] || '')
903
+ && actionable.some((clause) => /^[\s*+•>\d.)-]*(?:report|bao cao)\s*$/.test(clause));
904
+ const runtimeClause = (clause) => !operationNotOrdered(clause) && /(?<!\b(?:process|crash|hard|soft|graceful|after|upon|during|across|following)\s)\b(?:restart|redeploy|deploy|khoi dong lai|trien khai\s+(?:len\s+)?(?:service|server|production|prod|staging|dich vu|may chu|moi truong))\b/.test(clause)
905
+ && !/\.[cm]?[jt]sx?\b/.test(clause) && !/\bgit\b/.test(clause);
906
+ const runtimeOperation = actionable.some(runtimeClause);
907
+ // Only a PURE status wrap-up drops its bare commit; one that also orders a deploy keeps the git goal.
908
+ const bookkeepingCommit = (clause) => statusWrapUp && !runtimeOperation && /^[\s*+•>\d.)-]*commit\s*$/.test(clause);
909
+ const gitClause = (clause) => !operationNotOrdered(clause) && !bookkeepingCommit(clause)
910
+ && (GIT_ORDER_LEAD.test(clause) || /\bgit\s+(?:push|clean|commit|reset|rebase|merge|tag|stash|checkout|restore|cherry-pick)\b|\bpush\s+(?:to\s+)?origin\b/.test(clause));
911
+ const gitOperation = actionable.some(gitClause);
912
+ // Commit/push AND a deploy with no source-change order are TWO independent native obligations: each keeps
913
+ // its own proof (git remote parity; deploy receipt + live check). Neither is folded into the other, and
914
+ // owner authorization wording never drops one of them.
915
+ const nativeDomain = cronOperation ? 'scheduled-job' : gitOperation !== runtimeOperation ? (gitOperation ? 'git-integrity' : 'service-runtime')
916
+ : gitOperation && runtimeOperation && !sourceOrder && !codeChangeVerb && actionable.every((clause) => !PLAIN_CHANGE_VERB.test(clause) || /^[\s*+•>\d.)-]*(?:chay|run|verify|kiem tra|check)\b/.test(clause) || (clause.length > 3 && (releaseText.match(AUTH_EXCLUSION) || []).some((span) => span.includes(clause))) || HISTORY_OBJECT.test(clause)) ? 'multi' : null;
794
917
  const operation = Boolean(nativeDomain);
795
918
  if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', ...(bansTestRuns(promptText) ? {} : { verificationOnly: true }) };
796
919
  const CONFIG_CHANGE_REPORT_CLAUSE = /\b(?:da|has|have|had|already)\s+(?:doi|thay doi|changed?|updated?)\b|\b(?:nao|gi|which|what|report|bao cao)\b[^.;]*?\b(?:doi|thay doi|changed?|updated?)\b/;
@@ -824,8 +947,13 @@ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
824
947
  const taskKind = operation ? (sourceOrder || codeChangeVerb ? 'MIXED' : 'OPERATIONAL')
825
948
  : config ? 'CONFIGURATION' : documentation ? 'DOCUMENTATION_OUTPUT' : readOnly ? 'READ_ONLY' : 'CODE_IMPLEMENTATION';
826
949
  const id = text.match(/\b[a-f0-9]{8}(?:[a-f0-9-]{0,28})\b/)?.[0] || null;
950
+ // Multi-operation: the goal ordered first is the primary `operationGoal`; `operationGoals` carries all of them.
951
+ const operationGoals = nativeDomain === 'multi'
952
+ ? (actionable.findIndex(gitClause) <= actionable.findIndex(runtimeClause) ? ['git-integrity', 'service-runtime'] : ['service-runtime', 'git-integrity'])
953
+ .map((domain) => nativeOperationGoal(domain, actionable, text, promptText)) : null;
827
954
  return { taskKind, ...(releasePolicy ? { releasePolicy } : {}), ...(documentation ? { reportArtifact } : {}), ...(taskKind === 'READ_ONLY' && statusReport ? { statusReport: true } : {}), ...(config ? { configurationScope: repository ? 'repository' : 'external' } : {}),
828
- ...(operation && nativeDomain !== 'scheduled-job' ? { operationGoal: nativeOperationGoal(nativeDomain, actionable, text) } : {}),
955
+ ...(operationGoals ? { operationGoal: operationGoals[0], operationGoals } : {}),
956
+ ...(operation && !operationGoals && nativeDomain !== 'scheduled-job' ? { operationGoal: nativeOperationGoal(nativeDomain, actionable, text, promptText) } : {}),
829
957
  ...(operation && nativeDomain === 'scheduled-job' ? { operationGoal: { domain: 'scheduled-job', target: id, desiredState: /\b(?:delete|remove|cancel|xoa|huy|absent|removed|deleted|no longer|khong con)\b/.test(actionable.join(' ')) ? 'absent' : 'present',
830
958
  completionSemantics: /\b(?:ensure|dam bao)\b/.test(text)
831
959
  || actionable.some((clause) => /\b(?:delete|remove|cancel|xoa|huy)\b/.test(clause)
@@ -4280,6 +4408,7 @@ function applyTaskSemantics(contract, semantic) {
4280
4408
  // The task identity is minted on a fresh owner prompt and retained only on
4281
4409
  // the router's continuation lineage. It is also the route generation.
4282
4410
  persisted.routeGeneration = taskInstanceId;
4411
+ if (predecessorLink) persisted.predecessor = predecessorLink; else delete persisted.predecessor;
4283
4412
  // Bounded audit metadata (short strings, additive): where this turn's task id and
4284
4413
  // contract came from — 'system' marks a synthetic continuation that resumed the
4285
4414
  // previous task instead of minting a fresh one. No consumer branches on these yet.
@@ -4470,7 +4599,16 @@ function applyTaskSemantics(contract, semantic) {
4470
4599
  const readOrNull = async (file) => { try { return await fsp.readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
4471
4600
  const priorSidecar = sessionId ? await readOrNull(sessionRoutePath) : null;
4472
4601
  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 }));
4602
+ // The pending marker is the only session record while the publication is in flight: it carries the owner STOP
4603
+ // (from this publication, else the committed sidecar it replaces) so an interrupted publication cannot lift it.
4604
+ const committedStop = (() => {
4605
+ try {
4606
+ const committed = priorSidecar === null ? null : JSON.parse(priorSidecar);
4607
+ return committed?.ownerControl?.kind === 'stop' && committed.sessionId === sessionId ? committed.ownerControl : null;
4608
+ } catch { return null; }
4609
+ })();
4610
+ const markerControl = persisted.ownerControl ?? committedStop;
4611
+ if (sessionId) await writeJsonFileAtomic(sessionRoutePath, JSON.stringify({ sessionId, taskInstanceId, routeGeneration: persisted.routeGeneration, routePersistenceRevision: persisted.routePersistenceRevision, routePublicationIncomplete: true, ...(markerControl ? { ownerControl: markerControl } : {}) }));
4474
4612
  try {
4475
4613
  await writeJsonFileAtomic(statePath, text);
4476
4614
  } catch (error) {
@@ -4590,21 +4728,62 @@ function applyTaskSemantics(contract, semantic) {
4590
4728
  const buf = Buffer.alloc(len);
4591
4729
  fs.readSync(fd, buf, 0, len, size - len);
4592
4730
  const lines = buf.toString('utf8').split('\n');
4731
+ // Host-authored proof of a PEER delivery: a queued_command attachment whose origin the host
4732
+ // stamped as 'peer', bound to this session and to the exact prompt text. The envelope text
4733
+ // alone is never proof (a human can paste it); only the host's attachment counts.
4734
+ const peerDeliveryIds = new Set();
4735
+ for (const l of lines) {
4736
+ if (!l || !l.includes('queued_command')) continue;
4737
+ let a; try { a = JSON.parse(l); } catch { continue; }
4738
+ const at = a?.attachment;
4739
+ if (a.type === 'attachment' && at?.type === 'queued_command' && at.origin?.kind === 'peer'
4740
+ && typeof at.delivery_id === 'string' && sessionId && a.sessionId === sessionId
4741
+ && typeof at.prompt === 'string' && at.prompt.trim() === promptTrim) {
4742
+ peerDeliveryIds.add(at.delivery_id);
4743
+ }
4744
+ }
4745
+ let deliveryCurrent = true;
4593
4746
  for (let i = lines.length - 1; i >= 0; i -= 1) {
4594
4747
  const line = lines[i];
4595
4748
  if (!line) continue;
4596
4749
  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'
4750
+ // A response after a queued delivery means that delivery belongs to an earlier turn;
4751
+ // never let its text exempt a later owner prompt. Host hook metadata may follow the
4752
+ // delivery before this hook runs, but an assistant message is a turn boundary.
4753
+ if (entry.type === 'assistant' && entry.isSidechain !== true) deliveryCurrent = false;
4754
+ // Queued deliveries are not user orders. Require the host's consumed delivery record, exact
4755
+ // content and this session's owner. An enqueue, a foreign delivery or a human-pasted envelope
4756
+ // is not proof. A peer agent-message counts only with the host's peer attachment for that delivery.
4757
+ if (deliveryCurrent && entry.type === 'queue-operation' && entry.operation === 'remove'
4601
4758
  && entry.reason === 'absorbed_mid_turn' && entry.deliveryId
4602
4759
  && sessionId && entry.sessionId === sessionId
4603
4760
  && typeof entry.content === 'string' && entry.content.trim() === promptTrim
4604
- && /^<cross-session-message\s/.test(promptTrim)) {
4761
+ && (/^<cross-session-message\s/.test(promptTrim)
4762
+ || (/^<agent-message\s/.test(promptTrim) && peerDeliveryIds.has(entry.deliveryId)))) {
4605
4763
  coordinationTurn = true;
4606
4764
  return false;
4607
4765
  }
4766
+ // Host-authored wakeup provenance that exists at hook time: the scheduled_task_fire system
4767
+ // entry (the meta user entry is written only AFTER this hook runs). Same session, a task id,
4768
+ // the current turn, and the prompt equal to - or a >=40 char truncated prefix of (the /loop
4769
+ // fire record clips to ~200 chars) - the typed prompt. A human typing the text leaves no fire.
4770
+ if (deliveryCurrent && entry.type === 'system' && entry.subtype === 'scheduled_task_fire'
4771
+ && sessionId && entry.sessionId === sessionId
4772
+ && typeof entry.taskId === 'string' && entry.taskId.trim()
4773
+ && typeof entry.prompt === 'string') {
4774
+ const fired = entry.prompt.trim();
4775
+ const firedBase = fired.replace(/(?:\u2026|\.{3})+$/, '').trim();
4776
+ // Prefix match only for a CLIPPED fire (ellipsis, or at the host's ~200-char clip, which real fires
4777
+ // reach without an ellipsis); an unclipped fire plus owner-appended text is an owner prompt.
4778
+ const clipped = firedBase !== fired || entry.prompt.length >= 190;
4779
+ if (fired && (fired === promptTrim || (clipped && firedBase.length >= 40 && promptTrim.startsWith(firedBase)))) {
4780
+ if (classifyTaskSemantics({ promptText: promptTrim }).taskKind === 'READ_ONLY') {
4781
+ coordinationTurn = true;
4782
+ return false;
4783
+ }
4784
+ return true;
4785
+ }
4786
+ }
4608
4787
  if (entry.type !== 'user' || entry.isSidechain === true) continue;
4609
4788
  const content = entry.message?.content;
4610
4789
  const text = (typeof content === 'string' ? content
@@ -4747,6 +4926,34 @@ function applyTaskSemantics(contract, semantic) {
4747
4926
  if (GUIDANCE_MUTATION_VERB.test(guidanceResidue)) return false;
4748
4927
  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
4928
  }
4929
+ // Re-anchored linkage: "keep this work on the X" names X as the NOTE's topic. X binds only
4930
+ // when EVERY content word of X matches the task's own explicit prompt. Scope reading is
4931
+ // deterministic, not semantic: the phrase may contain slashes, ampersands, dotted FILE
4932
+ // names (punctuation followed by an alphanumeric stays inside the scope, so
4933
+ // "package.json" is one name, never truncated to "package") and quoted or parenthesized
4934
+ // parts (parentheticals are asides and are stripped); it ends at punctuation, a NEWLINE
4935
+ // or end of text. Words of 2-3 chars (API, CLI, MCP) count by EXACT equality; longer
4936
+ // words match only as prefix + bound morphology suffix ("deployment" ~ "deploy"), so a
4937
+ // prefix share alone never binds ("contractor" is not "contract", "production backlog"
4938
+ // is not "deploy to production"). Quantifier and temporal fragments (only/just/also/
4939
+ // for now/...) are never scope words. All this keeps the P0 isolation: receipt or
4940
+ // backlog reading never inherits a deploy order.
4941
+ 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|$)/);
4942
+ if (reanchoredScope) {
4943
+ const priorPrompt = String(previous.routingContext?.lastExplicitUserPromptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase();
4944
+ if (priorPrompt) {
4945
+ const scopeWords = reanchoredScope[1].replace(/[()]/g, ' ').replace(/\.(?![a-z0-9])/g, ' ').split(/[^a-z0-9]+/).filter((w) => w.length >= 2
4946
+ && !['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));
4947
+ const priorWords = priorPrompt.split(/[^a-z0-9]+/).filter((w) => w.length >= 2);
4948
+ const wordMatches = (w) => priorWords.some((p) => {
4949
+ if (p === w) return true;
4950
+ if (w.length < 4 || p.length < 4) return false;
4951
+ const [short, long] = w.length <= p.length ? [w, p] : [p, w];
4952
+ return long.startsWith(short) && ['s', 'es', 'ed', 'ing', 'ment', 'ments', 'ion', 'ions', 'ly', 'er', 'ers', 'ation', 'ations'].includes(long.slice(short.length));
4953
+ });
4954
+ if (scopeWords.length > 0 && !scopeWords.every(wordMatches)) return false;
4955
+ }
4956
+ }
4750
4957
  if (!previous.taskInstanceId) return false;
4751
4958
  const contract = previous.routeSummary?.executionContract;
4752
4959
  if (!contract?.taskKind) return false;
@@ -4771,6 +4978,18 @@ function applyTaskSemantics(contract, semantic) {
4771
4978
  return wanted.size > 0 && [...wanted].every((target) => owned.has(target));
4772
4979
  })();
4773
4980
  const continuingTask = Boolean(previous.taskInstanceId && (payload.tool_name || handoffExpansion || continuationPrompt || ownerResumeTurn || systemOriginTurn || guidanceTurn));
4981
+ // An owner prompt that explicitly resumes the previous checkpoint (names its background job id or commit)
4982
+ // still mints a fresh task id - the contract may legitimately differ (e.g. a new deploy authorization) -
4983
+ // but records a bounded single-hop predecessor link so the ledger can reconcile current evidence. A
4984
+ // genuinely new task has no such reference and gets no link.
4985
+ let predecessorLink = null;
4986
+ if (!continuingTask && sessionId && previous.taskInstanceId && String(previous.sessionId || '') === sessionId
4987
+ && !payload.tool_name && promptOrigin !== 'system' && previous.ownerControl?.kind !== 'stop') {
4988
+ try {
4989
+ const ledgerRuntime = await import(pathToFileURL(path.join(projectRoot, '.claude', 'ukit', 'runtime', 'execution-ledger.mjs')).href);
4990
+ predecessorLink = await ledgerRuntime.checkpointPredecessorLink(projectRoot, payload, extractPrompt(payload), previous);
4991
+ } catch { predecessorLink = null; }
4992
+ }
4774
4993
  let taskInstanceId = continuingTask
4775
4994
  ? previous.taskInstanceId
4776
4995
  : `task-${crypto.randomBytes(16).toString("hex")}`;