@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.
@@ -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:a489851b01e95788d8a3e0a080b80c04d8161c734b6c0ed5c9758a765f5bc0a4';
4
4
 
5
5
  export function semanticContractIdentity({ promptText = '', targetFile = '', taskInstanceId = null } = {}) {
6
6
  return { taskInstanceId, targetFile, engineVersion: SEMANTIC_ENGINE_VERSION,
@@ -8,7 +8,7 @@ export function semanticContractIdentity({ promptText = '', targetFile = '', tas
8
8
  }
9
9
 
10
10
  const semanticContractShape = (contract) => JSON.stringify([
11
- contract?.taskKind, contract?.publication === true, contract?.operationGoal ?? null,
11
+ contract?.taskKind, contract?.publication === true, contract?.operationGoal ?? null, contract?.operationGoals ?? null,
12
12
  contract?.configurationScope ?? null, contract?.releasePolicy ?? null, contract?.conditionalObligations ?? null,
13
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(),
@@ -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
  }
@@ -145,9 +152,9 @@ const CONDITIONAL_RUNTIME_VERB = /\b(?:redeploy|deploy|restart|khoi dong lai|tri
145
152
  const CONDITIONAL_RUNTIME_EXCLUDED = /\b(?:publish|phat hanh|commit|push|tag|git|implement|fix|edit|modify|sua)\b/;
146
153
  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
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
- const PAST_RELEASE_ITEM = new RegExp(`^(?:(?:please|just|now|also)\\s+)*${PAST_RELEASE_SOURCE}`);
155
+ 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))`);
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)]
@@ -157,6 +164,54 @@ function defectRepairBranches(text) {
157
164
  && /\b(?:sua|fix|repair)\b/.test(branch));
158
165
  }
159
166
 
167
+ 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/;
168
+ // deploy words prohibit only as a direct ban ("do not deploy"), never as an object inside other prose.
169
+ 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/;
170
+ 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/;
171
+ const GATE_ANCHOR = /\b(?:ukit|gates?|hooks?|logs?)\b|`/;
172
+ 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/;
173
+ const PURPOSE_SCOPE = /\b(?:chi de|only to|just to|only for)\b/;
174
+ const CONDITION_LEAD = /\b(?:neu|if|khi|unless|in case|truong hop)\b/;
175
+ 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']);
176
+ function authorizedSubjects(promptText) {
177
+ const out = new Set();
178
+ const raw = String(promptText).normalize('NFC').replace(/đ/g, 'd').replace(/Đ/g, 'D').normalize('NFD').replace(/[̀-ͯ]/g, '');
179
+ for (const item of raw.split(/[;\n,]|\.\s+/)) {
180
+ if (PUBLISH_ORDER_NEGATOR.test(item.toLowerCase())) continue;
181
+ 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)) {
182
+ const name = m[1].toLowerCase();
183
+ if (!NAME_STOP.has(name)) out.add(name);
184
+ }
185
+ }
186
+ return out;
187
+ }
188
+ // Returns null (fail closed: a direct in-scope prohibition) or a non-prohibiting verdict.
189
+ function properNames(promptText) {
190
+ const raw = String(promptText).normalize('NFC').replace(/đ/g, 'd').replace(/Đ/g, 'D').normalize('NFD').replace(/[̀-ͯ]/g, '');
191
+ const out = new Set();
192
+ for (const m of raw.matchAll(/(?<=[^\s.!?;:\n*#>\-\d)][ \t]+)([A-Z][A-Za-z0-9_-]{2,})\b/g)) out.add(m[1].toLowerCase());
193
+ return out;
194
+ }
195
+ const GATE_LEAD = /\b(?:bi bao|bao rang|reports?|reported|says?|said|shows?|showed|message|thong bao|log|logs|gate|gates|hook|hooks)\b/;
196
+ function classifyProhibitionItem(item, authorized, proper) {
197
+ const strongGate = /\b(?:prohibits? publication|publication blocked|ukit completion gate)\b/.test(item);
198
+ const quotedGate = GATE_QUOTE.test(item) && (item.includes('`') || GATE_LEAD.test(item)) && (strongGate || GATE_ANCHOR.test(item));
199
+ if (quotedGate) return { scope: 'quoted', conditional: false };
200
+ if (CONTINUATION_NEGATION.test(item)) {
201
+ // A continuation clause only neutralises itself; a publish ban in a sibling clause survives.
202
+ const rest = item.split(/\s*(?:,|\bva\b|\band\b)\s*/).filter((part) => !CONTINUATION_NEGATION.test(part)).join(' ');
203
+ if (!(PUBLISH_ORDER_NEGATOR.test(rest) && /\b(?:release|publish|publication|deploy)\b/.test(rest))) return { scope: 'continuation', conditional: false };
204
+ item = rest;
205
+ }
206
+ const neg = PUBLISH_ORDER_NEGATOR.exec(item);
207
+ const lead = CONDITION_LEAD.exec(item);
208
+ if (neg && lead && lead.index < neg.index) return { scope: 'workspace', conditional: true };
209
+ 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 };
210
+ 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];
211
+ if (target && !NAME_STOP.has(target) && authorized.size && !authorized.has(target) && proper.has(target)) return { scope: 'other', conditional: false };
212
+ return null;
213
+ }
214
+
160
215
  export function publicationScope(promptText = '') {
161
216
  const plain = String(promptText).normalize('NFC')
162
217
  .replace(/\bdùng\b/giu, 'su dung').replace(/đừng/giu, 'khong')
@@ -222,7 +277,9 @@ export function publicationScope(promptText = '') {
222
277
  lines.push(line);
223
278
  }
224
279
  const text = lines.join('\n');
225
- let prohibited = false;
280
+ const authorized = authorizedSubjects(promptText);
281
+ const proper = properNames(promptText);
282
+ const prohibitions = [];
226
283
  let prohibitionBlock = false;
227
284
  for (const line of text.split('\n')) {
228
285
  if (!line.trim()) continue;
@@ -238,11 +295,18 @@ export function publicationScope(promptText = '') {
238
295
  || /\b(?:publish|publication|release)\b[^,]*\b(?:must not|not yet)\b[^,]*\b(?:until|before|while)\b/.test(item)) continue;
239
296
  if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
240
297
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
241
- if (negated && /\b(?:release|publish|publication)\b/.test(item)) prohibited = true;
298
+ const revoked = REVOCATION_ITEM.test(item);
299
+ if (!revoked && !(negated && (/\b(?:release|publish|publication)\b/.test(item) || DIRECT_DEPLOY_BAN.test(item)))) continue;
300
+ let verdict = revoked ? null : classifyProhibitionItem(item, authorized, proper);
301
+ if (!verdict && !revoked && !/\b(?:release|publish|publication)\b/.test(item)) verdict = { scope: 'deploy', conditional: false };
302
+ if (prohibitions.length < 20) prohibitions.push({ span: item.slice(0, 160), line: line.trim().slice(0, 160), ...(verdict || { scope: 'workspace', conditional: false }) });
242
303
  }
243
304
  }
244
305
  }
245
- return { text, prohibited };
306
+ // A deploy-only ban does not prohibit an ordered npm publication; it stands only when no publication is ordered.
307
+ const prohibited = prohibitions.some((entry) => entry.scope === 'workspace' && !entry.conditional)
308
+ || (prohibitions.some((entry) => entry.scope === 'deploy') && !ordersPublicationFromText(text));
309
+ return { text, prohibited, prohibitions };
246
310
  }
247
311
 
248
312
  export function ordersPublication(promptText = '') {
@@ -250,7 +314,11 @@ export function ordersPublication(promptText = '') {
250
314
  }
251
315
 
252
316
  function ordersPublicationText(promptText = '') {
253
- let active = collapseInspectionSentences(publicationScope(promptText).text).replace(/```[^]*?```|~~~[^]*?~~~/g, '')
317
+ return ordersPublicationFromText(publicationScope(promptText).text);
318
+ }
319
+
320
+ function ordersPublicationFromText(scopedText = '') {
321
+ let active = collapseInspectionSentences(scopedText).replace(/```[^]*?```|~~~[^]*?~~~/g, '')
254
322
  .replace(/^[ \t]*>.*$/gm, '').replace(/[“"][^”"\n]*[”"]|‘[^’\n]*’/g, '');
255
323
  for (const branch of defectRepairBranches(active)) active = active.replace(branch, '');
256
324
  let ordered = false;
@@ -267,10 +335,11 @@ function ordersPublicationText(promptText = '') {
267
335
  if (PUBLISH_ORDER_NEGATOR.test(item)) negated = true;
268
336
  else if (/^(?:please\s+|now\s+|also\s+)*(?:run|execute|perform|chay)\s+\S/.test(item)) negated = false;
269
337
  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);
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);
338
+ 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);
339
+ 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);
272
340
  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);
341
+ 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)
342
+ || /^(?:(?:sua|kiem thu|hoan tat)\b[^.;\n]*\b(?:va|roi)\s+|(?:va|roi)\s+)(?:phat hanh|xuat ban)\s+npm\b/.test(politeItem);
274
343
  if (!negated && (releaseOrder || viPublish || (publication && (
275
344
  (/^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
345
  || /\b(?:chay|run)\s+`?npm\s+publish\b/.test(item)
@@ -282,8 +351,16 @@ function ordersPublicationText(promptText = '') {
282
351
  return ordered;
283
352
  }
284
353
 
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']);
286
- function nativeOperationGoal(domain, actionable, text) {
354
+ 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',
355
+ // Vietnamese function words typed without diacritics ("restart rieng X", "trien khai phu hop", "kiem chung").
356
+ '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']);
357
+ // A required service target must be a name the owner actually typed: a word whose diacritics were stripped
358
+ // ("phù" -> "phu", "riêng" -> "rieng") is prose, not a service no native command could ever name.
359
+ function typedToken(name, rawPrompt) {
360
+ if (typeof rawPrompt !== 'string' || !rawPrompt) return true;
361
+ return rawPrompt.toLowerCase().split(/[^\p{L}\p{N}_.-]+/u).some((token) => token === name || token.replace(/[.,:;]+$/, '') === name);
362
+ }
363
+ function nativeOperationGoal(domain, actionable, text, rawPrompt = '') {
287
364
  const goal = { domain, target: null, desiredState: 'verified', completionSemantics: 'execute-and-verify', requiredTargets: [] };
288
365
  const clauses = actionable.join(' . ');
289
366
  if (domain === 'git-integrity') {
@@ -299,9 +376,31 @@ function nativeOperationGoal(domain, actionable, text) {
299
376
  return goal;
300
377
  }
301
378
  const services = [...clauses.matchAll(/\b(?:restart|redeploy|deploy|khoi dong lai|trien khai)\s+(?:the\s+|lai\s+)?([a-z0-9][\w.-]*)/g)]
302
- .map((m) => m[1]).filter((name) => !NOT_A_SERVICE.has(name));
379
+ .map((m) => m[1]).filter((name) => !NOT_A_SERVICE.has(name) && !/^\d+(?:\.\d+)+/.test(name) && !/^[a-z0-9_-]+\.[a-z]{1,5}$/.test(name)
380
+ && name.length >= 2 && typedToken(name, rawPrompt));
303
381
  goal.requiredTargets = [...new Set(services)];
304
- const probePath = text.match(/(?:^|\s)(\/[a-z0-9_.-]+(?:\/[a-z0-9_.-]+)*)/)?.[1] || null;
382
+ 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;
383
+ // The owner-named deploy script is the single native mutation; project/service words around it are its
384
+ // subject, not separate commands, so they must not become targets no script invocation can ever name.
385
+ if (deployScript) {
386
+ goal.deployCommand = deployScript.slice(0, 64);
387
+ // Drop only the script's own subject: the name right after deploy/trien khai that sits before "via <script>".
388
+ 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];
389
+ goal.requiredTargets = goal.requiredTargets.filter((name) => name !== subject && !/^(?:production|prod|staging)$/.test(name));
390
+ }
391
+ const FS_PATH = /^\/(?:tmp|private|var|users|volumes|home|opt|etc)\b|\.[a-z0-9]{1,5}$/;
392
+ const urlPath = text.match(/\bhttps?:\/\/[^\s/]+(\/[a-z0-9_.\/-]*)/)?.[1];
393
+ const ctxPath = text.match(/\b(?:curl|get|endpoint|health|url)\b[^\n/]{0,20}\s(\/[a-z0-9_.-]+(?:\/[a-z0-9_.-]+)*)/)?.[1];
394
+ // A bare absolute path names the probe only next to a probe word ("verify /v1/models returns 200"); a path in a
395
+ // filesystem context (backup dir, "nam o", folder) never does. Trailing sentence punctuation is not part of it.
396
+ const PROBE_WORD = /\b(?:curl|get|endpoint|health|url|returns?|http|status)\b/;
397
+ const FS_CONTEXT = /\b(?:backups?|nam o|located|thu muc|directory|folder|duoi|under)\b/;
398
+ const barePaths = [...text.matchAll(/(?:^|\s)(\/[a-z0-9_.-]+(?:\/[a-z0-9_.-]+)*)/g)].filter((m) => {
399
+ const near = text.slice(Math.max(0, m.index - 40), m.index + m[0].length + 40);
400
+ return PROBE_WORD.test(near) && !FS_CONTEXT.test(near);
401
+ }).map((m) => m[1]);
402
+ const probePath = [urlPath, ctxPath, ...barePaths].map((candidate) => candidate?.replace(/[.,;:]+$/, ''))
403
+ .find((candidate) => candidate && !FS_PATH.test(candidate) && !FS_CONTEXT.test(candidate)) || null;
305
404
  const probeStatus = text.match(/\b(?:returns?|returning|responds?(?:\s+with)?|http|status(?:\s+code)?)\s+([1-5]\d\d)\b/)?.[1] || null;
306
405
  if (probePath || probeStatus) goal.probe = { path: probePath, status: probeStatus };
307
406
  return goal;
@@ -340,6 +439,11 @@ function neutralizeNonOrders(text) {
340
439
  .replace(/^[ \t]*(?:[-*+\u2022]|\d+[.)])[ \t]*(?:negative|positive)\s+controls?\b[^\n]*(?:\n(?![ \t]*(?:[-*+\u2022]|\d+[.)])|[ \t]*\n)[^\n]*)*/gm, ' ')
341
440
  .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
441
  .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'), ' ')
442
+ // Negated sufficiency ("git commit/tag/release chua du de ban giao", "a git commit is not enough /
443
+ // insufficient"): the negation sits AFTER the operation enumeration, so the khong/chua span strip
444
+ // below would remove only the predicate tail and leave the bare "git commit/tag/release" fragment
445
+ // standing as a phantom imperative. Consume the enumeration together with its negated predicate.
446
+ .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
447
  .replace(new RegExp(`\\b(?:(?:tuyet\\s+doi\\s+)?khong|chua)\\s+[^.;\\n]*?(?=\\s+(?:nhung|tuy nhien)\\b|[.;\\n]|$)`, 'g'), ' ')
344
448
  .replace(/"[^"\n]*\s[^"\n]*"|`[^`\n]*\s[^`\n]*`|\u201c[^\u201d\n]*\u201d/g, ' ')
345
449
  .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 +468,7 @@ function neutralizeNonOrders(text) {
364
468
  });
365
469
  }
366
470
 
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/;
471
+ 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
472
  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
473
  const IMPERATIVE_ORDER = new RegExp(`^(?:[-*+\\u2022>\\d.)\\s]*)(?:(?:please|hay|vui long|now|also|first|then)\\s+)*(?:${ORDER_VERBS})\\b\\s+\\S`);
370
474
  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 +591,9 @@ export function isStateOperationRequest(promptText = '') {
487
591
  return plain.split(/[;!?\n]+|[.:](?=\s|$)/).some((clause) => {
488
592
  const lead = clause.match(STATE_LEAD);
489
593
  if (!lead) return false;
594
+ // A clause whose verb is negated ("khong tu kill process", "do not stop the job") states a boundary, not an
595
+ // order to inspect or stop state. Only a negator BEFORE the verb counts: "stop X; do not ..." stays an order.
596
+ if (/\b(?:khong|do not|don't|never|not)\b/.test(clause.slice(0, lead.index))) return false;
490
597
  const after = clause.slice(lead.index + lead[0].length);
491
598
  const near = after.match(/^(?:\s+[\p{L}\p{N}_-]+){0,5}?\s+/u);
492
599
  const window = after.split(/\s+/).slice(0, 7).join(' ');
@@ -533,6 +640,10 @@ function classifySemanticText(input = {}) {
533
640
  return { ...rest, stateVerification: true, ...(shape.action ? { stateAction: true } : shape.conditional ? { stateConditionalStop: true } : {}), ...(shape.targets.length ? { stateTargets: shape.targets } : {}) };
534
641
  }
535
642
 
643
+ // Clauses that order a plain change keep a git+deploy prompt a code task; history/receipt bookkeeping does not.
644
+ 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/;
645
+ const HISTORY_OBJECT = /\b(?:release(?:\s+history)?|lich su release|receipts?|worklog|ledger|status)\b/;
646
+ const AUTH_EXCLUSION = /\b(?:khong cap phep|not authori[sz]e\w*|does not authori[sz]e|khong duoc phep)\b[^.]*\./g;
536
647
  function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
537
648
  promptText = publicationScope(promptText).text;
538
649
  const releaseText = String(promptText).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase();
@@ -583,11 +694,23 @@ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
583
694
  }
584
695
  return total > 0 && banned === total;
585
696
  };
586
- const gitOperation = actionable.some((clause) => !operationNotOrdered(clause)
587
- && (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)));
588
- 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)
589
- && !/\.[cm]?[jt]sx?\b/.test(clause) && !/\bgit\b/.test(clause));
590
- const nativeDomain = cronOperation ? 'scheduled-job' : gitOperation !== runtimeOperation ? (gitOperation ? 'git-integrity' : 'service-runtime') : null;
697
+ // A status/report wrap-up ("check X and Y results; then docs, commit, report") lists a bare `commit` as
698
+ // bookkeeping next to the report it closes; it is not an ordered history operation with a remote proof.
699
+ const statusWrapUp = /^[\s*+•>\d.)-]*(?:(?:please|hay|vui long)\s+)*(?:check|status|report|show|summari[sz]e|kiem tra|bao cao)\b/.test(actionable[0] || '')
700
+ && actionable.some((clause) => /^[\s*+•>\d.)-]*(?:report|bao cao)\s*$/.test(clause));
701
+ 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)
702
+ && !/\.[cm]?[jt]sx?\b/.test(clause) && !/\bgit\b/.test(clause);
703
+ const runtimeOperation = actionable.some(runtimeClause);
704
+ // Only a PURE status wrap-up drops its bare commit; one that also orders a deploy keeps the git goal.
705
+ const bookkeepingCommit = (clause) => statusWrapUp && !runtimeOperation && /^[\s*+•>\d.)-]*commit\s*$/.test(clause);
706
+ const gitClause = (clause) => !operationNotOrdered(clause) && !bookkeepingCommit(clause)
707
+ && (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));
708
+ const gitOperation = actionable.some(gitClause);
709
+ // Commit/push AND a deploy with no source-change order are TWO independent native obligations: each keeps
710
+ // its own proof (git remote parity; deploy receipt + live check). Neither is folded into the other, and
711
+ // owner authorization wording never drops one of them.
712
+ const nativeDomain = cronOperation ? 'scheduled-job' : gitOperation !== runtimeOperation ? (gitOperation ? 'git-integrity' : 'service-runtime')
713
+ : 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;
591
714
  const operation = Boolean(nativeDomain);
592
715
  if (!releasePolicy && !operation && isVerificationOnlyRequest(promptText)) return { taskKind: 'READ_ONLY', ...(bansTestRuns(promptText) ? {} : { verificationOnly: true }) };
593
716
  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/;
@@ -621,8 +744,13 @@ function classifySemanticCore({ promptText = '', targetFile = '' } = {}) {
621
744
  const taskKind = operation ? (sourceOrder || codeChangeVerb ? 'MIXED' : 'OPERATIONAL')
622
745
  : config ? 'CONFIGURATION' : documentation ? 'DOCUMENTATION_OUTPUT' : readOnly ? 'READ_ONLY' : 'CODE_IMPLEMENTATION';
623
746
  const id = text.match(/\b[a-f0-9]{8}(?:[a-f0-9-]{0,28})\b/)?.[0] || null;
747
+ // Multi-operation: the goal ordered first is the primary `operationGoal`; `operationGoals` carries all of them.
748
+ const operationGoals = nativeDomain === 'multi'
749
+ ? (actionable.findIndex(gitClause) <= actionable.findIndex(runtimeClause) ? ['git-integrity', 'service-runtime'] : ['service-runtime', 'git-integrity'])
750
+ .map((domain) => nativeOperationGoal(domain, actionable, text, promptText)) : null;
624
751
  return { taskKind, ...(releasePolicy ? { releasePolicy } : {}), ...(documentation ? { reportArtifact } : {}), ...(taskKind === 'READ_ONLY' && statusReport ? { statusReport: true } : {}), ...(config ? { configurationScope: repository ? 'repository' : 'external' } : {}),
625
- ...(operation && nativeDomain !== 'scheduled-job' ? { operationGoal: nativeOperationGoal(nativeDomain, actionable, text) } : {}),
752
+ ...(operationGoals ? { operationGoal: operationGoals[0], operationGoals } : {}),
753
+ ...(operation && !operationGoals && nativeDomain !== 'scheduled-job' ? { operationGoal: nativeOperationGoal(nativeDomain, actionable, text, promptText) } : {}),
626
754
  ...(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',
627
755
  completionSemantics: /\b(?:ensure|dam bao)\b/.test(text)
628
756
  || actionable.some((clause) => /\b(?:delete|remove|cancel|xoa|huy)\b/.test(clause)
@@ -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.
@@ -47,6 +47,18 @@ const GIT_MUTATION = /^git\s+(?:push|commit|clean|reset|merge|rebase|stash|tag|c
47
47
  const GIT_VERB = /^git\s+(push|commit|clean|reset|merge|rebase|stash|tag|checkout|restore|pull|cherry-pick|branch)\b/;
48
48
  const GIT_STATE = /^git\s+(?:fsck\b|diff\s+(?:--check|--exit-code|--quiet)\b|status\s+(?:--porcelain|-s|--short)\b)/;
49
49
  const SERVICE_MUTATION = /^(?:docker(?:\s+compose)?|docker-compose)\s+(?:restart|up|down|stop|start|build)\b|^(?:sudo\s+)?systemctl\s+(?:restart|start|stop|reload)\b|^pm2\s+(?:restart|reload|start)\b|^kubectl\s+(?:rollout|apply)\b|^launchctl\s+kickstart\b|^(?:\.\/)?(?:scripts\/)?deploy[\w.-]*(?:\s|$)|^(?:npm|yarn|pnpm)\s+(?:run\s+)?deploy\b/;
50
+ // A native deploy script named by the owner prompt (e.g. `bash sync_server.sh`). The name is validated as a
51
+ // bare script file name and regex-escaped; only `[bash|sh] [./][dir/]<name>` followed by args counts.
52
+ const DEPLOY_SCRIPT_NAME = /^[\w.-]+\.sh$/;
53
+ function invokesDeployScript(segment, deployCommand) {
54
+ if (typeof deployCommand !== 'string' || !DEPLOY_SCRIPT_NAME.test(deployCommand) || deployCommand.length > 64) return false;
55
+ const escaped = deployCommand.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
56
+ const match = new RegExp(`^(?:(?:bash|sh)\\s+)?(?:\\./)?(?:[\\w.-]+/)*${escaped}(?:\\s+([\\s\\S]*))?$`).exec(segment.trim());
57
+ if (!match) return false;
58
+ // Informational invocations (--help/-h/--status/--version/--dry-run only) change nothing.
59
+ const args = (match[1] || '').trim().split(/\s+/).filter(Boolean);
60
+ return !(args.length > 0 && args.every((a) => /^(?:--help|-h|--status|--version|--dry-run)$/.test(a)));
61
+ }
50
62
  // Remote authority, not stale tracking refs: gate binds sha to clean live HEAD/tracking
51
63
  // remote. Native mutation success remains a separate requirement.
52
64
  const GIT_LS_REMOTE = /^git\s+ls-remote\s+(\S+)\s+(refs\/heads\/\S+)\s*$/;
@@ -157,7 +169,7 @@ export function bashOperationReceipt(rawCommand, response, transportSuccess, goa
157
169
  role = 'mutation';
158
170
  target = seg.match(GIT_VERB)[1];
159
171
  }
160
- } else if (SERVICE_MUTATION.test(seg) && role !== 'state') {
172
+ } else if ((SERVICE_MUTATION.test(seg) || invokesDeployScript(seg, goal.deployCommand)) && role !== 'state') {
161
173
  role = 'mutation';
162
174
  target = requiredTargetOf(seg, required);
163
175
  } else if (CURL.test(seg)) {