@orion-agents/orion-code 0.4.6 → 0.4.8

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 (52) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/README.md +10 -11
  3. package/README.zh-CN.md +10 -10
  4. package/dist/acp/session-updates.js +1 -0
  5. package/dist/framework/query.d.ts +3 -7
  6. package/dist/framework/query.js +22 -74
  7. package/dist/framework/verification-command.d.ts +23 -0
  8. package/dist/framework/verification-command.js +66 -5
  9. package/dist/harness/assembler.d.ts +1 -0
  10. package/dist/harness/assembler.js +5 -2
  11. package/dist/harness/clarification.d.ts +3 -0
  12. package/dist/harness/clarification.js +56 -0
  13. package/dist/harness/context-harness.d.ts +3 -9
  14. package/dist/harness/context-harness.js +75 -167
  15. package/dist/harness/contract.js +36 -10
  16. package/dist/harness/drift-guard.js +12 -4
  17. package/dist/harness/goal-verification.d.ts +2 -0
  18. package/dist/harness/goal-verification.js +42 -0
  19. package/dist/harness/intent.js +10 -12
  20. package/dist/harness/state.d.ts +3 -0
  21. package/dist/harness/state.js +52 -6
  22. package/dist/harness/task-checklist.d.ts +1 -1
  23. package/dist/harness/task-checklist.js +2 -2
  24. package/dist/harness/types.d.ts +1 -0
  25. package/dist/harness/verification.d.ts +2 -0
  26. package/dist/harness/verification.js +18 -6
  27. package/dist/runtime/agent-loop.js +45 -50
  28. package/dist/runtime/agent-runtime-controller.js +1 -1
  29. package/dist/runtime/goal-lifecycle-v2.js +5 -0
  30. package/dist/runtime/goal-runtime-coordinator.js +6 -2
  31. package/dist/runtime/orion-runtime-v1.js +33 -6
  32. package/dist/runtime/plan-review.d.ts +1 -0
  33. package/dist/runtime/plan-review.js +12 -7
  34. package/dist/runtime/product-orion-runtime.js +7 -3
  35. package/dist/runtime/step-snapshot.d.ts +1 -0
  36. package/dist/runtime/step-snapshot.js +57 -9
  37. package/dist/runtime/task-context-recovery.js +22 -10
  38. package/dist/runtime/task-context-service.d.ts +2 -6
  39. package/dist/runtime/task-context-service.js +3 -12
  40. package/dist/runtime/thread-ui-adapter.js +13 -1
  41. package/dist/runtime/tool-gateway.js +1 -0
  42. package/dist/runtime/ui-events.d.ts +3 -0
  43. package/dist/runtime/verification-feedback.d.ts +4 -0
  44. package/dist/runtime/verification-feedback.js +61 -0
  45. package/dist/tools/bash_security.d.ts +1 -24
  46. package/dist/tools/bash_security.js +7 -124
  47. package/dist/tools/todo.js +9 -13
  48. package/dist/utils/shell-command.d.ts +29 -0
  49. package/dist/utils/shell-command.js +185 -0
  50. package/docs/cli-guide.md +4 -0
  51. package/npm-shrinkwrap.json +2 -2
  52. package/package.json +1 -1
@@ -2,7 +2,7 @@ import type { LLMResponse, Message } from '../services/llm';
2
2
  import type { TodoItem, TodoWriteAdjustment } from '../framework/tool-state';
3
3
  import { type PromptAssemblyOptions } from './assembler';
4
4
  import { type CreateTurnSummaryInput } from './turn-summary';
