@orion-agents/orion-code 0.4.4 → 0.4.5

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +4 -4
  4. package/dist/core/tool-artifacts.js +17 -4
  5. package/dist/framework/query.js +150 -16
  6. package/dist/framework/tool-state.d.ts +4 -0
  7. package/dist/harness/context-harness.d.ts +6 -2
  8. package/dist/harness/context-harness.js +221 -47
  9. package/dist/harness/contract.js +3 -1
  10. package/dist/harness/drift-guard.js +67 -17
  11. package/dist/harness/goal-verification.d.ts +11 -0
  12. package/dist/harness/goal-verification.js +62 -0
  13. package/dist/harness/ledger.js +16 -3
  14. package/dist/harness/state.js +3 -0
  15. package/dist/harness/task-checklist.d.ts +11 -1
  16. package/dist/harness/task-checklist.js +48 -4
  17. package/dist/harness/types.d.ts +10 -0
  18. package/dist/harness/verification.d.ts +11 -1
  19. package/dist/harness/verification.js +47 -2
  20. package/dist/runtime/agent-loop.js +4 -1
  21. package/dist/runtime/batch-read-service.js +21 -4
  22. package/dist/runtime/goal-runtime-coordinator.js +1 -0
  23. package/dist/runtime/product-orion-runtime.js +24 -2
  24. package/dist/runtime/task-context-recovery.js +21 -5
  25. package/dist/runtime/task-context-service.d.ts +3 -1
  26. package/dist/runtime/task-context-service.js +3 -0
  27. package/dist/runtime/workspace-verification.d.ts +2 -2
  28. package/dist/runtime/workspace-verification.js +24 -9
  29. package/dist/services/chat-completion-sse.d.ts +9 -0
  30. package/dist/services/chat-completion-sse.js +50 -0
  31. package/dist/services/compact/summary-generator.d.ts +1 -1
  32. package/dist/services/compact/summary-generator.js +12 -0
  33. package/dist/services/llm.d.ts +1 -1
  34. package/dist/services/llm.js +165 -292
  35. package/dist/services/provider-diagnostics.d.ts +1 -1
  36. package/dist/services/provider-diagnostics.js +7 -2
  37. package/dist/services/provider-resilience/error-classifier.d.ts +3 -0
  38. package/dist/services/provider-resilience/error-classifier.js +14 -0
  39. package/dist/tools/core/common.d.ts +0 -11
  40. package/dist/tools/core/common.js +0 -18
  41. package/dist/tools/core/edit-file.js +57 -86
  42. package/dist/tools/core/exec-command.js +61 -80
  43. package/dist/tools/core/grep.js +84 -24
  44. package/dist/tools/core/read-file.js +3 -2
  45. package/dist/tools/todo.d.ts +2 -2
  46. package/dist/tools/todo.js +13 -10
  47. package/dist/utils/utf8.d.ts +6 -0
  48. package/dist/utils/utf8.js +14 -0
  49. package/docs/cli-guide.md +7 -2
  50. package/npm-shrinkwrap.json +2 -2
  51. package/package.json +1 -1
@@ -7,6 +7,7 @@ const crypto_1 = require("crypto");
7
7
  const path_1 = require("path");
8
8
  const redaction_1 = require("../services/redaction");
9
9
  const tool_serializer_1 = require("../framework/tool-serializer");
10
+ const stop_decision_1 = require("../framework/stop-decision");
10
11
  const verification_command_1 = require("../framework/verification-command");
11
12
  const assembler_1 = require("./assembler");
12
13
  const capability_profile_1 = require("./capability-profile");
@@ -14,6 +15,7 @@ const capsule_1 = require("./capsule");
14
15
  const contract_1 = require("./contract");
15
16
  const drift_guard_1 = require("./drift-guard");
16
17
  const evidence_1 = require("./evidence");
18
+ const goal_verification_1 = require("./goal-verification");
17
19
  const intent_1 = require("./intent");
18
20
  const ledger_1 = require("./ledger");
19
21
  const progress_controller_1 = require("./progress-controller");
