@ngockhoale/ukit 3.4.74 → 3.4.75

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.
@@ -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:287d478b06a81ac1f9fcc1c53fd00217ab13bf6af53aca3bd662df0989e30b5e';
3
+ export const SEMANTIC_ENGINE_VERSION = 'round4-semantic-1:d2c70fa8c68d50f31917ee7befd16f6df36a441a2aae79a0de879f5b0a09edf1';
4
4
 
5
5
  export function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
6
6
  return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
@@ -10,7 +10,7 @@ export function semanticContractIdentity({ promptText = '', targetFile = '', tas
10
10
  const semanticContractShape = (contract) => JSON.stringify([
11
11
  contract?.taskKind, contract?.publication === true, contract?.operationGoal ?? null,
12
12
  contract?.configurationScope ?? null, contract?.releasePolicy ?? null, contract?.conditionalObligations ?? null,
13
- contract?.reportArtifact ?? null, contract?.verificationOnly === true, contract?.statusReport === true,
13
+ contract?.reportArtifact ?? null, contract?.verificationOnly === true, contract?.statusReport === true, contract?.stateVerification === true, contract?.stateAction === true, contract?.stateConditionalStop === true, (contract?.stateTargets || []).join(','),
14
14
  [...(contract?.completionEvidence || [])].sort(),
15
15
  ]);
16
16
  export function compareSemanticContracts({ stored, fresh, previousIdentity, identity }) {
@@ -45,7 +45,7 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
45
45
  const quoted = Boolean(marker || fence || /^\s*>/.test(raw));
46
46
  const context = quoted ? 'quotation' : description && bullet ? 'description' : 'instruction';
47
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)\b[^,;.\n]*/)?.[0] || null;
48
+ const condition = text.match(/\b(?:if|neu|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
  }
@@ -65,10 +65,23 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
65
65
  const nativeReleasePolicy = classifySemanticText({ promptText: original, targetFile }).releasePolicy;
66
66
  const deferredSpans = new Set(spans.filter(span => span.context === 'instruction'
67
67
  && span.polarity === 'affirmative' && span.condition
68
- && /^(?:[-*+•\d.)\s]*)(?:if|neu|only if|only when)\b/.test(foldIntent(span.raw))
68
+ && /^(?:[-*+•\d.)\s]*)(?:if|neu|only if|only when|only after|only once)\b/.test(foldIntent(span.raw))
69
69
  && !nativeReleasePolicy && !VERIFICATION_GOAL.test(foldIntent(original))
70
70
  && !defectRepairBranches(foldIntent(span.raw)).length
71
71
  && ordersPublicationText(foldIntent(span.raw).replace(/^[^,]*,\s*/, ''))));
72
+ spans.forEach((span, index) => {
73
+ const folded = foldIntent(span.raw);
74
+ const verb = folded.match(CONDITIONAL_RUNTIME_VERB);
75
+ const cond = span.condition ? folded.indexOf(span.condition) : -1;
76
+ if (!verb || cond < 0 || span.context !== 'instruction' || span.polarity !== 'affirmative' || nativeReleasePolicy
77
+ || CONDITIONAL_RUNTIME_EXCLUDED.test(folded)) return;
78
+ const governed = verb.index >= cond || /^(?:only\s+(?:if|when)|unless)\b/.test(span.condition);
79
+ if (!NEED_OR_FAILURE_CONDITION.test(span.condition)) return;
80
+ const leadsVerification = VERIFICATION_LEAD.test(folded.slice(0, cond)) && cond > 0
81
+ || spans.slice(0, index).some(prior => prior.context === 'instruction' && prior.polarity === 'affirmative'
82
+ && !prior.condition && VERIFICATION_LEAD.test(foldIntent(prior.raw)));
83
+ if (governed && leadsVerification) deferredSpans.add(span);
84
+ });
72
85
  // An explicit alternative links both consequences. Keep the unconditional
73
86
  // review prefix, but do not require a repair before its review has found one.
74
87
  const alternatives = spans.filter(span => span.condition?.startsWith('otherwise:'));
@@ -86,7 +99,7 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
86
99
  if (span.context === 'quotation' || span.context === 'description' || approvalPending || deferredSpans.has(span) || evidenceStatement) {
87
100
  // Retain the prefix before a comma-introduced postfix repair condition.
88
101
  // Leading conditions and otherwise consequences are masked in full.
89
- const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|otherwise)\b/.test(foldIntent(span.raw))
102
+ const prefix = deferredSpans.has(span) && !/^(?:\s*)(?:if|neu|only if|only when|only after|only once|otherwise)\b/.test(foldIntent(span.raw))
90
103
  ? span.raw.match(/^[^,]*,/)?.[0] || '' : '';
91
104
  const masked = prefix + span.raw.slice(prefix.length).replace(/[^\r\n]/g, ' ');
92
105
  semanticInput = semanticInput.slice(0, span.start) + masked + semanticInput.slice(span.end);