5
- import type { CompletionGateResult, CapabilityProfileInput, ContextCapsule, DriftCheckResult, HarnessConfig, HarnessProgressState, HarnessState, IntentUpdate, ProgressDelta, TaskPlanStop, TaskTodoObservation, TaskWorkspaceAction, ToolResultObservation, TurnSummary } from './types';
5
+ import type { CompletionGateResult, CapabilityProfileInput, ContextCapsule, DriftCheckResult, HarnessConfig, HarnessProgressState, HarnessState, IntentUpdate, ProgressDelta, TaskTodoObservation, TaskWorkspaceAction, ToolResultObservation, TurnSummary } from './types';
6
6
  export interface ContextHarnessOptions {
7
7
  cwd: string;
8
8
  modelId: string;
@@ -19,7 +19,6 @@ export declare class HarnessKernel {
19
19
  private contract;
20
20
  private ledger;
21
21
  private capsule?;
22
- private completionBlockCount;
23
22
  private taskEpoch;
24
23
  private taskChecklistRequired;
25
24
  private taskChecklistTargets;
@@ -27,8 +26,7 @@ export declare class HarnessKernel {
27
26
  private goalTaskId?;
28
27
  private goalVerificationBlocker?;
29
28
  private taskTodos;
30
- private reportedTaskBlocker?;
31
- private readonly taskTodoReceipts;
29
+ private taskTodoReceipts;
32
30
  private rootObjective?;
33
31
  private activeInstruction?;
34
32
  private intentHistory;
@@ -40,7 +38,6 @@ export declare class HarnessKernel {
40
38
  private promptAssemblyStats?;
41
39
  private diagnostics;
42
40
  private readonly progressController;
43
- private readonly stopController;
44
41
  private capabilityProfile;
45
42
  private capabilityHistory;
46
43
  private reconciledAt?;
@@ -51,12 +48,10 @@ export declare class HarnessKernel {
51
48
  observeGoalSteering(input: string, goalId: string): void;
52
49
  activeTaskTodo(): string | undefined;
53
50
  hasTaskTodos(): boolean;
54
- missingExecutionChecklist(action?: TaskWorkspaceAction): string | undefined;
51
+ deferredWorkspaceWriteReason(action: TaskWorkspaceAction): string | undefined;
55
52
  private checkDeferredWorkspaceAction;
56
- prepareTaskPlanStopCheck(): () => TaskPlanStop | undefined;
57
53
  private hasOnlyDeferredWork;
58
54
  private deferTaskTodos;
59
- requiresVerification(): boolean;
60
55
  recordTaskTodoReceipt(step: string, observation: TaskTodoObservation): void;
61
56
  updateTaskTodos(todos: TodoItem[], blockedReason?: string): TodoWriteAdjustment | string | undefined;
62
57
  private taskTodoId;
@@ -87,7 +82,6 @@ export declare class HarnessKernel {
87
82
  progressState(): HarnessProgressState;
88
83
  recordProgress(baseline?: HarnessProgressState, unconfirmedWorkspaceRevisions?: number): ProgressDelta;
89
84
  beforeComplete(enforceTaskTodos?: boolean, requireEveryCriterion?: boolean): CompletionGateResult;
90
- asCompletionBlockedMessage(result: CompletionGateResult): Message;
91
85
  asToolBlockedResult(result: DriftCheckResult): string;
92
86
  getCapsule(): ContextCapsule | undefined;
93
87
  linkEvidenceToCriterion(criterionId: string, evidenceRef: string): boolean;
@@ -7,11 +7,11 @@ 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");
11
10
  const verification_command_1 = require("../framework/verification-command");
12
11
  const assembler_1 = require("./assembler");
13
12
  const capability_profile_1 = require("./capability-profile");
14
13
  const capsule_1 = require("./capsule");
14
+ const clarification_1 = require("./clarification");
15
15
  const contract_1 = require("./contract");
16
16
  const drift_guard_1 = require("./drift-guard");
17
17
  const evidence_1 = require("./evidence");
@@ -20,7 +20,6 @@ const intent_1 = require("./intent");
20
20
  const ledger_1 = require("./ledger");
21
21
  const progress_controller_1 = require("./progress-controller");
22
22
  const state_1 = require("./state");
23
- const stop_controller_1 = require("./stop-controller");
24
23
  const task_checklist_1 = require("./task-checklist");
25
24
  const turn_summary_1 = require("./turn-summary");
26
25
  const verification_1 = require("./verification");
@@ -31,7 +30,6 @@ const DEFAULT_CONFIG = {
31
30
  maxRecentTurns: 8,
32
31
  evidenceBudgetRatio: 0.3,
33
32
  driftGuard: 'warn',
34
- completionGate: 'warn',
35
33
  };
36
34
  /** Canonical v0.1.9 task-state owner; ContextHarness remains a compatibility alias. */
37
35
  class HarnessKernel {
@@ -45,7 +43,6 @@ class HarnessKernel {
45
43
  this.ledger = new ledger_1.ContextLedger(state.ledger, state.workspaceRevision);
46
44
  this.verificationWorkspace = state.verificationWorkspace;
47
45
  this.capsule = state.capsule;
48
- this.completionBlockCount = state.completionBlockCount ?? 0;
49
46
  this.taskEpoch = state.taskEpoch ?? 1;
50
47
  this.goalTaskId = state.goalTaskId;
51
48
  this.goalVerificationBlocker = state.goalVerificationBlocker;
@@ -59,11 +56,7 @@ class HarnessKernel {
59
56
  byDescription.get(savedId) ?? savedId,
60
57
  ...receipt,
61
58
  ]);
62
- this.taskTodos = todos.map(todo => {
63
- return todo.status === 'completed' && this.missingTodoEvidence(todo)
64
- ? { ...todo, status: 'pending' }
65
- : todo;
66
- });
59
+ this.taskTodos = todos;
67
60
  this.rootObjective = state.rootObjective;
68
61
  this.activeInstruction = state.activeInstruction;
69
62
  this.intentHistory = state.intentHistory ?? [];
@@ -77,18 +70,22 @@ class HarnessKernel {
77
70
  this.promptAssemblyStats = state.promptAssemblyStats;
78
71
  this.diagnostics = state.diagnostics ?? [];
79
72
  this.progressController = new progress_controller_1.ProgressController(state.progressState);
80
- this.stopController = new stop_controller_1.StopController();
81
73
  this.capabilityProfile = state.capabilityProfile;
82
74
  this.capabilityHistory = state.capabilityHistory ?? [];
83
75
  this.reconciledAt = state.reconciledAt;
84
76
  this.updatedAt = state.updatedAt;
85
77
  }
86
78
  updateContractFromUserInput(input, goalTaskId) {
87
- this.reportedTaskBlocker = undefined;
88
79
  if (this.config.enabled === false)
89
80
  return;
90
81
  if (goalTaskId && this.goalTaskId === goalTaskId && this.contract)
91
82
  return;
83
+ const classified = (0, intent_1.classifyIntent)(input, this.toJSON());
84
+ if (!goalTaskId && classified.kind === 'clarification') {
85
+ this.intentHistory = [...this.intentHistory, classified].slice(-40);
86
+ this.touch();
87
+ return classified;
88
+ }
92
89
  const deferral = (0, task_checklist_1.requestedTaskDeferral)(input);
93
90
  if (deferral &&
94
91
  this.goalTaskId === goalTaskId &&
@@ -96,7 +93,6 @@ class HarnessKernel {
96
93
  this.deferTaskTodos(deferral);
97
94
  return;
98
95
  }
99
- const classified = (0, intent_1.classifyIntent)(input, this.toJSON());
100
96
  const ownerChanged = this.goalTaskId !== goalTaskId;
101
97
  const intent = ownerChanged
102
98
  ? {
@@ -118,7 +114,6 @@ class HarnessKernel {
118
114
  this.taskTodos = [];
119
115
  this.taskTodoReceipts.length = 0;
120
116
  this.goalVerificationBlocker = undefined;
121
- this.completionBlockCount = 0;
122
117
  this.activeConstraints = [];
123
118
  this.nonGoals = [];
124
119
  this.openQuestions = [];
@@ -160,8 +155,25 @@ class HarnessKernel {
160
155
  }
161
156
  observeGoalSteering(input, goalId) {
162
157
  const contract = this.contract;
163
- if (!contract || this.goalTaskId !== goalId || this.config.enabled === false)
158
+ if (!contract ||
159
+ this.goalTaskId !== goalId ||
160
+ this.config.enabled === false ||
161
+ (0, clarification_1.isReadOnlyQuestion)(input))
162
+ return;
163
+ const bound = (0, goal_verification_1.bindUnspecifiedVerification)(contract, input);
164
+ if (bound) {
165
+ this.ledger.recordUserRequirement(input);
166
+ this.contract = {
167
+ ...bound,
168
+ userIntent: input.trim(),
169
+ updatedAt: Math.max(Date.now(), contract.updatedAt + 1),
170
+ };
171
+ this.activeInstruction = input.trim();
172
+ this.goalVerificationBlocker = undefined;
173
+ this.refreshCapsule();
174
+ this.touch();
164
175
  return;
176
+ }
165
177
  const correction = (0, goal_verification_1.goalVerificationCorrection)(contract, input);
166
178
  if (!correction)
167
179
  return;
@@ -218,18 +230,13 @@ class HarnessKernel {
218
230
  hasTaskTodos() {
219
231
  return this.taskTodos.length > 0;
220
232
  }
221
- missingExecutionChecklist(action) {
233
+ deferredWorkspaceWriteReason(action) {
222
234
  if (this.hasOnlyDeferredWork()) {
223
235
  return 'The user deferred the remaining steps. Wait for explicit continuation.';
224
236
  }
225
- if (action && this.taskTodos.some(todo => todo.deferredReason)) {
226
- const scoped = this.checkDeferredWorkspaceAction(action);
227
- if (scoped)
228
- return scoped;
237
+ if (this.taskTodos.some(todo => todo.deferredReason)) {
238
+ return this.checkDeferredWorkspaceAction(action);
229
239
  }
230
- if (!this.taskChecklistRequired)
231
- return undefined;
232
- return (0, task_checklist_1.executionChecklistIssue)(this.taskTodos, this.taskChecklistTargets, this.cwd);
233
240
  }
234
241
  checkDeferredWorkspaceAction(action) {
235
242
  const target = action.path ? (0, verification_1.workspaceArtifactPath)(this.cwd, action.path) : undefined;
@@ -250,19 +257,6 @@ class HarnessKernel {
250
257
  }
251
258
  return 'The user deferred part of the checklist. Use a file tool for the active step or run its required check before making other workspace changes.';
252
259
  }
253
- prepareTaskPlanStopCheck() {
254
- return () => {
255
- if (this.hasOnlyDeferredWork()) {
256
- return {
257
- code: 'task_deferred',
258
- message: 'The remaining checklist steps are deferred at your request. Say “continue” to resume them.',
259
- };
260
- }
261
- const blocker = this.reportedTaskBlocker;
262
- this.reportedTaskBlocker = undefined;
263
- return blocker;
264
- };
265
- }
266
260
  hasOnlyDeferredWork() {
267
261
  return (this.taskTodos.some(todo => todo.deferredReason) &&
268
262
  this.taskTodos.every(todo => todo.deferredReason || todo.status === 'completed'));
@@ -284,13 +278,6 @@ class HarnessKernel {
284
278
  this.refreshCapsule();
285
279
  this.touch();
286
280
  }
287
- requiresVerification() {
288
- if (this.config.enabled === false ||
289
- (this.config.completionGate !== 'block' && this.config.completionGate !== true))
290
- return false;
291
- return (this.contract?.criteria?.some(item => (0, verification_1.requiredVerificationKinds)(item.statement).length > 0) ||
292
- (0, drift_guard_1.hasExplicitVerificationNeed)(this.contract));
293
- }
294
281
  recordTaskTodoReceipt(step, observation) {
295
282
  const todo = this.taskTodos.find(item => item.status === 'in_progress');
296
283
  if (todo?.id !== step)
@@ -344,62 +331,48 @@ class HarnessKernel {
344
331
  const previousByRequest = new Map();
345
332
  if (requested.size !== todos.length)
346
333
  return 'Todo descriptions must be unique.';
347
- if (this.taskTodos.some(todo => todo.deferredReason) && todos.length > this.taskTodos.length) {
334
+ const hasDeferredTodos = this.taskTodos.some(todo => todo.deferredReason);
335
+ if (hasDeferredTodos && todos.length > this.taskTodos.length) {
348
336
  return 'The user deferred part of the checklist. Wait for their continuation before adding steps.';
349
337
  }
350
338
  for (const previous of this.taskTodos) {
351
339
  let replacement = requested.get(previous.content);
352
- if (!replacement && previous.status !== 'completed' && !previous.deferredReason) {
340
+ if (!replacement &&
341
+ !previous.deferredReason &&
342
+ (previous.status !== 'completed' || this.missingTodoEvidence(previous))) {
353
343
  const refinements = todos.filter(todo => !originalNames.has(todo.content) &&
354
344
  !previousByRequest.has(todo.content) &&
355
345
  (0, task_checklist_1.clarifiesTodoFileTarget)(previous, todo, this.cwd, this.taskChecklistTargets));
356
346
  if (refinements.length === 1)
357
347
  replacement = refinements[0];
358
348
  }
359
- if (!replacement)
360
- return `Keep the existing todo "${previous.content}" in the checklist.`;
361
- if (previous.deferredReason && replacement.status !== 'pending') {
349
+ if (previous.deferredReason && replacement?.status !== 'pending') {
362
350
  return `The user deferred "${previous.content}". Keep it pending until they explicitly continue.`;
363
351
  }
364
- if (previous.status === 'completed' &&
365
- replacement.status !== 'completed' &&
366
- !this.missingTodoEvidence(previous)) {
367
- return `Add a new todo for further work on "${previous.content}".`;
352
+ if (hasDeferredTodos && !replacement) {
353
+ return `Keep the existing todo "${previous.content}" while the user has deferred steps.`;
368
354
  }
369
- previousByRequest.set(replacement.content, previous);
355
+ if (replacement)
356
+ previousByRequest.set(replacement.content, previous);
370
357
  }
371
- const warnings = [];
372
- let hasIndependentUpdate = false;
373
- let triedToAdvanceActiveTodo = false;
374
358
  const next = todos.map(input => {
375
359
  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;
360
+ return withTodoVerification(input, previous?.id ?? this.taskTodoId(input.content), previous);
388
361
  });
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');
393
- }
362
+ const warnings = [];
394
363
  if (blockedReason !== undefined) {
395
364
  const active = next.find(todo => todo.status === 'in_progress');
396
365
  if (!active || !blockedReason.trim())
397
366
  return 'Report the blocker on an active todo.';
398
- this.reportedTaskBlocker = {
399
- code: 'task_step_blocked',
400
- message: `Blocked at “${active.content}”. ${(0, redaction_1.redactTraceText)(blockedReason.trim())}`,
401
- };
367
+ warnings.push(`Reported blocker for “${active.content}”. ${(0, redaction_1.redactTraceText)(blockedReason.trim())}`);
368
+ }
369
+ for (const todo of next) {
370
+ const missing = todo.status === 'completed' ? this.missingTodoEvidence(todo) : undefined;
371
+ if (missing)
372
+ warnings.push(missing);
402
373
  }
374
+ const retained = new Set(next.map(todo => todo.id));
375
+ this.taskTodoReceipts = this.taskTodoReceipts.filter(([id]) => retained.has(id));
403
376
  this.taskTodos = next;
404
377
  this.touch();
405
378
  if (warnings.length) {
@@ -422,7 +395,6 @@ class HarnessKernel {
422
395
  const receipts = this.taskTodoReceipts.filter(([step]) => step === todo.id);
423
396
  const description = (0, redaction_1.redactTraceText)(todo.content);
424
397
  const problems = [];
425
- let missingChecks = [];
426
398
  const implementation = (0, task_checklist_1.isImplementationTodo)(todo);
427
399
  if (todo.verification?.length) {
428
400
  const expected = todoChecks(todo.content);
@@ -432,7 +404,7 @@ class HarnessKernel {
432
404
  result.workspaceRevision === this.ledger.workspaceRevision
433
405
  ? [result]
434
406
  : []);
435
- missingChecks = todo.verification.flatMap(kind => {
407
+ const missingChecks = todo.verification.flatMap(kind => {
436
408
  const selectors = expected.filter(check => check.kind === kind);
437
409
  if (selectors.length) {
438
410
  return selectors
@@ -444,7 +416,7 @@ class HarnessKernel {
444
416
  return [kind === 'diff' ? this.diffTodoCheckHint() : kind];
445
417
  });
446
418
  if (missingChecks.length) {
447
- problems.push('Run each check directly with exec_command while this todo is in progress.');
419
+ problems.push(`No matching passing check was recorded for ${missingChecks.join(', ')}.`);
448
420
  if (missingChecks.some(item => item.includes('git diff'))) {
449
421
  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
422
  }
@@ -458,29 +430,20 @@ class HarnessKernel {
458
430
  !changedFiles.has(target.candidates[0]) &&
459
431
  [...changedFiles].some(path => (0, path_1.basename)(path) === target.declared)));
460
432
  if (needsClarification.length) {
461
- problems.push(`Clarify the exact workspace-relative path for ${needsClarification.map(target => target.declared).join(', ')} in this todo.`);
433
+ problems.push(`The workspace-relative path is ambiguous for ${needsClarification.map(target => target.declared).join(', ')}.`);
462
434
  }
463
435
  const remaining = targets.filter(target => !needsClarification.includes(target) &&
464
436
  (target.candidates.length !== 1 || !changedFiles.has(target.candidates[0])));
465
437
  if (remaining.length) {
466
438
  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)}.`);
439
+ problems.push(`No matching file change was recorded for ${(0, redaction_1.redactTraceText)(paths)}.`);
468
440
  }
469
441
  else if (!targets.length && !changedFiles.size) {
470
- problems.push('Record a successful workspace change for this step.');
442
+ problems.push('No successful workspace change was recorded for this step.');
471
443
  }
472
444
  }
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;
481
- if (receipts.some(([, , result]) => !result))
482
- return undefined;
483
- return `Keep "${description}" open until a successful tool receipt is recorded for that step.`;
445
+ if (problems.length)
446
+ return `"${description}" is unverified. ${problems.join(' ')}`;
484
447
  }
485
448
  formatTodoCheck(command, cwd) {
486
449
  const path = (0, path_1.relative)(this.cwd, (0, path_1.resolve)(this.cwd, cwd ?? '.'));
@@ -736,76 +699,20 @@ class HarnessKernel {
736
699
  };
737
700
  }
738
701
  if (enforceTaskTodos) {
739
- const checklist = this.missingExecutionChecklist();
740
- if (checklist)
741
- result.missing.push(checklist);
742
702
  for (const todo of this.taskTodos) {
743
- if (todo.status !== 'completed')
744
- result.missing.push(`Unfinished todo: ${todo.content}`);
703
+ const remaining = todo.status === 'completed'
704
+ ? this.missingTodoEvidence(todo)
705
+ : `Unfinished todo: ${todo.content}`;
706
+ if (remaining)
707
+ result.missing.push(remaining);
745
708
  }
746
- if (result.missing.length > 0)
747
- result.canComplete = false;
748
- }
749
- const goalBlocker = requireEveryCriterion ? this.goalVerificationBlocker : undefined;
750
- if (goalBlocker) {
751
- result.missing.push(goalBlocker);
752
- result.canComplete = false;
753
- }
754
- const progressDelta = this.recordProgress();
755
- result.progressDelta = 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;
771
- const mode = this.config.completionGate === true
772
- ? 'block'
773
- : this.config.completionGate === false
774
- ? 'off'
775
- : (this.config.completionGate ?? 'warn');
776
- if (!result.canComplete && mode !== 'off') {
777
- this.ledger.add({
778
- type: mode === 'block' ? 'blocker' : 'risk',
779
- content: `Completion gate missing: ${result.missing.join('; ')}`,
780
- source: { kind: 'system', ref: 'completion_gate' },
781
- importance: 5,
782
- ttl: 'task',
783
- metadata: { missing: result.missing, mode },
784
- });
785
- this.refreshCapsule();
786
- this.touch();
787
- }
788
- // Block completion until evidence is provided. Track consecutive blocks
789
- // so callers can detect a stalled loop, but never silently pass the gate
790
- // without evidence.
791
- if (!result.canComplete && (mode === 'block' || requireEveryCriterion)) {
792
- this.completionBlockCount++;
793
- this.touch();
794
- return result;
795
709
  }
796
- if (result.canComplete) {
797
- const changed = this.completionBlockCount !== 0;
798
- this.completionBlockCount = 0;
799
- if (changed)
800
- this.touch();
710
+ if (requireEveryCriterion && this.goalVerificationBlocker) {
711
+ result.missing.push(this.goalVerificationBlocker);
801
712
  }
802
- return { ...result, canComplete: true };
803
- }
804
- asCompletionBlockedMessage(result) {
805
- return {
806
- role: 'user',
807
- content: `[Harness Completion Gate]\nThe task is not ready to finish.\nMissing:\n${result.missing.map(item => `- ${item}`).join('\n')}\nContinue working or explicitly explain why verification cannot be run.`,
808
- };
713
+ result.canComplete = result.missing.length === 0;
714
+ result.progressDelta = this.recordProgress();
715
+ return result;
809
716
  }
810
717
  asToolBlockedResult(result) {
811
718
  return JSON.stringify({
@@ -895,7 +802,6 @@ class HarnessKernel {
895
802
  workspaceRevision: this.ledger.workspaceRevision,
896
803
  ...(this.verificationWorkspace ? { verificationWorkspace: this.verificationWorkspace } : {}),
897
804
  capsule: this.capsule,
898
- completionBlockCount: this.completionBlockCount,
899
805
  taskEpoch: this.taskEpoch,
900
806
  ...(this.taskChecklistRequired ? { taskChecklistRequired: true } : {}),
901
807
  ...(this.taskChecklistTargets.length
@@ -972,22 +878,24 @@ class HarnessKernel {
972
878
  : criterion),
973
879
  };
974
880
  }
975
- this.taskTodos = this.taskTodos.map(todo => todo.status === 'completed' && todo.verification?.length && this.missingTodoEvidence(todo)
976
- ? { ...todo, status: 'pending' }
977
- : todo);
978
881
  }
979
882
  autoLinkVerificationEvidence(entry) {
980
883
  if (!this.contract?.criteria || !(0, verification_1.isTrustedEvidence)(entry))
981
884
  return;
982
885
  const kind = (0, verification_1.verificationKindForEntry)(entry, this.requireLocalVerificationReceipt);
983
- if (kind === 'generic' && entry.type !== 'verification')
886
+ if (kind === 'generic' &&
887
+ (entry.type !== 'verification' ||
888
+ (this.requireLocalVerificationReceipt &&
889
+ typeof entry.metadata?.toolReceiptDigest !== 'string'))) {
984
890
  return;
891
+ }
985
892
  const workspace = this.contract.allowedScope.cwd;
986
893
  for (const criterion of this.contract.criteria) {
987
894
  if (!(0, verification_1.requiredVerificationKinds)(criterion.statement).includes(kind))
988
895
  continue;
989
896
  const checks = (0, verification_1.requestedLocalChecks)(criterion.statement).filter(check => check.kind === kind);
990
- if (checks.length && !checks.some(check => (0, verification_1.matchesRequestedCheck)(entry, check, workspace)))
897
+ if ((kind === 'generic' || checks.length) &&
898
+ !checks.some(check => (0, verification_1.matchesRequestedCheck)(entry, check, workspace)))
991
899
  continue;
992
900
  this.updateCriterionEvidence(criterion.id, entry.id);
993
901
  }
@@ -1115,8 +1023,8 @@ function diffCheckSelector(command) {
1115
1023
  }
1116
1024
  function matchesTodoCheck(observed, check, workspace) {
1117
1025
  return (observed.kind === check.kind &&
1118
- observed.command === check.command &&
1119
- (!check.cwd || (0, path_1.resolve)(workspace, observed.cwd ?? '.') === (0, path_1.resolve)(workspace, check.cwd)));
1026
+ observed.command !== undefined &&
1027
+ (0, verification_1.matchesRequestedCheckInvocation)(observed.command, observed.cwd, check, workspace));
1120
1028
  }
1121
1029
  function sameTodoEvidenceTarget(previous, next) {
1122
1030
  if (!previous || !next)
@@ -5,9 +5,13 @@ exports.normalizeTaskContract = normalizeTaskContract;
5
5
  exports.createTaskContract = createTaskContract;
6
6
  exports.updateTaskContract = updateTaskContract;
7
7
  const crypto_1 = require("crypto");
8
+ const clarification_1 = require("./clarification");
9
+ const goal_verification_1 = require("./goal-verification");
8
10
  const verification_1 = require("./verification");
9
11
  function normalizeLine(text) {
10
- return text.trim().replace(/\s+/g, ' ');
12
+ return text
13
+ .trim()
14
+ .replace(/\x60[^\x60\r\n]+\x60|\s+/gu, value => (value.startsWith('\x60') ? value : ' '));
11
15
  }
12
16
  function cleanLine(line) {
13
17
  return line.replace(/^[-*+\d.)\s]+/, '').trim();
@@ -29,7 +33,11 @@ function isObjectiveFallback(item) {
29
33
  return item.startsWith('Address the objective: ');
30
34
  }
31
35
  function stableCriterionId(statement) {
32
- const digest = (0, crypto_1.createHash)('sha256').update(normalizeLine(statement).toLowerCase()).digest('hex');
36
+ const normalized = normalizeLine(statement)
37
+ .split(/(\x60[^\x60\r\n]+\x60)/u)
38
+ .map((part, index) => (index % 2 === 0 ? part.toLowerCase() : part))
39
+ .join('');
40
+ const digest = (0, crypto_1.createHash)('sha256').update(normalized).digest('hex');
33
41
  return `criterion:harness:${digest.slice(0, 16)}`;
34
42
  }
35
43
  function normalizeCriterionStatus(criterion) {
@@ -128,7 +136,19 @@ function extractExplicitObjective(input) {
128
136
  return undefined;
129
137
  }
130
138
  function normalizeTaskContract(contract) {
131
- const requirements = unique((contract.requirements ?? []).filter(item => !isSectionHeading(item)));
139
+ const isInferredQuestion = (item) => {
140
+ if (!(0, clarification_1.isReadOnlyQuestion)(item))
141
+ return false;
142
+ const statement = normalizeLine(item);
143
+ return !(contract.criteria ?? []).some(criterion => typeof criterion?.statement === 'string' &&
144
+ normalizeLine(criterion.statement) === statement &&
145
+ (criterion.id !== stableCriterionId(statement) ||
146
+ criterion.scope !== 'task' ||
147
+ criterion.source?.kind !== 'user' ||
148
+ criterion.source.ref ||
149
+ criterion.waiver));
150
+ };
151
+ const requirements = unique((contract.requirements ?? []).filter(item => !isSectionHeading(item) && !isInferredQuestion(item)));
132
152
  const typedCriterionStatements = (contract.criteria ?? [])
133
153
  .map(criterion => criterion?.statement)
134
154
  .filter((statement) => typeof statement === 'string');
@@ -140,7 +160,7 @@ function normalizeTaskContract(contract) {
140
160
  // statements that remain authoritative.
141
161
  const legacySuccessCriteria = contract.successCriteria ?? [];
142
162
  const inputSuccessCriteria = legacySuccessCriteria.length > 0 ? legacySuccessCriteria : typedCriterionStatements;
143
- const explicitSuccessCriteria = unique(inputSuccessCriteria.filter(item => !isSectionHeading(item) && !isObjectiveFallback(item)));
163
+ const explicitSuccessCriteria = unique(inputSuccessCriteria.filter(item => !isSectionHeading(item) && !isObjectiveFallback(item) && !isInferredQuestion(item)));
144
164
  const fallbackCriteria = unique(inputSuccessCriteria.filter(isObjectiveFallback));
145
165
  const successCriteria = explicitSuccessCriteria.length > 0 || requirements.length > 0
146
166
  ? explicitSuccessCriteria
@@ -159,17 +179,20 @@ function normalizeTaskContract(contract) {
159
179
  function createTaskContract(input, cwd) {
160
180
  const now = Date.now();
161
181
  const lines = splitMeaningfulLines(input);
182
+ const workLines = (0, clarification_1.isReadOnlyQuestion)(input)
183
+ ? []
184
+ : lines.filter(line => !(0, clarification_1.isReadOnlyQuestion)(line));
162
185
  const objective = extractExplicitObjective(input) ??
163
- normalizeLine(lines[0] || input || 'Continue the current task');
186
+ normalizeLine(workLines[0] || lines[0] || input || 'Continue the current task');
164
187
  const requirementHints = /(must|should|required|require|need|ensure|verify|test|build|run|希望|需要|必须|要求|确保|验证|测试|完成)/i;
165
188
  const prohibitionHints = /(do not|don't|never|avoid|without|禁止|不要|不能|不准|避免)/i;
166
189
  const verificationHints = /(test|build|tsc|lint|verify|验证|测试|通过|运行|检查)/i;
167
- const requirements = unique(lines.filter(line => requirementHints.test(line)));
168
- const prohibitions = unique(lines.filter(line => prohibitionHints.test(line)));
190
+ const requirements = unique(workLines.filter(line => requirementHints.test(line)));
191
+ const prohibitions = unique(workLines.filter(line => prohibitionHints.test(line)));
169
192
  const successCriteria = unique([
170
- ...lines.filter(line => verificationHints.test(line) ||
193
+ ...workLines.filter(line => verificationHints.test(line) ||
171
194
  ((0, verification_1.requestedLocalChecks)(line).length > 0 && (0, verification_1.requiredVerificationKinds)(line).length > 0)),
172
- requirements.length === 0 ? `Address the objective: ${objective}` : '',
195
+ workLines.length > 0 && requirements.length === 0 ? `Address the objective: ${objective}` : '',
173
196
  ]);
174
197
  return normalizeTaskContract({
175
198
  version: 3,
@@ -192,11 +215,14 @@ function updateTaskContract(previous, input, cwd, intent) {
192
215
  if (!previous) {
193
216
  return createTaskContract(input, cwd);
194
217
  }
195
- const normalizedPrevious = normalizeTaskContract(previous);
218
+ const original = normalizeTaskContract(previous);
219
+ if (intent?.kind === 'clarification' || (!intent && (0, clarification_1.isReadOnlyQuestion)(input)))
220
+ return original;
196
221
  const next = createTaskContract(input, cwd);
197
222
  if (intent?.kind === 'new_task') {
198
223
  return { ...next, taskEpoch: intent.taskEpoch };
199
224
  }
225
+ const normalizedPrevious = (0, goal_verification_1.bindUnspecifiedVerification)(original, input) ?? original;
200
226
  const nextSuccessCriteria = next.successCriteria.filter(item => !isObjectiveFallback(item));
201
227
  return normalizeTaskContract({
202
228
  ...normalizedPrevious,
@@ -355,11 +355,16 @@ function evaluateCompletionGate(params) {
355
355
  }
356
356
  const candidates = trusted.filter(entry => (0, verification_1.verificationKindForEntry)(entry, params.requireLocalReceipt) === kind &&
357
357
  (kind !== 'generic' ||
358
- !params.requireLocalReceipt ||
359
358
  (entry.type === 'verification' &&
360
- typeof entry.metadata?.toolReceiptDigest === 'string')));
359
+ (!params.requireLocalReceipt ||
360
+ typeof entry.metadata?.toolReceiptDigest === 'string'))));
361
361
  const workspace = contract.allowedScope.cwd;
362
362
  const expected = checks.filter(check => check.kind === kind);
363
+ if (kind === 'generic' && !expected.length) {
364
+ missingKinds.push(kind);
365
+ verificationProblems.push({ kind, status: 'missing' });
366
+ continue;
367
+ }
363
368
  const selectors = expected.length ? expected : [undefined];
364
369
  for (const selector of selectors) {
365
370
  const matching = selector
@@ -457,8 +462,11 @@ function verificationProblem(kind, status, workspace, selector, metadata) {
457
462
  function describeVerificationProblem(problem, statement) {
458
463
  const subject = problem.command
459
464
  ? `\`${problem.command}\` in \`${problem.cwd}\``
460
- : safeFeedback(statement);
465
+ : safeFeedback(statement).replace(/[.。]+$/u, '');
461
466
  const exit = problem.exitCode === undefined ? '' : ` (exit ${problem.exitCode})`;
462
- return `Verification ${problem.status} for ${subject}${exit}.`;
467
+ const clarification = problem.kind === 'generic' && !problem.command
468
+ ? ' Specify the exact checker command and its working directory.'
469
+ : '';
470
+ return `Verification ${problem.status} for ${subject}${exit}.${clarification}`;
463
471
  }
464
472
  //# sourceMappingURL=drift-guard.js.map
@@ -6,6 +6,8 @@ export type GoalVerificationCorrection = {
6
6
  } | {
7
7
  readonly blocker: string;
8
8
  };
9
+ /** An explicit user correction can give one unresolved verification its missing selector. */
10
+ export declare function bindUnspecifiedVerification(contract: TaskContract, input: string): TaskContract | undefined;
9
11
  /** Only explicit user correction can supersede a required verification selector. */
10
12
  export declare function goalVerificationCorrection(contract: TaskContract, input: string): GoalVerificationCorrection | undefined;
11
13
  //# sourceMappingURL=goal-verification.d.ts.map