@@ -46,6 +48,7 @@ class HarnessKernel {
46
48
  this.completionBlockCount = state.completionBlockCount ?? 0;
47
49
  this.taskEpoch = state.taskEpoch ?? 1;
48
50
  this.goalTaskId = state.goalTaskId;
51
+ this.goalVerificationBlocker = state.goalVerificationBlocker;
49
52
  const restoredChanges = (0, task_checklist_1.requestedWorkspaceChanges)(state.activeInstruction ?? this.contract?.userIntent ?? '');
50
53
  this.taskChecklistRequired = state.taskChecklistRequired ?? restoredChanges.checklistRequired;
51
54
  this.taskChecklistTargets =
@@ -114,6 +117,7 @@ class HarnessKernel {
114
117
  this.taskChecklistTargets = [];
115
118
  this.taskTodos = [];
116
119
  this.taskTodoReceipts.length = 0;
120
+ this.goalVerificationBlocker = undefined;
117
121
  this.completionBlockCount = 0;
118
122
  this.activeConstraints = [];
119
123
  this.nonGoals = [];
@@ -154,6 +158,60 @@ class HarnessKernel {
154
158
  classifyIntent(input) {
155
159
  return (0, intent_1.classifyIntent)(input, this.toJSON());
156
160
  }
161
+ observeGoalSteering(input, goalId) {
162
+ const contract = this.contract;
163
+ if (!contract || this.goalTaskId !== goalId || this.config.enabled === false)
164
+ return;
165
+ const correction = (0, goal_verification_1.goalVerificationCorrection)(contract, input);
166
+ if (!correction)
167
+ return;
168
+ this.ledger.recordUserRequirement(input);
169
+ if ('blocker' in correction) {
170
+ this.goalVerificationBlocker = correction.blocker;
171
+ this.touch();
172
+ return;
173
+ }
174
+ const { previous, next } = correction;
175
+ const rewrite = (statement) => (0, verification_1.replaceRequestedCheck)(statement, previous, next, contract.allowedScope.cwd);
176
+ const priorEvidence = new Set(this.ledger
177
+ .getEntries()
178
+ .filter(entry => (0, verification_1.matchesRequestedCheck)(entry, previous, contract.allowedScope.cwd))
179
+ .flatMap(entry => [entry.id, `ledger:${entry.id}`]));
180
+ this.contract = {
181
+ ...contract,
182
+ objective: rewrite(contract.objective),
183
+ userIntent: input.trim(),
184
+ requirements: contract.requirements.map(rewrite),
185
+ successCriteria: contract.successCriteria.map(rewrite),
186
+ criteria: contract.criteria?.map(item => {
187
+ const statement = rewrite(item.statement);
188
+ if (statement === item.statement)
189
+ return item;
190
+ return {
191
+ ...item,
192
+ statement,
193
+ status: 'pending',
194
+ waiver: undefined,
195
+ evidenceRefs: item.evidenceRefs.filter(ref => !priorEvidence.has(ref)),
196
+ };
197
+ }),
198
+ updatedAt: Math.max(Date.now(), contract.updatedAt + 1),
199
+ };
200
+ this.taskTodos = this.taskTodos.map(todo => {
201
+ const content = rewrite(todo.content);
202
+ if (content === todo.content)
203
+ return todo;
204
+ return {
205
+ ...todo,
206
+ content,
207
+ status: todo.status === 'completed' ? 'pending' : todo.status,
208
+ };
209
+ });
210
+ this.activeInstruction = input.trim();
211
+ this.goalVerificationBlocker = undefined;
212
+ this.refreshCapsule();
213
+ this.touch();
214
+ }
157
215
  activeTaskTodo() {
158
216
  return this.taskTodos.find(todo => todo.status === 'in_progress' && !todo.deferredReason)?.id;
159
217
  }
@@ -176,7 +234,8 @@ class HarnessKernel {
176
234
  checkDeferredWorkspaceAction(action) {
177
235
  const target = action.path ? (0, verification_1.workspaceArtifactPath)(this.cwd, action.path) : undefined;
178
236
  if (target) {
179
- const covering = this.taskTodos.filter(todo => (0, task_checklist_1.workspaceChangeTargets)(this.cwd, (0, task_checklist_1.requestedWorkspaceChanges)(todo.content).paths).includes(target));
237
+ const covering = this.taskTodos.filter(todo => (0, task_checklist_1.todoFileTargets)(todo.content, this.cwd, this.taskChecklistTargets).some(scope => scope.candidates.includes(target) ||
238
+ (scope.unscopedBasename && (0, path_1.basename)(target) === scope.declared)));
180
239
  return covering.length > 0 && covering.every(todo => todo.deferredReason)
181
240
  ? `The user deferred the checklist step that changes ${target}.`
182
241
  : undefined;
@@ -240,10 +299,9 @@ class HarnessKernel {
240
299
  if (this.taskTodoReceipts.some(([, recordedDigest]) => recordedDigest === digest))
241
300
  return;
242
301
  const required = todo.verification ?? [];
302
+ const implementation = (0, task_checklist_1.isImplementationTodo)(todo);
243
303
  let evidence;
244
- if (required.length) {
245
- if (!kind || !required.includes(kind))
246
- return;
304
+ if (kind && required.includes(kind)) {
247
305
  const requested = todoChecks(todo.content).filter(check => check.kind === kind);
248
306
  if (requested.length &&
249
307
  !requested.some(check => matchesTodoCheck(observation, check, this.cwd)))
@@ -255,16 +313,17 @@ class HarnessKernel {
255
313
  ...(requested.length ? { command, cwd: (0, path_1.resolve)(this.cwd, cwd ?? '.') } : {}),
256
314
  };
257
315
  }
258
- else if ((0, task_checklist_1.isImplementationTodo)(todo)) {
259
- if (!passed || !changedFile)
260
- return;
316
+ else if (passed && changedFile && implementation) {
261
317
  const path = (0, verification_1.workspaceArtifactPath)(this.cwd, changedFile);
262
- const targets = (0, task_checklist_1.workspaceChangeTargets)(this.cwd, (0, task_checklist_1.requestedWorkspaceChanges)(todo.content).paths);
263
- if (!path || (targets.length && !targets.includes(path)))
318
+ const targets = (0, task_checklist_1.todoFileTargets)(todo.content, this.cwd, this.taskChecklistTargets);
319
+ if (!path ||
320
+ (targets.length &&
321
+ !targets.some(target => target.candidates.includes(path) ||
322
+ (target.unscopedBasename && (0, path_1.basename)(path) === target.declared))))
264
323
  return;
265
324
  evidence = { changedFile: path };
266
325
  }
267
- else if (!passed) {
326
+ else if (required.length || implementation || !passed) {
268
327
  return;
269
328
  }
270
329
  const index = this.taskTodoReceipts.findIndex(([name, , previous]) => name === step && sameTodoEvidenceTarget(previous, evidence));
@@ -280,39 +339,60 @@ class HarnessKernel {
280
339
  this.touch();
281
340
  }
282
341
  updateTaskTodos(todos, blockedReason) {
283
- const previousTodos = new Map(this.taskTodos.map(todo => [todo.content, todo]));
284
- const next = new Map(todos.map(todo => {
285
- const previous = previousTodos.get(todo.content);
286
- return [
287
- todo.content,
288
- withTodoVerification(todo, previous?.id ?? this.taskTodoId(todo.content), previous),
289
- ];
290
- }));
291
- if (next.size !== todos.length)
342
+ const requested = new Map(todos.map(todo => [todo.content, todo]));
343
+ const originalNames = new Set(this.taskTodos.map(todo => todo.content));
344
+ const previousByRequest = new Map();
345
+ if (requested.size !== todos.length)
292
346
  return 'Todo descriptions must be unique.';
293
- if (this.taskTodos.some(todo => todo.deferredReason) && next.size > previousTodos.size) {
347
+ if (this.taskTodos.some(todo => todo.deferredReason) && todos.length > this.taskTodos.length) {
294
348
  return 'The user deferred part of the checklist. Wait for their continuation before adding steps.';
295
349
  }
296
350
  for (const previous of this.taskTodos) {
297
- const replacement = next.get(previous.content);
351
+ let replacement = requested.get(previous.content);
352
+ if (!replacement && previous.status !== 'completed' && !previous.deferredReason) {
353
+ const refinements = todos.filter(todo => !originalNames.has(todo.content) &&
354
+ !previousByRequest.has(todo.content) &&
355
+ (0, task_checklist_1.clarifiesTodoFileTarget)(previous, todo, this.cwd, this.taskChecklistTargets));
356
+ if (refinements.length === 1)
357
+ replacement = refinements[0];
358
+ }
298
359
  if (!replacement)
299
360
  return `Keep the existing todo "${previous.content}" in the checklist.`;
300
361
  if (previous.deferredReason && replacement.status !== 'pending') {
301
362
  return `The user deferred "${previous.content}". Keep it pending until they explicitly continue.`;
302
363
  }
303
- if (previous.status === 'completed' && replacement.status !== 'completed') {
364
+ if (previous.status === 'completed' &&
365
+ replacement.status !== 'completed' &&
366
+ !this.missingTodoEvidence(previous)) {
304
367
  return `Add a new todo for further work on "${previous.content}".`;
305
368
  }
369
+ previousByRequest.set(replacement.content, previous);
306
370
  }
307
- for (const todo of next.values()) {
308
- if (todo.status !== 'completed')
309
- continue;
310
- const missing = this.missingTodoEvidence(todo);
311
- if (missing)
312
- return missing;
371
+ const warnings = [];
372
+ let hasIndependentUpdate = false;
373
+ let triedToAdvanceActiveTodo = false;
374
+ const next = todos.map(input => {
375
+ const previous = previousByRequest.get(input.content);
376
+ const todo = withTodoVerification(input, previous?.id ?? this.taskTodoId(input.content), previous);
377
+ const missing = todo.status === 'completed' ? this.missingTodoEvidence(todo) : undefined;
378
+ if (missing) {
379
+ warnings.push(missing);
380
+ triedToAdvanceActiveTodo || (triedToAdvanceActiveTodo = previous?.status === 'in_progress');
381
+ return { ...todo, status: 'pending' };
382
+ }
383
+ hasIndependentUpdate || (hasIndependentUpdate = !previous ||
384
+ previous.status !== todo.status ||
385
+ previous.content !== todo.content ||
386
+ previous.verification?.length !== todo.verification?.length);
387
+ return todo;
388
+ });
389
+ // Keep the active step if it still needs evidence so its next tool call
390
+ // can supply it. Repeated stale claims on inactive steps can stay pending.
391
+ if (warnings.length && (triedToAdvanceActiveTodo || !hasIndependentUpdate)) {
392
+ return warnings.join('\n');
313
393
  }
314
394
  if (blockedReason !== undefined) {
315
- const active = [...next.values()].find(todo => todo.status === 'in_progress');
395
+ const active = next.find(todo => todo.status === 'in_progress');
316
396
  if (!active || !blockedReason.trim())
317
397
  return 'Report the blocker on an active todo.';
318
398
  this.reportedTaskBlocker = {
@@ -320,9 +400,17 @@ class HarnessKernel {
320
400
  message: `Blocked at “${active.content}”. ${(0, redaction_1.redactTraceText)(blockedReason.trim())}`,
321
401
  };
322
402
  }
323
- this.taskTodos = [...next.values()];
403
+ this.taskTodos = next;
324
404
  this.touch();
325
- return undefined;
405
+ if (warnings.length) {
406
+ const applied = next.map(({ content, activeForm, status, verification }) => ({
407
+ content,
408
+ activeForm,
409
+ status,
410
+ ...(verification ? { verification } : {}),
411
+ }));
412
+ return { todos: applied, warnings };
413
+ }
326
414
  }
327
415
  taskTodoId(content) {
328
416
  return (0, crypto_1.createHash)('sha256')
@@ -332,6 +420,10 @@ class HarnessKernel {
332
420
  }
333
421
  missingTodoEvidence(todo) {
334
422
  const receipts = this.taskTodoReceipts.filter(([step]) => step === todo.id);
423
+ const description = (0, redaction_1.redactTraceText)(todo.content);
424
+ const problems = [];
425
+ let missingChecks = [];
426
+ const implementation = (0, task_checklist_1.isImplementationTodo)(todo);
335
427
  if (todo.verification?.length) {
336
428
  const expected = todoChecks(todo.content);
337
429
  const verified = receipts.flatMap(([, , result]) => result &&
@@ -340,32 +432,77 @@ class HarnessKernel {
340
432
  result.workspaceRevision === this.ledger.workspaceRevision
341
433
  ? [result]
342
434
  : []);
343
- const missing = todo.verification.flatMap(kind => {
435
+ missingChecks = todo.verification.flatMap(kind => {
344
436
  const selectors = expected.filter(check => check.kind === kind);
345
437
  if (selectors.length) {
346
438
  return selectors
347
439
  .filter(check => !verified.some(result => matchesTodoCheck(result, check, this.cwd)))
348
- .map(check => check.command);
440
+ .map(check => this.formatTodoCheck(check.command, check.cwd));
349
441
  }
350
- return verified.some(result => result.kind === kind) ? [] : [kind];
442
+ if (verified.some(result => result.kind === kind))
443
+ return [];
444
+ return [kind === 'diff' ? this.diffTodoCheckHint() : kind];
351
445
  });
352
- if (missing.length === 0)
353
- return undefined;
354
- return `Keep "${todo.content}" open until its required checks pass: ${missing.join(', ')}. Run each check directly with exec_command while this todo is in progress.`;
446
+ if (missingChecks.length) {
447
+ problems.push('Run each check directly with exec_command while this todo is in progress.');
448
+ if (missingChecks.some(item => item.includes('git diff'))) {
449
+ problems.push('A patch display only shows the changes. A compound shell call reports its overall result. A direct diff check records the verification receipt.');
450
+ }
451
+ }
355
452
  }
356
- if ((0, task_checklist_1.isImplementationTodo)(todo)) {
453
+ if (implementation) {
357
454
  const changedFiles = new Set(receipts.flatMap(([, , result]) => result && 'changedFile' in result ? [result.changedFile] : []));
358
- const targets = (0, task_checklist_1.workspaceChangeTargets)(this.cwd, (0, task_checklist_1.requestedWorkspaceChanges)(todo.content).paths);
359
- const remaining = targets.filter(target => !changedFiles.has(target));
360
- if (remaining.length)
361
- return `Keep "${todo.content}" open until there are verified file changes for: ${remaining.join(', ')}.`;
362
- if (changedFiles.size)
363
- return undefined;
364
- return `Keep "${todo.content}" open until a successful workspace change is recorded for that step.`;
455
+ const targets = (0, task_checklist_1.todoFileTargets)(todo.content, this.cwd, this.taskChecklistTargets);
456
+ const needsClarification = targets.filter(target => target.candidates.length > 1 ||
457
+ (target.unscopedBasename &&
458
+ !changedFiles.has(target.candidates[0]) &&
459
+ [...changedFiles].some(path => (0, path_1.basename)(path) === target.declared)));
460
+ if (needsClarification.length) {
461
+ problems.push(`Clarify the exact workspace-relative path for ${needsClarification.map(target => target.declared).join(', ')} in this todo.`);
462
+ }
463
+ const remaining = targets.filter(target => !needsClarification.includes(target) &&
464
+ (target.candidates.length !== 1 || !changedFiles.has(target.candidates[0])));
465
+ if (remaining.length) {
466
+ const paths = remaining.map(target => target.candidates[0] ?? target.declared).join(', ');
467
+ problems.push(`Wait for verified file changes for: ${(0, redaction_1.redactTraceText)(paths)}.`);
468
+ }
469
+ else if (!targets.length && !changedFiles.size) {
470
+ problems.push('Record a successful workspace change for this step.');
471
+ }
365
472
  }
473
+ if (problems.length) {
474
+ const required = missingChecks.length
475
+ ? ` until its required checks pass: ${missingChecks.join(', ')}`
476
+ : '';
477
+ return `Keep "${description}" open${required}. ${problems.join(' ')}`;
478
+ }
479
+ if (implementation || todo.verification?.length)
480
+ return undefined;
366
481
  if (receipts.some(([, , result]) => !result))
367
482
  return undefined;
368
- return `Keep "${todo.content}" open until a successful tool receipt is recorded for that step.`;
483
+ return `Keep "${description}" open until a successful tool receipt is recorded for that step.`;
484
+ }
485
+ formatTodoCheck(command, cwd) {
486
+ const path = (0, path_1.relative)(this.cwd, (0, path_1.resolve)(this.cwd, cwd ?? '.'));
487
+ const inWorkspace = path !== '..' && !path.startsWith('..' + path_1.sep) && !(0, path_1.isAbsolute)(path);
488
+ const safeCommand = (0, redaction_1.redactTraceText)(command);
489
+ return inWorkspace
490
+ ? `exec_command(${JSON.stringify({ cwd: (0, redaction_1.redactTraceText)(path || '.'), command: safeCommand })})`
491
+ : `${safeCommand} in the required working directory`;
492
+ }
493
+ diffTodoCheckHint() {
494
+ for (const { metadata } of this.ledger.getEntries().reverse()) {
495
+ if (metadata?.taskContractId !== this.contract?.id)
496
+ continue;
497
+ if (metadata?.toolName !== 'exec_command' || typeof metadata.command !== 'string')
498
+ continue;
499
+ const selector = diffCheckSelector(metadata.command);
500
+ if (!selector)
501
+ continue;
502
+ const cwd = typeof metadata.cwd === 'string' ? metadata.cwd : '.';
503
+ return this.formatTodoCheck(selector.command, (0, path_1.resolve)(this.cwd, cwd, selector.cwd ?? '.'));
504
+ }
505
+ return this.formatTodoCheck('git diff --check');
369
506
  }
370
507
  updateCapabilityProfile(input) {
371
508
  if (this.config.enabled === false)
@@ -609,9 +746,28 @@ class HarnessKernel {
609
746
  if (result.missing.length > 0)
610
747
  result.canComplete = false;
611
748
  }
749
+ const goalBlocker = requireEveryCriterion ? this.goalVerificationBlocker : undefined;
750
+ if (goalBlocker) {
751
+ result.missing.push(goalBlocker);
752
+ result.canComplete = false;
753
+ }
612
754
  const progressDelta = this.recordProgress();
613
755
  result.progressDelta = progressDelta;
614
- result.stopDecision = this.stopController.decideCompletion(result, progressDelta);
756
+ const completion = this.stopController.decideCompletion(result, progressDelta);
757
+ result.stopDecision = goalBlocker
758
+ ? (0, stop_decision_1.createStopDecision)({
759
+ ...completion,
760
+ status: 'blocked',
761
+ reason: { code: 'task_step_blocked', message: goalBlocker },
762
+ nextActions: [
763
+ {
764
+ kind: 'resume',
765
+ label: 'Resume and send the exact replacement check.',
766
+ command: '/goal resume',
767
+ },
768
+ ],
769
+ })
770
+ : completion;
615
771
  const mode = this.config.completionGate === true
616
772
  ? 'block'
617
773
  : this.config.completionGate === false
@@ -746,6 +902,9 @@ class HarnessKernel {
746
902
  ? { taskChecklistTargets: this.taskChecklistTargets }
747
903
  : {}),
748
904
  ...(this.goalTaskId ? { goalTaskId: this.goalTaskId } : {}),
905
+ ...(this.goalVerificationBlocker
906
+ ? { goalVerificationBlocker: this.goalVerificationBlocker }
907
+ : {}),
749
908
  ...(this.taskTodos.length ? { taskTodos: this.taskTodos } : {}),
750
909
  ...(this.taskTodoReceipts.length ? { taskTodoReceipts: [...this.taskTodoReceipts] } : {}),
751
910
  rootObjective: this.rootObjective,
@@ -939,6 +1098,21 @@ function todoChecks(content) {
939
1098
  requested.push({ kind: direct, command });
940
1099
  return requested;
941
1100
  }
1101
+ /** Reuse a recognizable diff selector only as a hint. No inspection call becomes evidence here. */
1102
+ function diffCheckSelector(command) {
1103
+ if ((0, verification_command_1.classifyDirectVerificationCommand)(command) === 'diff')
1104
+ return { command: command.trim() };
1105
+ const match = /^(?:cd\s+([\w./-]+)\s+&&\s+)?git\s+diff(?:\s+(--cached|--staged))?(?:\s+--check)?(?:\s+--(?:\s+([\w./-]+(?:\s+[\w./-]+)*))?)?$/u.exec(command.trim());
1106
+ if (!match)
1107
+ return undefined;
1108
+ const [, cwd, staged, paths] = match;
1109
+ return {
1110
+ cwd,
1111
+ command: ['git diff', staged, '--check', paths ? '-- ' + paths : undefined]
1112
+ .filter(Boolean)
1113
+ .join(' '),
1114
+ };
1115
+ }
942
1116
  function matchesTodoCheck(observed, check, workspace) {
943
1117
  return (observed.kind === check.kind &&
944
1118
  observed.command === check.command &&
@@ -5,6 +5,7 @@ exports.normalizeTaskContract = normalizeTaskContract;
5
5
  exports.createTaskContract = createTaskContract;
6
6
  exports.updateTaskContract = updateTaskContract;
7
7
  const crypto_1 = require("crypto");
8
+ const verification_1 = require("./verification");
8
9
  function normalizeLine(text) {
9
10
  return text.trim().replace(/\s+/g, ' ');
10
11
  }
@@ -166,7 +167,8 @@ function createTaskContract(input, cwd) {
166
167
  const requirements = unique(lines.filter(line => requirementHints.test(line)));
167
168
  const prohibitions = unique(lines.filter(line => prohibitionHints.test(line)));
168
169
  const successCriteria = unique([
169
- ...lines.filter(line => verificationHints.test(line)),
170
+ ...lines.filter(line => verificationHints.test(line) ||
171
+ ((0, verification_1.requestedLocalChecks)(line).length > 0 && (0, verification_1.requiredVerificationKinds)(line).length > 0)),
170
172
  requirements.length === 0 ? `Address the objective: ${objective}` : '',
171
173
  ]);
172
174
  return normalizeTaskContract({
@@ -4,6 +4,8 @@ exports.hasExplicitVerificationNeed = hasExplicitVerificationNeed;
4
4
  exports.checkToolDrift = checkToolDrift;
5
5
  exports.evaluateCompletionGate = evaluateCompletionGate;
6
6
  const path_1 = require("path");
7
+ const redaction_1 = require("../services/redaction");
8
+ const terminal_text_1 = require("../utils/terminal-text");
7
9
  const contract_1 = require("./contract");
8
10
  const verification_1 = require("./verification");
9
11
  const PATH_ARGUMENT_KEYS = new Set([
@@ -311,9 +313,10 @@ function evaluateCompletionGate(params) {
311
313
  if (artifact)
312
314
  requiredKinds.push('file');
313
315
  const applicable = requiredKinds.length > 0;
314
- const linked = criterion.evidenceRefs
316
+ const allLinked = criterion.evidenceRefs
315
317
  .map(ref => ({ ref, entry: byEvidenceRef.get(ref) }))
316
- .filter((item) => item.entry !== undefined && (0, verification_1.isFreshVerification)(item.entry, params.workspaceRevision));
318
+ .filter((item) => item.entry !== undefined);
319
+ const linked = allLinked.filter(item => (0, verification_1.isFreshVerification)(item.entry, params.workspaceRevision));
317
320
  if ((0, verification_1.criterionHasAuthorizedWaiver)(criterion)) {
318
321
  return {
319
322
  criterionId: criterion.id,
@@ -326,13 +329,14 @@ function evaluateCompletionGate(params) {
326
329
  failedKinds: [],
327
330
  };
328
331
  }
329
- const trusted = linked
332
+ const trusted = allLinked
330
333
  .map(item => item.entry)
331
334
  .filter(verification_1.isTrustedEvidence)
332
335
  .sort((left, right) => position.get(right.id) - position.get(left.id));
333
336
  const checks = (0, verification_1.requestedLocalChecks)(criterion.statement);
334
337
  const failedKinds = [];
335
338
  const missingKinds = [];
339
+ const verificationProblems = [];
336
340
  for (const kind of requiredKinds) {
337
341
  if (kind === 'file' && artifact) {
338
342
  const write = (0, verification_1.latestArtifactWrite)(params.ledger, contract.id, contract.allowedScope.cwd, artifact.path);
@@ -354,18 +358,26 @@ function evaluateCompletionGate(params) {
354
358
  !params.requireLocalReceipt ||
355
359
  (entry.type === 'verification' &&
356
360
  typeof entry.metadata?.toolReceiptDigest === 'string')));
361
+ const workspace = contract.allowedScope.cwd;
357
362
  const expected = checks.filter(check => check.kind === kind);
358
- const latest = expected.length
359
- ? expected.map(check => candidates.find(entry => (0, verification_1.matchesRequestedCheck)(entry, check, contract.allowedScope.cwd)))
360
- : [candidates[0]];
361
- if (latest.some(entry => entry?.metadata?.success !== true))
362
- missingKinds.push(kind);
363
- if (latest.some(entry => entry?.metadata?.success === false))
364
- failedKinds.push(kind);
365
- for (const entry of latest) {
366
- if (entry?.metadata?.success === true && !evidence.includes(entry.content)) {
367
- evidence.push(entry.content);
363
+ const selectors = expected.length ? expected : [undefined];
364
+ for (const selector of selectors) {
365
+ const matching = selector
366
+ ? candidates.filter(entry => (0, verification_1.matchesRequestedCheck)(entry, selector, workspace))
367
+ : candidates;
368
+ const current = matching.find(entry => (0, verification_1.isFreshVerification)(entry, params.workspaceRevision));
369
+ if (current?.metadata?.success === true) {
370
+ if (!evidence.includes(current.content))
371
+ evidence.push(current.content);
372
+ continue;
368
373
  }
374
+ if (!missingKinds.includes(kind))
375
+ missingKinds.push(kind);
376
+ const status = current ? 'failed' : matching[0] ? 'stale' : 'missing';
377
+ if (status === 'failed' && !failedKinds.includes(kind))
378
+ failedKinds.push(kind);
379
+ const last = current ?? matching[0];
380
+ verificationProblems.push(verificationProblem(kind, status, workspace, selector, last?.metadata));
369
381
  }
370
382
  }
371
383
  const status = !applicable
@@ -386,6 +398,7 @@ function evaluateCompletionGate(params) {
386
398
  requiredKinds,
387
399
  missingKinds,
388
400
  failedKinds,
401
+ ...(verificationProblems.length ? { verificationProblems } : {}),
389
402
  };
390
403
  });
391
404
  const unsatisfied = criterionResults.filter(result => (params.requireEveryCriterion || result.applicable) &&
@@ -393,11 +406,15 @@ function evaluateCompletionGate(params) {
393
406
  result.status !== 'waived');
394
407
  if (unsatisfied.length > 0 ||
395
408
  (criterionResults.length === 0 && hasExplicitVerificationNeed(contract))) {
396
- if (params.requireEveryCriterion) {
397
- for (const result of unsatisfied)
398
- missing.push(`Verify the Goal criterion: ${result.statement}`);
409
+ for (const result of unsatisfied) {
410
+ if (result.verificationProblems?.length) {
411
+ missing.push(...result.verificationProblems.map(problem => describeVerificationProblem(problem, result.statement)));
412
+ }
413
+ else if (params.requireEveryCriterion) {
414
+ missing.push(`Verify the Goal criterion: ${safeFeedback(result.statement)}`);
415
+ }
399
416
  }
400
- else {
417
+ if (!missing.length && !params.requireEveryCriterion) {
401
418
  missing.push('Required verification has not passed yet.');
402
419
  }
403
420
  }
@@ -411,4 +428,37 @@ function evaluateCompletionGate(params) {
411
428
  criterionResults,
412
429
  };
413
430
  }
431
+ function safeFeedback(text, limit = 240) {
432
+ return (0, terminal_text_1.sanitizeTerminalText)((0, redaction_1.redactTraceText)(text)).replace(/\s+/gu, ' ').trim().slice(0, limit);
433
+ }
434
+ function verificationProblem(kind, status, workspace, selector, metadata) {
435
+ const command = selector?.command ?? metadata?.command;
436
+ const cwd = selector?.cwd ?? metadata?.cwd;
437
+ const scoped = typeof cwd === 'string' ? (0, path_1.relative)(workspace, (0, path_1.resolve)(workspace, cwd)) : '';
438
+ return {
439
+ kind,
440
+ status,
441
+ ...(typeof command === 'string'
442
+ ? {
443
+ command: safeFeedback(command),
444
+ cwd: scoped === '..' || (0, path_1.isAbsolute)(scoped) || scoped.startsWith(`..${path_1.sep}`)
445
+ ? '(outside workspace)'
446
+ : safeFeedback(scoped || '.'),
447
+ }
448
+ : {}),
449
+ ...(status === 'failed' && typeof metadata?.exitCode === 'number'
450
+ ? { exitCode: metadata.exitCode }
451
+ : {}),
452
+ ...(status === 'failed' && typeof metadata?.verificationFailureFingerprint === 'string'
453
+ ? { failureFingerprint: metadata.verificationFailureFingerprint }
454
+ : {}),
455
+ };
456
+ }
457
+ function describeVerificationProblem(problem, statement) {
458
+ const subject = problem.command
459
+ ? `\`${problem.command}\` in \`${problem.cwd}\``
460
+ : safeFeedback(statement);
461
+ const exit = problem.exitCode === undefined ? '' : ` (exit ${problem.exitCode})`;
462
+ return `Verification ${problem.status} for ${subject}${exit}.`;
463
+ }
414
464
  //# sourceMappingURL=drift-guard.js.map
@@ -0,0 +1,11 @@
1
+ import type { TaskContract } from './types';
2
+ import { type RequestedCheck } from './verification';
3
+ export type GoalVerificationCorrection = {
4
+ readonly previous: RequestedCheck;
5
+ readonly next: RequestedCheck;
6
+ } | {
7
+ readonly blocker: string;
8
+ };
9
+ /** Only explicit user correction can supersede a required verification selector. */
10
+ export declare function goalVerificationCorrection(contract: TaskContract, input: string): GoalVerificationCorrection | undefined;
11
+ //# sourceMappingURL=goal-verification.d.ts.map
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.goalVerificationCorrection = goalVerificationCorrection;
4
+ const path_1 = require("path");
5
+ const verification_1 = require("./verification");
6
+ const clarification = 'The Goal check could not be identified. Specify “Replace `old command` with `new command`”, with each workspace directory if needed.';
7
+ /** Only explicit user correction can supersede a required verification selector. */
8
+ function goalVerificationCorrection(contract, input) {
9
+ const prose = input.replace(/\x60[^\x60]+\x60/gu, ' ');
10
+ const nextFirst = /\b(?:instead of|rather than)\b|而不是|取代|代替/u.test(prose.toLowerCase());
11
+ const oldFirst = /\b(?:replace|supersede|switch from|change from)\b|替换|改为|换成/u.test(prose.toLowerCase());
12
+ if (!nextFirst && !oldFirst)
13
+ return undefined;
14
+ const requested = (0, verification_1.locateRequestedChecks)(input);
15
+ const refersToCheck = /\b(?:replace|supersede|change|switch)\s+(?:(?:the|earlier|previous|old|existing|required|original|goal)\s+)*(?:check|verification|test)\b/iu.test(prose) ||
16
+ /\b(?:instead of|rather than)\s+(?:(?:the|earlier|previous|old|existing|required|original|goal)\s+)*(?:check|verification|test)\b/iu.test(prose) ||
17
+ /(?:替换|更改|修改).{0,10}(?:验证|检查|测试)|(?:验证|检查|测试).{0,10}(?:改为|换成|替换)|(?:取代|代替|而不是).{0,10}(?:验证|检查|测试)/u.test(prose);
18
+ const [first, second] = requested;
19
+ const between = second
20
+ ? input.slice(first.end, second.start).replace(/\x60[^\x60]+\x60/gu, ' ')
21
+ : '';
22
+ const replacementFirst = /\b(?:instead of|rather than|to replace|to supersede)\b|而不是|取代|代替|替换(?![成为])/iu.test(between);
23
+ const originalFirst = oldFirst && /\b(?:with|to)\b|改为|换成|替换[成为]/iu.test(between);
24
+ if (!(refersToCheck || replacementFirst || originalFirst))
25
+ return undefined;
26
+ if (!first || requested.length > 2 || (second && !replacementFirst && !originalFirst)) {
27
+ return { blocker: clarification };
28
+ }
29
+ const workspace = contract.allowedScope.cwd;
30
+ const existing = [];
31
+ for (const criterion of contract.criteria ?? []) {
32
+ for (const check of (0, verification_1.requestedLocalChecks)(criterion.statement)) {
33
+ if (!existing.some(prior => (0, verification_1.equalRequestedChecks)(prior, check, workspace)))
34
+ existing.push(check);
35
+ }
36
+ }
37
+ const wanted = !second || replacementFirst ? first : second;
38
+ const oldSelector = !second ? undefined : replacementFirst ? second : first;
39
+ const matching = existing.filter(check => oldSelector
40
+ ? check.command === oldSelector.command &&
41
+ (oldSelector.cwd === undefined || (0, verification_1.equalRequestedChecks)(check, oldSelector, workspace))
42
+ : check.kind === wanted.kind);
43
+ if (!matching.length &&
44
+ oldSelector &&
45
+ existing.some(check => (0, verification_1.equalRequestedChecks)(check, wanted, workspace)))
46
+ return undefined;
47
+ if (matching.length !== 1)
48
+ return { blocker: clarification };
49
+ const [previous] = matching;
50
+ const next = { kind: wanted.kind, command: wanted.command, cwd: wanted.cwd ?? previous.cwd };
51
+ const scoped = (0, path_1.relative)(workspace, (0, path_1.resolve)(workspace, next.cwd ?? '.'));
52
+ if (scoped === '..' || (0, path_1.isAbsolute)(scoped) || scoped.startsWith(`..${path_1.sep}`)) {
53
+ return { blocker: 'Choose a replacement check inside this Goal’s workspace.' };
54
+ }
55
+ if (previous.kind !== next.kind) {
56
+ return {
57
+ blocker: 'Replace the Goal check with a direct check of the same kind. For a different verification requirement, specify the corrected Goal objective.',
58
+ };
59
+ }
60
+ return { previous, next };
61
+ }
62
+ //# sourceMappingURL=goal-verification.js.map