@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
@@ -1,9 +1,51 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bindUnspecifiedVerification = bindUnspecifiedVerification;
3
4
  exports.goalVerificationCorrection = goalVerificationCorrection;
4
5
  const path_1 = require("path");
5
6
  const verification_1 = require("./verification");
6
7
  const clarification = 'The Goal check could not be identified. Specify “Replace `old command` with `new command`”, with each workspace directory if needed.';
8
+ /** An explicit user correction can give one unresolved verification its missing selector. */
9
+ function bindUnspecifiedVerification(contract, input) {
10
+ if (!(0, verification_1.isVerificationReplacement)(input))
11
+ return undefined;
12
+ const prose = input.replace(/\x60[^\x60]+\x60/gu, ' ').trim();
13
+ const checks = (0, verification_1.locateRequestedChecks)(input);
14
+ if (checks.length !== 1)
15
+ return undefined;
16
+ const [check] = checks;
17
+ const workspace = contract.allowedScope.cwd;
18
+ const scoped = (0, path_1.relative)(workspace, (0, path_1.resolve)(workspace, check.cwd ?? '.'));
19
+ if (scoped === '..' || (0, path_1.isAbsolute)(scoped) || scoped.startsWith(`..${path_1.sep}`))
20
+ return undefined;
21
+ const verification = (contract.criteria ?? []).filter(criterion => (0, verification_1.requiredVerificationKinds)(criterion.statement).length > 0 &&
22
+ !(0, verification_1.criterionHasAuthorizedWaiver)(criterion));
23
+ if (verification.length !== 1 && !/\b(?:generic|unbound|unspecified)\b|通用|未指定/iu.test(prose))
24
+ return undefined;
25
+ const unbound = verification.filter(criterion => {
26
+ const kinds = (0, verification_1.requiredVerificationKinds)(criterion.statement);
27
+ return (kinds.length === 1 &&
28
+ kinds[0] === 'generic' &&
29
+ !(0, verification_1.requestedLocalChecks)(criterion.statement).length);
30
+ });
31
+ if (unbound.length !== 1)
32
+ return undefined;
33
+ const [criterion] = unbound;
34
+ const line = input
35
+ .slice(input.lastIndexOf('\n', check.start) + 1)
36
+ .split('\n', 1)[0]
37
+ .trim();
38
+ const statement = (0, verification_1.requiredVerificationKinds)(line).includes(check.kind)
39
+ ? line
40
+ : `Run \`${check.command}\` in \`${check.cwd ?? '.'}\` to verify the workflow.`;
41
+ const replace = (previous) => (previous === criterion.statement ? statement : previous);
42
+ return {
43
+ ...contract,
44
+ requirements: contract.requirements.map(replace),
45
+ successCriteria: contract.successCriteria.map(replace),
46
+ criteria: contract.criteria?.map(item => item.id === criterion.id ? { ...item, statement, evidenceRefs: [], status: 'pending' } : item),
47
+ };
48
+ }
7
49
  /** Only explicit user correction can supersede a required verification selector. */