@@ -127,6 +140,12 @@ export function analyzeTaskIntent({ promptText = '', targetFile = '', taskInstan
127
140
  }
128
141
  return { engineVersion: SEMANTIC_ENGINE_VERSION, identity: { taskInstanceId, sessionId }, original, spans, actions, semantic };
129
142
  }
143
+ const NEED_OR_FAILURE_CONDITION = /\b(?:needed|necessary|required|requires?|broken|fails?|failed|failing|failure|down|unhealthy|stale|missing|wrong|errors?|crash\w*|unavailable|not\s+(?:working|healthy|running|live|ok)|neu\s+(?:can|loi|hong|that bai|thieu|sai|chet)|khi\s+can|loi)\b|^unless\s+(?:healthy|ok|working|running|live)\b/;
144
+ const CONDITIONAL_RUNTIME_VERB = /\b(?:redeploy|deploy|restart|khoi dong lai|trien khai)\b/;
145
+ const CONDITIONAL_RUNTIME_EXCLUDED = /\b(?:publish|phat hanh|commit|push|tag|git|implement|fix|edit|modify|sua)\b/;
146
+ const VERIFICATION_LEAD = /^[-*+\u2022>\d.)\s]*(?:(?:please|hay|vui long|now|also|first)\s+)*(?:verify|check|confirm|validate|inspect|kiem tra|xac nhan)\b/;
147
+ 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
+ const PAST_RELEASE_ITEM = new RegExp(`^(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}`);
130
149
  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/;
131
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/;
132
151
  const PUBLISH_ORDER_HEADER = /prohibit|forbidden|out of scope|non-goal|scope control/;
@@ -249,7 +268,7 @@ function ordersPublicationText(promptText = '') {
249
268
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
250
269
  const commandItem = item.replace(/^(?:please|just|now|also|then)\s+/, '');
251
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);
252
- const releaseOrder = /^(?: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);
271
+ 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);
253
272
  const politeItem = item.replace(/^(?:(?:please|just|now|also|then|vui long|hay)\s+)+/, '');