8
50
  function goalVerificationCorrection(contract, input) {
9
51
  const prose = input.replace(/\x60[^\x60]+\x60/gu, ' ');
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.classifyIntent = classifyIntent;
4
4
  exports.shouldReplaceActiveInstruction = shouldReplaceActiveInstruction;
5
5
  const crypto_1 = require("crypto");
6
+ const clarification_1 = require("./clarification");
6
7
  const task_checklist_1 = require("./task-checklist");
7
8
  const MAX_SUMMARY = 220;
8
9
  function normalize(input) {
@@ -67,7 +68,7 @@ function extractQuestions(input) {
67
68
  .slice(0, 8);
68
69
  }
69
70
  function isGenericContinue(input) {
70
- return /^(继续|继续吧|继续开发|继续做|接着|接着做|go on|continue|keep going)$/i.test(input.trim());
71
+ return /^(?:继续|继续吧|继续开发|继续做|接着|接着做|go on|continue|keep going)[.!。!]?$/i.test(input.trim());
71
72
  }
72
73
  function isExplicitContinuation(input) {
73
74
  return /^(?:(?:please\s+)?(?:continue(?:\s+the)?|keep working on|refine)\b|(?:请\s*)?(?:继续|接着))/iu.test(input);
@@ -102,6 +103,13 @@ function classifyKind(input, state) {
102
103
  reason: 'short feedback should not replace the root objective',
103
104
  };
104
105
  }
106
+ if ((0, clarification_1.isReadOnlyQuestion)(input)) {
107
+ return {
108
+ kind: 'clarification',
109
+ confidence: 0.78,
110
+ reason: 'read-only explanation or status request',
111
+ };
112
+ }
105
113
  const change = (0, task_checklist_1.requestedWorkspaceChanges)(input);
106
114
  if ((change.checklistRequired || change.paths.length > 0) &&
107
115
  !isExplicitContinuation(text) &&
@@ -162,16 +170,6 @@ function classifyKind(input, state) {
162
170
  reason: 'explicit task creation wording',
163
171
  };
164
172
  }
165
- // Clarification: user is asking for explanation or asking about meaning
166
- // Must be checked BEFORE refinement since clarification phrases may contain "这个"
167
- if (matches(text, /(什么意思|解释一下|解释说明|clarify|explain to me|what does.*mean|what is.*for|can you explain|meaning of)/) ||
168
- matches(lower, /^(what|why|how|explain|clarify|could you explain|can you explain)\b/)) {
169
- return {
170
- kind: 'clarification',
171
- confidence: 0.7,
172
- reason: 'clarification or explanation request',
173
- };
174
- }
175
173
  if (matches(text, /(补充|另外|同时|还有|希望|可以|顺便|完善|优化|灰色|填充|这个|这里|如图|也|继续)/) ||
176
174
  matches(lower, /\b(also|additionally|please also|refine|improve|continue)\b/)) {
177
175
  return {
@@ -192,7 +190,7 @@ function classifyIntent(input, state) {
192
190
  const now = Date.now();
193
191
  const baseEpoch = state?.taskEpoch ?? (state?.contract ? 1 : 0);
194
192
  const classified = classifyKind(input, state);
195
- const rootObjectiveChanged = classified.kind === 'new_task' || !state?.contract;
193
+ const rootObjectiveChanged = classified.kind !== 'clarification' && (classified.kind === 'new_task' || !state?.contract);
196
194
  const taskEpoch = rootObjectiveChanged
197
195
  ? Math.max(1, baseEpoch + (state?.contract ? 1 : 0))
198
196
  : Math.max(1, baseEpoch || 1);
@@ -3,6 +3,9 @@ interface TranscriptMessage {
3
3
  role: string;
4
4
  content: string;
5
5
  }
6
+ /** Matches feedback inserted by older runtimes as a synthetic user message. */
7
+ export declare function isLegacyCompletionFeedback(message: TranscriptMessage): boolean;
8
+ export declare function withoutLegacyGoalGate(content: string): string | undefined;
6
9
  export declare function upgradeHarnessState(state?: Partial<HarnessState> | null, options?: {
7
10
  cwd?: string;
8
11
  messages?: TranscriptMessage[];
@@ -1,10 +1,27 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isLegacyCompletionFeedback = isLegacyCompletionFeedback;
4
+ exports.withoutLegacyGoalGate = withoutLegacyGoalGate;
3
5
  exports.upgradeHarnessState = upgradeHarnessState;
4
6
  exports.summarizeHarnessStateForMeta = summarizeHarnessStateForMeta;
5
7
  const capsule_1 = require("./capsule");
8
+ const clarification_1 = require("./clarification");
6
9
  const contract_1 = require("./contract");
7
10
  const evidence_1 = require("./evidence");
11
+ const intent_1 = require("./intent");
12
+ /** Matches feedback inserted by older runtimes as a synthetic user message. */
13
+ function isLegacyCompletionFeedback(message) {
14
+ return (message.role === 'user' &&
15
+ message.content.startsWith('[Harness Completion Gate]\nThe task is not ready to finish.\nMissing:\n- ') &&
16
+ message.content.endsWith('\nContinue working or explicitly explain why verification cannot be run.'));
17
+ }
18
+ const legacyGoalGate = '\nDo not claim completion unless the TaskContext completion gate verifies every criterion.';
19
+ function withoutLegacyGoalGate(content) {
20
+ if (content.startsWith('Continue the active Goal using saved state and receipts.\nObjective: ') &&
21
+ content.endsWith(legacyGoalGate)) {
22
+ return content.slice(0, -legacyGoalGate.length);
23
+ }
24
+ }
8
25
  function unique(items) {
9
26
  return [...new Set(items.map(item => item.trim()).filter(Boolean))];
10
27
  }
@@ -25,13 +42,19 @@ function firstRealUserMessage(messages) {
25
42
  }
26
43
  function upgradeHarnessState(state, options = {}) {
27
44
  const now = Date.now();
28
- const ledger = state?.ledger ?? [];
45
+ const ledger = (state?.ledger ?? []).filter(entry => entry.source.kind !== 'system' || entry.source.ref !== 'completion_gate');
29
46
  const diagnostics = [...(state?.diagnostics ?? [])].filter(message => message !==
30
47
  'latest transcript user message differs from active instruction; using stored active instruction' &&
31
48
  message !==
32
49
  'root objective does not exactly match the first transcript user message; preserving harness root objective');
33
- const firstUser = firstRealUserMessage(options.messages);
34
- const lastUser = latestRealUserMessage(options.messages);
50
+ const recordedUserInputs = new Set([
51
+ state?.activeInstruction,
52
+ state?.contract?.userIntent,
53
+ ...ledger.filter(entry => entry.source.kind === 'user').map(entry => entry.content),
54
+ ]);
55
+ const messages = options.messages?.filter(message => !isLegacyCompletionFeedback(message) || recordedUserInputs.has(message.content));
56
+ const firstUser = firstRealUserMessage(messages);
57
+ const lastUser = latestRealUserMessage(messages);
35
58
  const explicitObjective = firstUser ? (0, contract_1.extractExplicitObjective)(firstUser) : undefined;
36
59
  const storedContract = state?.contract
37
60
  ? {
@@ -47,8 +70,25 @@ function upgradeHarnessState(state, options = {}) {
47
70
  state?.rootObjective ??
48
71
  contract?.objective ??
49
72
  (firstUser ? firstUser.trim().replace(/\s+/g, ' ') : undefined);
50
- const activeInstruction = state?.activeInstruction ?? contract?.userIntent ?? lastUser ?? rootObjective;
51
- const turnSummaries = state?.turnSummaries ?? [];
73
+ const storedInstruction = state?.activeInstruction ?? contract?.userIntent ?? lastUser ?? rootObjective;
74
+ const intents = state?.intentHistory ?? [];
75
+ const matchingIntent = [...intents]
76
+ .reverse()
77
+ .find(intent => intent.taskEpoch === taskEpoch && intent.activeInstruction === storedInstruction);
78
+ const activeInstruction = (0, clarification_1.isReadOnlyQuestion)(matchingIntent?.input ?? storedInstruction ?? '')
79
+ ? ([...intents]
80
+ .reverse()
81
+ .find(intent => intent.taskEpoch === taskEpoch &&
82
+ (0, intent_1.shouldReplaceActiveInstruction)(intent) &&
83
+ !(0, clarification_1.isReadOnlyQuestion)(intent.input))?.activeInstruction ?? rootObjective)
84
+ : storedInstruction;
85
+ const turnSummaries = (state?.turnSummaries ?? []).map(summary => summary.assistantOutcome.startsWith('Completion gate stopped this turn: ')
86
+ ? {
87
+ ...summary,
88
+ assistantOutcome: 'The previous turn ended with incomplete verification.',
89
+ decisions: summary.decisions.filter(decision => decision !== summary.assistantOutcome),
90
+ }
91
+ : summary);
52
92
  const evidenceIndex = (0, evidence_1.buildEvidenceIndex)({
53
93
  ledger,
54
94
  turnSummaries,
@@ -59,6 +99,12 @@ function upgradeHarnessState(state, options = {}) {
59
99
  : contract || ledger.length > 0
60
100
  ? (0, capsule_1.createContextCapsule)(contract, ledger, state?.workspaceRevision)
61
101
  : undefined;
102
+ if (capsule?.verification) {
103
+ capsule.verification = {
104
+ ...capsule.verification,
105
+ warnings: capsule.verification.warnings.filter(warning => !warning.startsWith('Completion gate missing: ')),
106
+ };
107
+ }
62
108
  if (state && state.version !== 2) {
63
109
  diagnostics.push('upgraded legacy harness state to v2');
64
110
  }
@@ -97,7 +143,7 @@ function upgradeHarnessState(state, options = {}) {
97
143
  ...(state?.taskTodoReceipts ? { taskTodoReceipts: state.taskTodoReceipts } : {}),
98
144
  rootObjective,
99
145
  activeInstruction,
100
- intentHistory: state?.intentHistory ?? [],
146
+ intentHistory: intents,
101
147
  activeConstraints: unique([
102
148
  ...(state?.activeConstraints ?? []),
103
149
  ...(contract?.constraints ?? []),
@@ -1,6 +1,6 @@
1
1
  import type { TodoItem } from '../framework/tool-state';
2
2
  import type { TaskTodoItem } from './types';
3
- export declare const TASK_CHECKLIST_REQUIRED = "Create an execution checklist with todo_write before changing the workspace. Include the implementation work and a verification check. You can inspect files first.";
3
+ export declare const TASK_CHECKLIST_REQUIRED = "Consider using todo_write to track implementation paths and verification for this multi-step task.";
4
4
  export declare function supportsExecutionChecklist(mode: string): boolean;
5
5
  export declare const TASK_RECOVERY_STRATEGY_HISTORY_LIMIT = 4;
6
6
  /** Deferral is applied from explicit user input. Tool arguments cannot defer work. */
@@ -19,7 +19,7 @@ const fileExtension = /\.[a-z][a-z0-9]{0,7}$/iu;
19
19
  const referenceClause = /\s+(?:to (?:match|follow|use)|based on|according to|using|after reading|as (?:in|described in))\s+|(?:,|\s)*(?:参考|参照|依据|基于|对照|按照)/iu;
20
20
  const checkInstruction = /^(?:(?:verify|validate|check|review)\b|验收|验证|核对|检查|审阅)/iu;
21
21
  const sameFileScope = /^(?:(?:edit|modify|change|update)\s+(?:only\s+)?(?:this|that|the same)\s+file(?:\s+only)?|(?:只)?(?:修改|编辑|更新)(?:这个|该|同一)文件)[.,,。]?$/iu;
22
- exports.TASK_CHECKLIST_REQUIRED = 'Create an execution checklist with todo_write before changing the workspace. Include the implementation work and a verification check. You can inspect files first.';
22
+ exports.TASK_CHECKLIST_REQUIRED = 'Consider using todo_write to track implementation paths and verification for this multi-step task.';
23
23
  function supportsExecutionChecklist(mode) {
24
24
  return mode === 'build' || mode === 'auto' || mode === 'goal';
25
25
  }
@@ -49,7 +49,7 @@ function modificationClauses(instruction) {
49
49
  .replace(/^[ \t]*\x60{3}[^\r\n]*\r?\n[\s\S]*?^[ \t]*\x60{3}[^\r\n]*/gmu, '')
50
50
  .split(/\r?\n|[;;]|\b(?:and then|then|and(?=\s+(?:verify|test|run|check|implement|edit|update|modify|fix|refactor|create|write)\b))\b|然后|(?:再|并)(?=实现|修改|更新|修复|新增|添加|重构|删除|运行|验证|测试)/iu)
51
51
  .map(part => part.trim().replace(/^(?:[-*]|\d+[.、)])\s*/u, ''))
52
- .filter(part => writeInstruction.test(part));
52
+ .filter(part => writeInstruction.test(part) && !(0, verification_1.isVerificationReplacement)(part));
53
53
  }
54
54
  function pathsInActions(actions) {
55
55
  return [
@@ -289,6 +289,7 @@ export interface HarnessConfig {
289
289
  maxRecentTurns?: number;
290
290
  evidenceBudgetRatio?: number;
291
291
  driftGuard?: 'off' | 'warn' | 'block';
292
+ /** @deprecated Accepted for older callers. Completion evidence is advisory. */
292
293
  completionGate?: boolean | 'off' | 'warn' | 'block';
293
294
  }
294
295
  export interface DriftCheckResult {
@@ -8,6 +8,7 @@ export declare function requestedFileArtifact(statement: string): {
8
8
  export declare function workspaceArtifactPath(root: string, path: string): string | undefined;
9
9
  export declare function latestArtifactWrite(ledger: readonly ContextLedgerEntry[], contractId: string, cwd: string, path: string): ContextLedgerEntry | undefined;
10
10
  export declare function classifyVerificationCommand(command: string | undefined): VerificationKind;
11
+ export declare function isVerificationReplacement(statement: string): boolean;
11
12
  export declare function requiredVerificationKinds(statement: string): VerificationKind[];
12
13
  export interface RequestedCheck {
13
14
  readonly kind: VerificationCommandKind;
@@ -27,6 +28,7 @@ export declare function equalRequestedChecks(left: RequestedCheck, right: Reques
27
28
  /** Rewrite only the selected command and its own directory literal. */
28
29
  export declare function replaceRequestedCheck(statement: string, previous: RequestedCheck, next: RequestedCheck, workspace: string): string;
29
30
  export declare function matchesRequestedCheck(entry: ContextLedgerEntry, check: RequestedCheck, workspace: string): boolean;
31
+ export declare function matchesRequestedCheckInvocation(command: string, cwd: string | undefined, check: RequestedCheck, workspace: string): boolean;
30
32
  export declare function verificationKindForEntry(entry: ContextLedgerEntry, requireLocalReceipt?: boolean): VerificationKind;
31
33
  export declare function isTrustedEvidence(entry: ContextLedgerEntry): boolean;
32
34
  export declare function isFreshVerification(entry: ContextLedgerEntry, workspaceRevision?: number): boolean;
@@ -4,12 +4,14 @@ exports.requestedFileArtifact = requestedFileArtifact;
4
4
  exports.workspaceArtifactPath = workspaceArtifactPath;
5
5
  exports.latestArtifactWrite = latestArtifactWrite;
6
6
  exports.classifyVerificationCommand = classifyVerificationCommand;
7
+ exports.isVerificationReplacement = isVerificationReplacement;
7
8
  exports.requiredVerificationKinds = requiredVerificationKinds;
8
9
  exports.requestedLocalChecks = requestedLocalChecks;
9
10
  exports.locateRequestedChecks = locateRequestedChecks;
10
11
  exports.equalRequestedChecks = equalRequestedChecks;
11
12
  exports.replaceRequestedCheck = replaceRequestedCheck;
12
13
  exports.matchesRequestedCheck = matchesRequestedCheck;
14
+ exports.matchesRequestedCheckInvocation = matchesRequestedCheckInvocation;
13
15
  exports.verificationKindForEntry = verificationKindForEntry;
14
16
  exports.isTrustedEvidence = isTrustedEvidence;
15
17
  exports.isFreshVerification = isFreshVerification;
@@ -80,11 +82,13 @@ function uniqueKinds(kinds) {
80
82
  }
81
83
  function classifyVerificationCommand(command) {
82
84
  const normalized = command?.trim();
83
- if (!normalized || verification_command_1.SHELL_CONTROL_OPERATOR.test(normalized))
85
+ if (!normalized)
84
86
  return 'generic';
85
87
  const local = (0, verification_command_1.classifyDirectVerificationCommand)(normalized);
86
88
  if (local)
87
89
  return local;
90
+ if (verification_command_1.SHELL_CONTROL_OPERATOR.test(normalized))
91
+ return 'generic';
88
92
  if (/^(?:npm\s+publish|gh\s+release|git\s+tag)(?=\s|$)/u.test(normalized)) {
89
93
  return 'release';
90
94
  }
@@ -96,6 +100,11 @@ function classifyVerificationCommand(command) {
96
100
  }
97
101
  return 'generic';
98
102
  }
103
+ function isVerificationReplacement(statement) {
104
+ const prose = statement.replace(/\x60[^\x60]+\x60/gu, ' ').trim();
105
+ return (/^(?:please\s+)?(?:replace|change|switch)\s+(?:(?:the|previous|old|current|required|generic|unbound|unspecified|workflow)\s+)*(?:verification|check)\s+(?:with|to)\b/iu.test(prose) ||
106
+ /^(?:请\s*)?(?:(?:把|将)\s*)?(?:原来的?|之前的?|前面的?|当前的?|通用的?|未指定的?|工作流的?)*(?:验证|检查)\s*(?:改为|改成|换成|换为|替换为|指定为|绑定到)/u.test(prose));
107
+ }
99
108
  function requiredVerificationKinds(statement) {
100
109
  const normalized = statement.toLowerCase();
101
110
  const englishAction = /^(?:please\s+)?(?:run|execute|verify|validate|check|ensure)\b/u.test(normalized) ||
@@ -107,7 +116,7 @@ function requiredVerificationKinds(statement) {
107
116
  // do not add an obligation to pass a separate verification command.
108
117
  const chineseAction = /(?:必须|需要|要求|确保|请|(?<!可)(?:运行|执行)|通过|完成|成功).{0,60}(?:测试|验证|构建|编译|检查|发布|提交|推送|流水线)/u.test(statement) ||
109
118
  /(?:测试|验证|构建|编译|检查|发布|提交|推送|流水线).{0,60}(?:必须|需要|要求|确保|通过|成功|(?<!可)(?:运行|执行)|完成)/u.test(statement);
110
- if (!englishAction && !chineseAction)
119
+ if (!englishAction && !chineseAction && !isVerificationReplacement(statement))
111
120
  return [];
112
121
  const checks = requestedLocalChecks(statement);
113
122
  const prose = normalized.replace(/\x60[^\x60]+\x60/gu, '');
@@ -162,7 +171,7 @@ function locateRequestedChecks(statement) {
162
171
  for (const match of statement.matchAll(/\x60([^\x60\r\n]+)\x60/gu)) {
163
172
  const [span, literal] = match;
164
173
  const command = literal.trim();
165
- const kind = (0, verification_command_1.classifyDirectVerificationCommand)(command);
174
+ const kind = (0, verification_command_1.classifyVerificationSelector)(command);
166
175
  if (!kind)
167
176
  continue;
168
177
  const index = match.index ?? 0;
@@ -217,9 +226,12 @@ function replaceRequestedCheck(statement, previous, next, workspace) {
217
226
  function matchesRequestedCheck(entry, check, workspace) {
218
227
  const { command, cwd } = entry.metadata ?? {};
219
228
  return (typeof command === 'string' &&
220
- command.trim() === check.command &&
221
- (!check.cwd ||
222
- (0, path_1.resolve)(workspace, typeof cwd === 'string' ? cwd : '.') === (0, path_1.resolve)(workspace, check.cwd)));
229
+ matchesRequestedCheckInvocation(command, typeof cwd === 'string' ? cwd : undefined, check, workspace));
230
+ }
231
+ function matchesRequestedCheckInvocation(command, cwd, check, workspace) {
232
+ return (command.trim() === check.command &&
233
+ (check.kind !== 'generic' || cwd !== undefined) &&
234
+ (0, path_1.resolve)(workspace, cwd ?? '.') === (0, path_1.resolve)(workspace, check.cwd ?? '.'));
223
235
  }
224
236
  function verificationKindForEntry(entry, requireLocalReceipt = false) {
225
237
  const stored = entry.metadata?.verificationKind;
@@ -49,7 +49,8 @@ class AgentLoopV1 {
49
49
  ? (0, task_context_recovery_1.createTaskRecoveryBinder)(this.options.taskContext, this.options.previousCommitDigest, progressAtAdmission)
50
50
  : undefined;
51
51
  const goal = context.mode === 'goal' ? this.options.resolveGoalTask?.() : undefined;
52
- this.options.taskContext.observeUserInput(goal?.objective ?? context.input, goal?.goalId);
52
+ const intent = this.options.taskContext.observeUserInput(goal?.objective ?? context.input, goal?.goalId);
53
+ let answeringQuestion = (context.mode === 'build' || context.mode === 'auto') && intent?.kind === 'clarification';
53
54
  const messages = (await this.options.loadBaseMessages(context)).map(message => ({
54
55
  ...message,
55
56
  }));
@@ -124,7 +125,7 @@ class AgentLoopV1 {
124
125
  const executionChecklist = this.options.enableTaskTodos === true && (0, task_checklist_1.supportsExecutionChecklist)(context.mode);
125
126
  const harness = createQueryTaskContextAdapter(this.options.taskContext, decision => {
126
127
  taskContextCompletion = decision;
127
- }, context.mode === 'plan', executionChecklist, context.mode === 'goal');
128
+ }, executionChecklist, context.mode === 'goal', () => answeringQuestion);
128
129
  try {
129
130
  for await (const event of (0, query_1.query)({
130
131
  messages,
@@ -154,7 +155,7 @@ class AgentLoopV1 {
154
155
  activeStep = await this.bindStep(context, prepared, router, bindingInput);
155
156
  return {
156
157
  receiptDigest: activeStep.digest,
157
- toolExecutor: (name, args, abortSignal, metadata) => this.invokeTool(context, activeStep, name, args, bindRecovery, abortSignal, metadata),
158
+ toolExecutor: (name, args, abortSignal, metadata) => this.invokeTool(context, activeStep, name, args, answeringQuestion, bindRecovery, abortSignal, metadata),
158
159
  };
159
160
  },
160
161
  };
@@ -162,15 +163,6 @@ class AgentLoopV1 {
162
163
  llm: this.options.llm,
163
164
  abortSignal: context.abortSignal,
164
165
  streamCallbacks,
165
- holdAssistantUntilCompletionCheck: () => context.mode !== 'plan' &&
166
- (context.mode === 'goal' ||
167
- this.options.taskContext.requiresVerification() ||
168
- (executionChecklist &&
169
- (this.options.taskContext.hasTaskTodos() ||
170
- !!this.options.taskContext.missingExecutionChecklist()))),
171
- ...(executionChecklist
172
- ? { checkTaskPlanStop: this.options.taskContext.prepareTaskPlanStopCheck() }
173
- : {}),
174
166
  harness,
175
167
  input: context.input,
176
168
  toolContext: {
@@ -186,10 +178,13 @@ class AgentLoopV1 {
186
178
  const inputs = context.takePendingSteering?.(closeIfEmpty) ?? [];
187
179
  for (const input of inputs) {
188
180
  taskContextCompletion = undefined;
189
- if (goal)
181
+ if (goal) {
190
182
  this.options.taskContext.observeGoalSteering(input, goal.goalId);
191
- else
192
- this.options.taskContext.observeUserInput(input);
183
+ }
184
+ else {
185
+ const steering = this.options.taskContext.observeUserInput(input);
186
+ answeringQuestion && (answeringQuestion = steering?.kind === 'clarification');
187
+ }
193
188
  }
194
189
  return inputs;
195
190
  },
@@ -215,15 +210,6 @@ class AgentLoopV1 {
215
210
  break;
216
211
  }
217
212
  case 'complete':
218
- if (executionChecklist &&
219
- (event.stats?.finishReason === 'completion_gate' ||
220
- event.stats?.stopDecision?.reason.code === 'task_step_blocked')) {
221
- const item = context.startItem({ kind: 'message', role: 'system' });
222
- context.completeItem(item, {
223
- content: event.content,
224
- summary: compactSummary(event.content),
225
- });
226
- }
227
213
  completeEvent = event;
228
214
  break;
229
215
  case 'prompt_assembly':
@@ -322,22 +308,28 @@ class AgentLoopV1 {
322
308
  await this.options.onStepCaptured?.(snapshot);
323
309
  return snapshot;
324
310
  }
325
- async invokeTool(context, snapshot, name, args, bindRecovery, abortSignal, metadata) {
311
+ async invokeTool(context, snapshot, name, args, answeringQuestion, bindRecovery, abortSignal, metadata) {
326
312
  if (!metadata)
327
313
  throw new Error('ToolGateway execution requires provider call identity');
328
314
  const executionChecklist = this.options.enableTaskTodos === true && (0, task_checklist_1.supportsExecutionChecklist)(context.mode);
329
315
  const descriptor = snapshot.toolRouter.resolveDescriptor(name);
330
- const prerequisiteFailure = executionChecklist && mayChangeWorkspace(descriptor, args)
331
- ? this.options.taskContext.missingExecutionChecklist({
316
+ const workspaceWrite = mayChangeWorkspace(descriptor, args);
317
+ let prerequisiteFailure;
318
+ if (answeringQuestion &&
319
+ descriptor &&
320
+ !descriptor.risk.readOnly &&
321
+ (descriptor.name !== 'exec_command' || workspaceWrite)) {
322
+ prerequisiteFailure = 'Answer the current question without modifying the task or workspace.';
323
+ }
324
+ else if (executionChecklist && workspaceWrite) {
325
+ prerequisiteFailure = this.options.taskContext.deferredWorkspaceWriteReason({
332
326
  path: (name === 'write_file' || name === 'edit_file') && typeof args.path === 'string'
333
327
  ? args.path
334
328
  : undefined,
335
- command: name === 'exec_command' && typeof args.command === 'string'
336
- ? args.command
337
- : undefined,
329
+ command: name === 'exec_command' && typeof args.command === 'string' ? args.command : undefined,
338
330
  cwd: typeof args.cwd === 'string' ? args.cwd : undefined,
339
- })
340
- : undefined;
331
+ });
332
+ }
341
333
  const invocationId = deterministicRuntimeId([
342
334
  context.threadId,
343
335
  context.turnId,
@@ -349,7 +341,7 @@ class AgentLoopV1 {
349
341
  cwd: snapshot.environment.cwd,
350
342
  config: { name: 'orion-code', mode: context.mode },
351
343
  };
352
- const activeTodo = executionChecklist && name !== 'todo_write'
344
+ const activeTodo = executionChecklist && !answeringQuestion && name !== 'todo_write'
353
345
  ? this.options.taskContext.activeTaskTodo()
354
346
  : undefined;
355
347
  const invoked = await this.options.gateway.invoke({
@@ -360,13 +352,15 @@ class AgentLoopV1 {
360
352
  context: toolContext,
361
353
  abortSignal,
362
354
  prerequisiteFailure,
363
- taskRecovery: bindRecovery?.({
364
- descriptor,
365
- name,
366
- args,
367
- cwd: toolContext.cwd,
368
- activeTodoId: activeTodo,
369
- }),
355
+ taskRecovery: answeringQuestion
356
+ ? undefined
357
+ : bindRecovery?.({
358
+ descriptor,
359
+ name,
360
+ args,
361
+ cwd: toolContext.cwd,
362
+ activeTodoId: activeTodo,
363
+ }),
370
364
  });
371
365
  const receipt = invoked.receipt;
372
366
  const evidence = (0, task_context_recovery_1.projectTaskToolEvidence)(receipt, args, toolContext.cwd);
@@ -522,10 +516,14 @@ function createSnapshotToolFacade(descriptor) {
522
516
  isFileEdit: () => descriptor.risk.fileEdit,
523
517
  };
524
518
  }
525
- function createQueryTaskContextAdapter(taskContext, onCompletion, planningPhase, enforceTaskTodos, requireEveryCriterion) {
519
+ function createQueryTaskContextAdapter(taskContext, onCompletion, enforceTaskTodos, requireEveryCriterion, answeringQuestion) {
526
520
  return {
527
521
  updateCapabilityProfile: input => structuredClone(taskContext.observeCapability(input)),
528
- assembleMessages: (messages, options) => taskContext.assembleMessages(messages, { ...options, includeTaskTodos: enforceTaskTodos }),
522
+ assembleMessages: (messages, options) => taskContext.assembleMessages(messages, {
523
+ ...options,
524
+ includeTaskTodos: enforceTaskTodos,
525
+ answeringQuestion: answeringQuestion(),
526
+ }),
529
527
  getCapsule: () => {
530
528
  const capsule = taskContext.getCapsule();
531
529
  return capsule
@@ -541,16 +539,13 @@ function createQueryTaskContextAdapter(taskContext, onCompletion, planningPhase,
541
539
  taskContext.observeToolResult(input);
542
540
  },
543
541
  beforeComplete: () => {
544
- const decision = taskContext.auditCompletion(enforceTaskTodos, requireEveryCriterion);
542
+ if (answeringQuestion())
543
+ return { canComplete: true, missing: [], evidence: [] };
544
+ // Goal verification is based on its criteria. The checklist tracks model progress.
545
+ const decision = taskContext.auditCompletion(enforceTaskTodos && !requireEveryCriterion, requireEveryCriterion);
545
546
  onCompletion(decision);
546
- // PLAN completes a planning phase, not the parent implementation task.
547
- // Persist the unmodified audit for the PlanReceipt, while allowing the
548
- // query to stop after its decision-complete plan. BUILD/AUTO will enforce
549
- // the same TaskContext criteria in the following logical turn.
550
- const queryDecision = planningPhase ? { ...decision, canComplete: true } : decision;
551
- return structuredClone(queryDecision);
547
+ return structuredClone(decision);
552
548
  },
553
- asCompletionBlockedMessage: result => taskContext.completionBlockedMessage(result),
554
549
  };
555
550
  }
556
551
  function compactSummary(content) {
@@ -956,7 +956,7 @@ class AgentRuntimeController {
956
956
  else if (completedPlan) {
957
957
  nextRequest = {
958
958
  inputKind: 'plan_execution',
959
- text: `Execute the saved plan now. Continue autonomously from the plan and verify the result.\n\n${completedPlan}`,
959
+ text: `Execute the saved plan now. Continue autonomously and follow the plan's verification steps.\n\n${completedPlan}`,
960
960
  sessionId: this.options.runtime.getSession()?.id ?? request.sessionId,
961
961
  persistAsUserMessage: false,
962
962
  echoToTranscript: false,
@@ -152,6 +152,11 @@ class GoalLifecycleServiceV2 {
152
152
  resources: resourceSnapshot,
153
153
  });
154
154
  }
155
+ else if (observation.requestDecision?.status === 'completed' &&
156
+ observation.taskContextCompletion) {
157
+ status = 'paused';
158
+ decision = goalDecision('stopped', 'pause_scope', 'goal_verification_pending', 'The model ended the turn. Goal verification is still pending.', resourceSnapshot);
159
+ }
155
160
  else if (observation.continuationMode === 'manual') {
156
161
  status = 'paused';
157
162
  decision = goalDecision('stopped', 'pause_scope', 'goal_manual_continuation', 'Goal checkpoint saved. Manual continuation is enabled; use /goal resume for the next turn.', resourceSnapshot);
@@ -260,7 +260,11 @@ class GoalRuntimeCoordinatorV2 {
260
260
  });
261
261
  const observation = this.observeTurn(turn, requestDecision);
262
262
  const resolution = candidate.finalizeTurn(observation);
263
- const stopDecision = resolution.decision ?? requestDecision;
263
+ // The Goal keeps its own resumable state. Its open criteria do not turn
264
+ // the model's normal reply into a refused request.
265
+ const stopDecision = resolution.decision?.reason.code === 'goal_verification_pending'
266
+ ? requestDecision
267
+ : (resolution.decision ?? requestDecision);
264
268
  const receipt = persist({
265
269
  goalState: resolution.state,
266
270
  ...(stopDecision ? { stopDecision } : {}),
@@ -609,7 +613,7 @@ function defaultContinuationInput(state) {
609
613
  'Continue the active Goal using saved state and receipts.',
610
614
  `Objective: ${objective}`,
611
615
  'Use the current TaskContext verification requirements when the user has corrected a check.',
612
- 'Do not claim completion unless the TaskContext completion gate verifies every criterion.',
616
+ 'Report which checks passed and which remain unverified. End the turn when you have an answer for the user.',
613
617
  ].join('\n');
614
618
  }
615
619
  function deepFreeze(value) {
@@ -4,6 +4,7 @@ exports.OrionRuntimeV1 = exports.OrionRuntimeV1Error = void 0;
4
4
  exports.createOrionRuntimeV1 = createOrionRuntimeV1;
5
5
  const fs_1 = require("fs");
6
6
  const path_1 = require("path");
7
+ const state_1 = require("../harness/state");
7
8
  const paths_1 = require("../product/paths");
8
9
  const task_checklist_1 = require("../harness/task-checklist");
9
10
  const file_lock_1 = require("../services/file-lock");
@@ -541,12 +542,15 @@ class OrionRuntimeV1 {
541
542
  previousCommitDigest: () => latestTurnCommitProjection(eventStore)?.digest,
542
543
  enableTaskTodos: this.options.enableTaskTodos,
543
544
  resolveGoalTask: () => goal.state,
544
- loadBaseMessages: context => loadRuntimeBaseMessages(compactPersistence, this.options.loadBaseMessages?.(eventStore, context, prompts, {
545
- taskContext,
546
- goal,
547
- skills,
548
- mcp,
549
- })),
545
+ loadBaseMessages: async (context) => {
546
+ const history = await loadRuntimeBaseMessages(compactPersistence, this.options.loadBaseMessages?.(eventStore, context, prompts, {
547
+ taskContext,
548
+ goal,
549
+ skills,
550
+ mcp,
551
+ }));
552
+ return restoreLegacyHarnessHistory(history, eventStore);
553
+ },
550
554
  toolContext: () => this.options.toolContext,
551
555
  streamCallbacks: this.options.loop?.streamCallbacks,
552
556
  get loopBudget() {
@@ -1050,6 +1054,29 @@ function parseModelVisibleHistory(history) {
1050
1054
  }
1051
1055
  return history.map(message => ({ ...message }));
1052
1056
  }
1057
+ function restoreLegacyHarnessHistory(history, store) {
1058
+ if (!history.some(message => message.role === 'user' &&
1059
+ ((0, state_1.isLegacyCompletionFeedback)(message) ||
1060
+ (0, state_1.withoutLegacyGoalGate)(message.content) !== undefined)))
1061
+ return history;
1062
+ const projection = store.loadProjection();
1063
+ const recordedInputs = new Set(Object.values(projection.items)
1064
+ .filter(item => item.role === 'user')
1065
+ .map(item => item.content));
1066
+ if (!recordedInputs.size)
1067
+ return history;
1068
+ const goalInputs = new Set(Object.values(projection.turns)
1069
+ .filter(turn => turn.mode === 'goal')
1070
+ .map(turn => turn.input));
1071
+ return history.flatMap(message => {
1072
+ if ((0, state_1.isLegacyCompletionFeedback)(message) && !recordedInputs.has(message.content))
1073
+ return [];
1074
+ const repaired = message.role === 'user' && goalInputs.has(message.content)
1075
+ ? (0, state_1.withoutLegacyGoalGate)(message.content)
1076
+ : undefined;
1077
+ return [repaired ? { ...message, content: repaired } : message];
1078
+ });
1079
+ }
1053
1080
  function isMessage(value) {
1054
1081
  if (!value || typeof value !== 'object')
1055
1082
  return false;