254
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);
255
274
  if (!negated && (releaseOrder || viPublish || (publication && (
@@ -263,7 +282,7 @@ function ordersPublicationText(promptText = '') {
263
282
  return ordered;
264
283
  }
265
284
 
266
- const NOT_A_SERVICE = new Set(['it', 'this', 'that', 'them', 'the', 'all', 'everything', 'service', 'services', 'again', 'now', 'to', 'and', 'then']);
285
+ 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']);
267
286
  function nativeOperationGoal(domain, actionable, text) {
268
287
  const goal = { domain, target: null, desiredState: 'verified', completionSemantics: 'execute-and-verify', requiredTargets: [] };
269
288
  const clauses = actionable.join(' . ');
@@ -315,6 +334,7 @@ function neutralizeNonOrders(text) {
315
334
  return source.replace(noVerbList(), ' ')
316
335
  .replace(/\brelease-(?:publication|verification)\b|\brelease\s+(?:instructions?|authorization|obligations?|policies|readiness)\b/g, 'publication topic')
317
336
  .replace(/\brelease\s+(?:safety|verification\s+plan)\b/g, 'publication topic')
337
+ .replace(new RegExp(`(^|[\\n.;]\\s*)(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}[^.;\\n]*`, 'g'), '$1publication topic')
318
338
  .replace(/^[ \t]*[-*+•][ \t]*owner\s+yeu\s+cau\b[^\n]*/gm, ' ')
319
339
  .replace(/^([ \t]*[-*+•][ \t]*)release\s+progress\s+reporter(?=[ \t]*(?:,|$))/gm, '$1progress reporter')
320
340
  .replace(/^[ \t]*(?:[-*+\u2022]|\d+[.)])[ \t]*(?:negative|positive)\s+controls?\b[^\n]*(?:\n(?![ \t]*(?:[-*+\u2022]|\d+[.)])|[ \t]*\n)[^\n]*)*/gm, ' ')
@@ -325,6 +345,8 @@ function neutralizeNonOrders(text) {
325
345
  .replace(/\b(?:uu tien|prefer(?:red)?)\s+(?:a\s+|an\s+)?(?:configuration|config|cau hinh)\s+(?:change|changes|update|thay doi)\b/g, ' ')
326
346
  .replace(/\b(?:neu\s+(?:chi\s+)?(?:phai|can|thieu|khong du|bang chung chua du)(?![^.;\n]*\b(?:restart|deploy|xoa|delete|remove|cancel)\b)|if\s+(?:needed|necessary|required|evidence is insufficient))\b[^.;\n]*/g, ' ')
327
347
  .replace(/[^.;\n]*\b(?:nao|gi|sao|the nao|bao nhieu)\b[^.;\n]*\?/g, ' ')
348
+ .replace(/\b(?:truoc khi|before)\s+(?:quay lai|tro lai|returning|going back|you (?:go|return)|we (?:go|return))\b[^.;\n]*/g, ' ')
349
+ .replace(/\b(?:cua|do|tu)\s+chinh\b|\bchinh\s+(?:cac|nhung|phien|no|minh|toi|ban than)\b/g, ' ')
328
350
  .replace(/\bchinh\s+(?:xac|sach)\b|\b(?:phuong an|cach|de xuat|ban)\s+(?:sua|fix)\b|\b(?:diem|cho|muc|phan)\s+(?:phai|can|nen)\s+(?:sua|fix)\b/g, ' ')
329
351
  .replace(/\bwrite\s*\/\s*verification\b|\bverification\s*\/\s*write\b|\bwrite\s+(?:or|and)\s+verification\b/g, ' ')
330
352
  .replace(/\bwrite\s+permission\b/g, 'permission')
@@ -372,6 +394,13 @@ function declaredReadOnly(promptText, releasePolicy) {
372
394
 
373
395
  const VERIFY_LEAD = /^(?:[-*+•>\d.)\s]*)(?:(?:please|hay|vui long|now|also|first|then)\s+)*(?:(?:keep|continue|tiep tuc)\s+)?(?:verify|re-?run|confirm|xac nhan|validate|double-?check|wait(?:ing)?|monitor|watch|cho(?=\s+(?:dung\s+)?(?:job|verifier|build|test|suite|gate|ci|run|task|ket qua|xong|output)\b))\b/;
374
396
  const CHANGE_LEAD = /^(?:[-*+•>\d.)\s]*)(?:(?:please|hay|vui long|now|also|first|then)\s+)*(?:make|rebuild|redo|rewrite|restore|revert|correct|clean|patch|resolve|ensure|run(?!(?=[^.]*\b(?:tests?|suite|gate|checks?|lint|typecheck|pilot|smoke|e2e|verif\w*|vitest|jest|audit)\b)))\b/;
397
+ const BANS_TEST_RUNS = /\b(?:do not|don't|never|khong|dung)\s+(?:run|execute|chay)\s+(?:(?:any|more|additional|extra|them)\s+)*(?:tests?|checks?|verifications?)\b(?:\s+on\s+\w+)?/g;
398
+ const OWN_TARGET = /\b(?:yarn|npm|npx|pnpm|vitest|jest|pytest|node)\s+\S|\b(?:staging|ci|job|build|release(?!\s+notes?)|published|integration|e2e)\b/;
399
+ const bansTestRuns = (promptText) => {
400
+ const plain = String(promptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
401
+ const bans = plain.match(BANS_TEST_RUNS);
402
+ return !!bans && !bans.some((ban) => /\bon\s+\w+$/.test(ban)) && !OWN_TARGET.test(plain.replace(BANS_TEST_RUNS, ' '));
403
+ };
375
404
  export function isVerificationOnlyRequest(promptText) {
376
405
  const plain = String(promptText ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase()
377
406
  .replace(/```[\s\S]*?```/g, ' ').replace(/^[ \t]*>.*$/gm, ' ');
@@ -395,6 +424,27 @@ function neutralizeBannedLists(text) {
395
424
  });
396
425
  }
397
426
 
427
+ const OWNER_CONTROL_HOOK_TEXT = /^\s*(?:UKit completion gate:|UKit handoff|\[ukit[-\w]*\]|<system-reminder|<task-notification)/i;
428
+ const OWNER_STOP_EN = /^(?:please\s+)?(?:stop|halt|pause|cancel|abort)(?:\s+(?:all|everything|execution|executing|work|working|now|immediately|here|this|the|current|session|run|task|tasks|handoff|processing))*$/;
429
+ const OWNER_STOP_VI = /^(?:(?:tam\s+)?(?:dừng|ngừng)|(?:tạm\s+)?(?:dừng|ngừng)|hủy|huỷ|tam\s+dung|tam\s+ngung|ngung|dung\s+(?:lai|thuc\s+thi|ngay)|huy)(?:\s+(?:thực\s+thi|thuc\s+thi|phiên\s+này|phien\s+nay|phiên|phien|lại|lai|ngay|ngay\s+lập\s+tức|tất\s+cả|tat\s+ca|mọi\s+thứ|moi\s+thu|việc|viec|công\s+việc|cong\s+viec|run|handoff|session|task))*$/;
430
+ const OWNER_CONTROL_TASK_WORD = /\b(?:fix|implement|add|update|edit|write|create|deploy|redeploy|publish|commit|refactor|rewrite|install|sua|sửa|them|thêm|chay|chạy|cap nhat|cập nhật)\b|[\w-]+\/[\w.-]+/;
431
+ const OWNER_CONTROL_TASK_LEAD = /^(?:(?:and\s+)?then|also|afterwards?|after that|next|now|sau do|sau đó|roi|rồi|va|và)\b|^(?:please\s+)?(?:fix|implement|add|update|edit|write|create|run|deploy|redeploy|publish|commit|push|refactor|rewrite|install|build|sua|sửa|them|thêm|chay|chạy|trien khai|triển khai|cap nhat|cập nhật)\b/;
432
+ export function classifyOwnerControl(promptText = '') {
433
+ const raw = String(promptText ?? '').normalize('NFC').trim();
434
+ if (!raw || OWNER_CONTROL_HOOK_TEXT.test(raw)) return { kind: null };
435
+ const stripped = raw.replace(/^[\s*#_-]+/, '');
436
+ if (/^[>"'`\u201c\u2018]/.test(stripped)) return { kind: null };
437
+ const sentences = stripped.split(/[.!?\n]/);
438
+ const [lead, ...rest] = sentences[0].split(/[:;]/);
439
+ const first = lead.trim().toLowerCase().replace(/\s+/g, ' ');
440
+ if (!first || first.length > 80) return { kind: null };
441
+ if (OWNER_CONTROL_TASK_WORD.test(rest.join(' ').toLowerCase())) return { kind: null };
442
+ if (!OWNER_STOP_EN.test(first) && !OWNER_STOP_VI.test(first)) return { kind: null };
443
+ const next = (sentences.slice(1).find((part) => part.trim()) || '').trim().toLowerCase();
444
+ if (OWNER_CONTROL_TASK_LEAD.test(next)) return { kind: null };
445
+ return { kind: 'stop' };
446
+ }
447
+
398
448
  export function classifyTaskSemantics(input = {}) {
399
449
  return analyzeTaskIntent(input).semantic;
400
450
  }
@@ -409,7 +459,7 @@ const collapseInspectionSentences = (text) => text.replace(INSPECTION_SENTENCE,
409
459
 
410
460
  function actionableClauses(promptText) {
411
461
  const text = neutralizeBannedLists(neutralizeNonOrders(collapseInspectionSentences(String(promptText).normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[đĐ]/g, 'd').toLowerCase())));
412
- const clauses = text.split(/\s*(?:[;\n,]|\.(?:\s+|$)|\band\b|\bthen\b|\bva\b)\s*/);
462
+ const clauses = text.split(/\s*(?:[;\n,]|\.(?:\s+|$)|\band\b|\bthen\b|\bva\b|\broi\b(?=\s+(?:redeploy|deploy|restart|khoi dong lai|trien khai)\b))\s*/);
413
463
  const actionable = clauses.map((clause) => clause.split(/\bwithout\b/)[0]).filter((clause) => !/\b(?:do not|don't|never|khong)\b|^[\s*+•>\d.)-]*(?:(?:vui long|xin|hay|please)\s+)*dung\b/.test(clause)
414
464
  && !/^[\s*+•>\d.)-]*(?:(?:please|just|hay|vui long|now|also)\s+)*(?:audit|inspect|review|analyze|analyse|explain|read|kiem tra|phan tich)\b/.test(clause)
415
465
  // A fragment led by a subordinator continues the previous clause's predicate ("…, including source
@@ -424,7 +474,66 @@ export function ordersAdditiveChange(promptText = '') {
424
474
  return actionableClauses(publicationScope(promptText).text).actionable.some((clause) => ADDITIVE_ORDER_LEAD.test(clause));
425
475
  }
426
476
 
427
- function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
477
+ const STATE_OBJECT = /\b(?:shells?|jobs?|process(?:es)?|pids?|agents?|subagents?|wakeups?|tien trinh|tac vu nen|background (?:tasks?|work)|crons?)\b/;
478
+ const STATE_LEAD = /\b(?:check|inspect|list|stop|cancel|kill|terminate|revoke|reclaim|kiem tra|liet ke|xac dinh|huy|thu hoi|ket thuc)\b/;
479
+ const STATE_ACTION = /\b(?:stop|cancel|kill|terminate|revoke|reclaim|dung|huy|thu hoi|ket thuc)\b/;
480
+ function statePlain(promptText) {
481
+ return String(promptText).normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[\u0111\u0110]/g, 'd').toLowerCase()
482
+ .replace(/```[\s\S]*?```/g, ' ').replace(/^[ \t]*>.*$/gm, ' ');
483
+ }
484
+ export function isStateOperationRequest(promptText = '') {
485
+ const plain = statePlain(promptText);
486
+ if (!/\b(?:running|still|live|background|wakeups?|pids?|hung|stuck|orphan\w*|leftover|reclaim|chay|nen|treo|con sot|\d+\s+(?:shells?|jobs?|agents?|subagents?|process(?:es)?)|(?:job|task|shell|agent)\s+(?:id\s+)?[a-z0-9]*\d[a-z0-9]{5,})\b/.test(plain)) return false;
487
+ return plain.split(/[;!?\n]+|[.:](?=\s|$)/).some((clause) => {
488
+ const lead = clause.match(STATE_LEAD);
489
+ if (!lead) return false;
490
+ const after = clause.slice(lead.index + lead[0].length);
491
+ const near = after.match(/^(?:\s+[\p{L}\p{N}_-]+){0,5}?\s+/u);
492
+ const window = after.split(/\s+/).slice(0, 7).join(' ');
493
+ return near !== null && STATE_OBJECT.test(window);
494
+ });
495
+ }
496
+
497
+ export function stateOperationShape(promptText = '') {
498
+ const plain = statePlain(promptText);
499
+ const unquoted = plain.replace(/`[^`\n]*`|"[^"\n]*"|\u201c[^\u201d\n]*\u201d/g, ' ');
500
+ const targets = [...new Set((unquoted.match(/(?<![\w-])[a-z]*\d[a-z0-9]{7,}\b/g) || []).filter((id) => /[a-z]/.test(id)))].slice(0, 8);
501
+ let conditional = false;
502
+ let gated = false;
503
+ const action = plain.split(/[;!?\n]+|[.:](?=\s|$)|,\s*/).some((raw) => {
504
+ const clause = raw.replace(/^[\s*\-\d.)]+/, '').trim();
505
+ if (!clause) return false;
506
+ const conditionLead = /^(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause);
507
+ if (!conditionLead && /\b(?:khong|do not|don't|never|not)\b/.test(clause)) return false;
508
+ if (/\b(?:cho phep|allow(?:ed|s)?|permit(?:ted)?|authori[sz]ed?|you may|may stop|duoc phep)\b/.test(clause)) { gated = false; return false; }
509
+ const head = clause.split(/\s+/).slice(0, 3).join(' ');
510
+ if (/\b(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause)) {
511
+ const leadsWithCondition = /^(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/.test(clause);
512
+ const preCondition = leadsWithCondition ? '' : clause.split(/\b(?:if|when|unless|neu|khi|truoc khi|sau khi)\b/)[0].trim();
513
+ if (preCondition && /\b(?:and|va|then|roi)\s+(?:stop|cancel|kill|terminate|revoke|reclaim|dung|huy|thu hoi|ket thuc)\b/.test(preCondition)) { conditional = true; return false; }
514
+ const consequent = leadsWithCondition ? (/\s(?:then|thi)\s/.test(clause) ? clause.split(/\s(?:then|thi)\s/).pop() : '') : clause;
515
+ if (STATE_ACTION.test(consequent.split(/\s+/).slice(0, 3).join(' '))) { conditional = true; return false; }
516
+ gated = leadsWithCondition && !STATE_ACTION.test(consequent);
517
+ return false;
518
+ }
519
+ const wasGated = gated;
520
+ gated = false;
521
+ const stops = (wasGated ? STATE_ACTION.test(clause) : STATE_ACTION.test(head)) && (wasGated || STATE_OBJECT.test(clause));
522
+ if (stops && wasGated) { conditional = true; return false; }
523
+ return stops;
524
+ });
525
+ return { action, conditional: conditional && !action, targets };
526
+ }
527
+
528
+ function classifySemanticText(input = {}) {
529
+ const semantic = classifySemanticCore(input);
530
+ if (semantic.taskKind !== 'READ_ONLY' || semantic.conditionalObligations || semantic.publication || !isStateOperationRequest(input.promptText)) return semantic;
531
+ const { verificationOnly: _verification, statusReport: _status, ...rest } = semantic;
532
+ const shape = stateOperationShape(input.promptText);
533
+ return { ...rest, stateVerification: true, ...(shape.action ? { stateAction: true } : shape.conditional ? { stateConditionalStop: true } : {}), ...(shape.targets.length ? { stateTargets: shape.targets } : {}) };
534
+ }
535
+
536
+ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
428
537
  promptText = publicationScope(promptText).text;
429
538
  const releaseText = String(promptText).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
430
539
  const preflight = releaseText.match(/\b(?:yarn\s+release:verify|npm\s+run\s+release:verify)\b/)?.[0];
@@ -435,13 +544,13 @@ function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
435
544
  if (ordersPublicationText(promptText)) {
436
545
  const implementation = hasExplicitOrder(clauses.filter((clause) => !/\b(?:release|publish)\b/.test(clause)));
437
546
  const remaining = clauses.filter((clause) => !ordersPublicationText(clause) && !/\b(?:release|publish)\b/.test(clause)).join('; ');
438
- const base = remaining.trim() ? classifySemanticText({ promptText: remaining, targetFile }) : {};
547
+ const base = remaining.trim() ? classifySemanticCore({ promptText: remaining, targetFile }) : {};
439
548
  delete base.verificationOnly;
440
549
  delete base.statusReport;
441
550
  return { ...base, taskKind: implementation ? 'MIXED' : 'OPERATIONAL', publication: true, ...(releasePolicy ? { releasePolicy } : {}) };
442
551
  }
443
552
  if (!/[a-z0-9]/.test(text)) return { taskKind: 'READ_ONLY' };
444
- if (declaredReadOnly(promptText, releasePolicy)) return { taskKind: 'READ_ONLY', ...(isVerificationOnlyRequest(promptText) ? { verificationOnly: true } : {}) };
553
+ if (declaredReadOnly(promptText, releasePolicy)) return { taskKind: 'READ_ONLY', ...(isVerificationOnlyRequest(promptText) && !bansTestRuns(promptText) ? { verificationOnly: true } : {}) };
445
554
  const sourceOrder = actionable.some((clause) => /\b(?:implement|fix(?:es)?|apply|refactor|modify|edit|write|update|sua|viet|chinh)\b/.test(clause)
446
555
  && /\b(?:source|code|logic|scheduler|implementation|ma nguon)\b|\.[cm]?[jt]sx?\b/.test(clause));
447
556
  const codeChangeVerb = actionable.some((clause) => !/^(?:run\s+|execute\s+)?git\s+/.test(clause) && /\b(?:implement|fix(?:es)?|apply|refactor|modify|edit|write|update|sua|viet|chinh)\b/.test(clause));
@@ -480,7 +589,7 @@ function classifySemanticText({ promptText = '', targetFile = '' } = {}) {
480
589
  && !/\.[cm]?[jt]sx?\b/.test(clause) && !/\bgit\b/.test(clause));
481
590
  const nativeDomain = cronOperation ? 'scheduled-job' : gitOperation !== runtimeOperation ? (gitOperation ? 'git-integrity' : 'service-runtime') : null;
482
591
  const operation = Boolean(nativeDomain);
483
- if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', verificationOnly: true };
592
+ if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', ...(bansTestRuns(promptText) ? {} : { verificationOnly: true }) };
484
593
  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/;
485
594
  const CONFIG_MUTATION_VERB = /\b(?:set|change|toggle|enable|disable|switch|turn|configure|modify|update|edit|doi(?!\s+chieu\b)|bat(?!\s+dau\b)|tat(?!\s+ca\b)|chinh)\b/;
486
595
  const CONFIG_NOUN = /\b(?:configuration|config|toggle|cau hinh)\b/;
@@ -533,6 +642,7 @@ export function applyTaskSemantics(contract, semantic) {
533
642
  return { ...(contract || {}), ...semantic,
534
643
  completionEvidence: semantic.taskKind === 'DOCUMENTATION_OUTPUT' ? ['report-artifact'] : operationOnly ? ['operation-verification']
535
644
  : semantic.taskKind === 'MIXED' ? [...new Set([...evidence, 'write-evidence', 'operation-verification'])]
645
+ : semantic.taskKind === 'READ_ONLY' && semantic.stateVerification ? ['state-verification']
536
646
  : semantic.taskKind === 'READ_ONLY' && semantic.statusReport ? []
537
647
  : semantic.taskKind === 'READ_ONLY' ? (semantic.verificationOnly ? ['verification-evidence'] : ['impact-evidence'])
538
648
  // A routed contract owns the debt; an unrouted (informational/null) turn carries none, because
@@ -1412,11 +1412,14 @@ async function main() {
1412
1412
  const guidanceRefresh = Boolean(guidanceReuse) && Boolean(lastPrompt);
1413
1413
  if (continuingTask || guidanceRefresh) promptText = lastPrompt;
1414
1414
  const carryGuidanceState = (state) => {
1415
+ if (sessionId && previousState.ownerControl?.kind === 'stop' && previousState.ownerControl.sessionId === sessionId) {
1416
+ state.ownerControl = previousState.ownerControl;
1417
+ }
1415
1418
  if (!guidanceRefresh || state.taskInstanceId !== previousState.taskInstanceId) return state;
1416
1419
  state.requestKey = previousState.requestKey;
1417
1420
  state.routingContext = { ...previousState.routingContext };
1418
1421
  state.routeSummary ||= {};
1419
- for (const key of ['executionContract', 'expectedSourceFiles', 'completionState', 'continuationState', 'executionMode']) {
1422
+ for (const key of ['executionContract', 'expectedSourceFiles', 'expectedSourceProvenance', 'completionState', 'continuationState', 'executionMode']) {
1420
1423
  if (previousState.routeSummary[key] !== undefined) state.routeSummary[key] = previousState.routeSummary[key];
1421
1424
  else delete state.routeSummary[key];
1422
1425
  }
@@ -4150,7 +4153,41 @@ export async function applyRoleAdviceConsult({
4150
4153
  }
4151
4154
 
4152
4155
 
4153
- function buildRouteSummary({
4156
+ const PROMPT_FILE_TOKEN_RE = /[\w@.~+-]+(?:\/[\w@.~+-]+)*\.[A-Za-z][\w]{0,9}\b/g;
4157
+ const PROMPT_DIR_TOKEN_RE = /[\w@.~+-]+(?:\/[\w@.~+-]+)*\/(?![\w@.~+-])|[\w@.~+-]+(?:\/[\w@.~+-]+)+(?![\w@.~+/-])/g;
4158
+ function promptNamesFile(promptTokens, filePath, promptDirs = []) {
4159
+ const file = String(filePath).replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase();
4160
+ const base = file.split('/').pop();
4161
+ if (promptDirs.some((dir) => file.startsWith(`${dir}/`) || file.includes(`/${dir}/`))) return true;
4162
+ return promptTokens.some((token) => token === file
4163
+ || (token.includes('/') && file.endsWith(`/${token}`))
4164
+ || (token.includes('/') && token.endsWith(`/${file}`))
4165
+ || token === base);
4166
+ }
4167
+ const DOCS_HOUSEKEEPING_PROMPT = /\b(?:docs?|documentation|readme|changelog|worklog|archive|archiving|status\s+(?:file|doc|update)|plans?|commit|tai\s*lieu|tài\s*liệu|luu\s*tru|lưu\s*trữ)\b/i;
4168
+ const CODE_CHANGE_PROMPT = /\b(?:fix|bug|implement|refactor|rewrite|add\s+(?:a\s+|an\s+|the\s+)?(?:function|feature|option|test|endpoint|handler|support)|patch|crash|error|regression|sua\s+loi|sửa\s+lỗi|them\s+tinh\s+nang|thêm\s+tính\s+năng)\b/i;
4169
+ export function deriveExpectedSourceProvenance({ promptText = '', targetFile = null, primaryTargets = [], relatedTests = [] } = {}) {
4170
+ const valid = (list) => (Array.isArray(list) ? list : []).filter((f) => typeof f === 'string' && f.trim());
4171
+ const promptTokens = String(promptText ?? '').replace(/\\/g, '/').toLowerCase()
4172
+ .match(PROMPT_FILE_TOKEN_RE)?.map((t) => t.replace(/^\.\//, '')) ?? [];
4173
+ const promptDirs = (String(promptText ?? '').replace(/\\/g, '/').toLowerCase().match(PROMPT_DIR_TOKEN_RE) ?? [])
4174
+ .map((d) => d.replace(/^\.\//, '').replace(/\/+$/, '')).filter((d) => d && !/\.[a-z][\w]{0,9}$/.test(d));
4175
+ const primaries = valid(primaryTargets);
4176
+ const tests = valid(relatedTests);
4177
+ const target = typeof targetFile === 'string' && targetFile.trim() ? targetFile : null;
4178
+ const named = (f) => promptNamesFile(promptTokens, f, promptDirs);
4179
+ const anchored = Boolean(target) || [...primaries, ...tests].some(named);
4180
+ const advisory = DOCS_HOUSEKEEPING_PROMPT.test(String(promptText ?? '')) && !CODE_CHANGE_PROMPT.test(String(promptText ?? ''));
4181
+ const entries = [];
4182
+ if (target) entries.push({ file: target, source: 'target' });
4183
+ for (const f of primaries) entries.push({ file: f, source: named(f) ? 'prompt' : target ? 'target' : anchored || advisory ? 'index-guess' : 'index-primary' });
4184
+ for (const f of tests) entries.push({ file: f, source: !anchored ? (advisory ? 'index-guess' : 'index-primary') : named(f) ? 'prompt' : 'related-test' });
4185
+ const seen = new Set();
4186
+ const expectedSourceProvenance = entries.filter((e) => (seen.has(e.file) ? false : seen.add(e.file))).slice(0, 8);
4187
+ return { expectedSourceFiles: expectedSourceProvenance.map((e) => e.file), expectedSourceProvenance };
4188
+ }
4189
+
4190
+ export function buildRouteSummary({
4154
4191
  activeSkills = [],
4155
4192
  routingContext = {},
4156
4193
  contextRecommendation = null,
@@ -4180,11 +4217,12 @@ function buildRouteSummary({
4180
4217
  // files, so carry the full resolver list (target + primaryTargets + relatedTests), bounded
4181
4218
  // for compact route state. Absent when the route has no indexed context — the ledger then
4182
4219
  // falls back to its legacy any-read behaviour.
4183
- const expectedSourceFiles = unique([
4184
- ...(routingContext.targetFile ? [routingContext.targetFile] : []),
4185
- ...(preview.primaryTargets ?? []),
4186
- ...(preview.relatedTests ?? []),
4187
- ].filter((filePath) => typeof filePath === 'string' && filePath.trim())).slice(0, 8);
4220
+ const { expectedSourceFiles, expectedSourceProvenance } = deriveExpectedSourceProvenance({
4221
+ promptText: routingContext.lastExplicitUserPromptText || routingContext.promptText,
4222
+ targetFile: routingContext.targetFile,
4223
+ primaryTargets: preview.primaryTargets,
4224
+ relatedTests: preview.relatedTests,
4225
+ });
4188
4226
  const primaryCommands = unique(verificationRecommendation?.commands ?? []);
4189
4227
  const fallbackCommands = unique(verificationRecommendation?.fallbackCommands ?? []);
4190
4228
  const preferredOrder = unique(
@@ -4365,7 +4403,7 @@ function buildRouteSummary({
4365
4403
  continuationState,
4366
4404
  autonomyLevel,
4367
4405
  continuousExecution,
4368
- ...(expectedSourceFiles.length > 0 ? { expectedSourceFiles } : {}),
4406
+ ...(expectedSourceFiles.length > 0 ? { expectedSourceFiles, expectedSourceProvenance } : {}),
4369
4407
  intentMode: routingContext.intentMode ?? null,
4370
4408
  handoffFile,
4371
4409
  delegateHint: delegationRecommendation?.hint ?? null,
@@ -6152,6 +6190,7 @@ export function compactRouteSummary(routeSummary = null) {
6152
6190
  // to legacy any-read behaviour.
6153
6191
  ...(Array.isArray(routeSummary.expectedSourceFiles) && routeSummary.expectedSourceFiles.length > 0 ? {
6154
6192
  expectedSourceFiles: routeSummary.expectedSourceFiles,
6193
+ ...(Array.isArray(routeSummary.expectedSourceProvenance) ? { expectedSourceProvenance: routeSummary.expectedSourceProvenance } : {}),
6155
6194
  } : {}),
6156
6195
  nextActionType: routeSummary.nextActionType ?? null,
6157
6196
  nextActionCommand: routeSummary.nextActionCommand ?? null,
@@ -193,7 +193,7 @@ export function bashOperationReceipt(rawCommand, response, transportSuccess, goa
193
193
  // the registry actually printed a semver. Agent prose is never evidence; the completion gate compares the
194
194
  // recorded version with package.json and live Git state before it treats a release as published.
195
195
  const NPM_PUBLISH = /^npm\s+publish(?:\s|$)/;
196
- const NPM_VIEW = /^npm\s+view\s+(\S+?)(?:@\S+)?\s+version(?:\s+--prefer-online)?(?:\s+2>&1)?\s*$/;
196
+ const NPM_VIEW = /^npm\s+view\s+(\S+?)(?:@(\S+))?\s+(version|dist\.shasum)(?:\s+--prefer-online)?(?:\s+2>&1)?\s*$/;
197
197
  const SEMVER_LINE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
198
198
  export function releaseReceipt(rawCommand, response, transportSuccess) {
199
199
  if (typeof rawCommand !== 'string') return null;
@@ -211,13 +211,17 @@ export function releaseReceipt(rawCommand, response, transportSuccess) {
211
211
  const view = seg.match(NPM_VIEW);
212
212
  if (view) {
213
213
  const text = responseText(response);
214
+ if (view[3] !== 'version') {
215
+ const sha = /^[a-f0-9]{40}$/.test(text) && SEMVER_LINE.test(view[2] || '') && text;
216
+ return { type: 'view', success: ok && !!sha, version: view[2], integrity: sha, package: view[1] };
217
+ }
214
218
  const version = SEMVER_LINE.test(text) ? text : null;
215
219
  return { type: 'view', success: ok && version !== null, version, package: view[1] };
216
220
  }
217
221
  return null;
218
222
  }
219
223
 
220
- export function releaseOperationReceipt(command, response, transportSuccess, { sessionId, harness } = {}) {
224
+ export function releaseOperationReceipt(command, response, transportSuccess, { sessionId, harness, candidate } = {}) {
221
225
  const found = releaseReceipt(command, response, transportSuccess);
222
226
  if (!found) return null;
223
227
  const scope = typeof sessionId === 'string' && sessionId.trim() ? `session:${sessionId.trim()}` : null;
@@ -225,9 +229,12 @@ export function releaseOperationReceipt(command, response, transportSuccess, { s
225
229
  const base = { kind: 'operation', success: ok, transportSuccess: transportSuccess === true, harness };
226
230
  if (found.type === 'publish') {
227
231
  const state = found.package && found.version ? `published:${found.package}@${found.version}` : 'unproven';
228
- return { ...base, operation: { domain: 'release', role: 'mutation', scope, target: 'npm-publish', state } };
232
+ const shasum = responseText(response).match(/(?:^|\n)npm notice shasum:\s+([a-f0-9]{40})\s*(?:\n|$)/)?.[1];
233
+ return { ...base, operation: { domain: 'release', role: 'mutation', scope, target: 'npm-publish', state,
234
+ ...(/^[a-f0-9]{40,64}$/.test(candidate || '') ? { candidate } : {}), ...(shasum ? { integrity: shasum } : {}) } };
229
235
  }
230
236
  const state = ok && `published:${found.package}@${found.version}`.length <= 200
231
237
  ? `published:${found.package}@${found.version}` : 'unproven';
232
- return { ...base, operation: { domain: 'release', role: 'state', scope, target: null, state, complete: ok && state !== 'unproven' } };
238
+ return { ...base, operation: { domain: 'release', role: 'state', scope, target: null, state, complete: ok && state !== 'unproven',
239
+ ...(found.integrity ? { integrity: found.integrity, integrityFor: `${found.package}@${found.version}` } : {}) } };
233
240
  }