@orion-agents/orion-code 0.4.5 → 0.4.7

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 (64) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +7 -7
  3. package/README.zh-CN.md +7 -7
  4. package/dist/commands/context-commands.js +16 -28
  5. package/dist/commands/context-tool-command-handlers.d.ts +2 -3
  6. package/dist/commands/context-tool-command-handlers.js +2 -20
  7. package/dist/commands/registry.js +24 -61
  8. package/dist/commands/retired-commands.d.ts +2 -0
  9. package/dist/commands/retired-commands.js +24 -0
  10. package/dist/commands/session-command-handlers.d.ts +3 -2
  11. package/dist/commands/session-command-handlers.js +41 -42
  12. package/dist/commands/session-commands.js +21 -0
  13. package/dist/commands/system-commands.js +2 -27
  14. package/dist/commands/tool-commands.js +0 -10
  15. package/dist/commands/types.d.ts +6 -4
  16. package/dist/commands/workflow-commands.js +0 -24
  17. package/dist/framework/query.js +1 -1
  18. package/dist/framework/verification-command.d.ts +2 -0
  19. package/dist/framework/verification-command.js +16 -4
  20. package/dist/harness/assembler.d.ts +1 -0
  21. package/dist/harness/assembler.js +5 -2
  22. package/dist/harness/clarification.d.ts +3 -0
  23. package/dist/harness/clarification.js +56 -0
  24. package/dist/harness/context-harness.d.ts +1 -1
  25. package/dist/harness/context-harness.js +33 -5
  26. package/dist/harness/contract.js +36 -10
  27. package/dist/harness/drift-guard.js +12 -4
  28. package/dist/harness/goal-verification.d.ts +2 -0
  29. package/dist/harness/goal-verification.js +42 -0
  30. package/dist/harness/intent.js +10 -12
  31. package/dist/harness/state.js +15 -2
  32. package/dist/harness/stop-controller.js +1 -1
  33. package/dist/harness/task-checklist.js +1 -1
  34. package/dist/harness/verification.d.ts +2 -0
  35. package/dist/harness/verification.js +16 -5
  36. package/dist/runtime/agent-loop.js +49 -27
  37. package/dist/runtime/agent-runtime-controller.d.ts +4 -2
  38. package/dist/runtime/agent-runtime-controller.js +116 -31
  39. package/dist/runtime/orion-session-runner.js +3 -5
  40. package/dist/runtime/plan-review.d.ts +1 -0
  41. package/dist/runtime/plan-review.js +12 -7
  42. package/dist/runtime/product-bootstrap.js +24 -11
  43. package/dist/runtime/product-orion-runtime.js +1 -1
  44. package/dist/runtime/step-snapshot.d.ts +1 -0
  45. package/dist/runtime/step-snapshot.js +2 -1
  46. package/dist/runtime/task-context-recovery.js +15 -7
  47. package/dist/runtime/tool-gateway.js +1 -0
  48. package/dist/runtime/ui-events.d.ts +4 -1
  49. package/dist/runtime/ui-view-model.js +7 -3
  50. package/dist/skills/builtin/security-check/SKILL.md +2 -2
  51. package/dist/skills/builtin/test-gen/SKILL.md +2 -2
  52. package/dist/terminal-ui/launch.js +1 -1
  53. package/dist/tui-ui/launch.js +4 -1
  54. package/dist/tui-ui/layout.d.ts +2 -2
  55. package/dist/tui-ui/layout.js +59 -47
  56. package/dist/tui-ui/pickers.d.ts +3 -1
  57. package/dist/tui-ui/pickers.js +17 -11
  58. package/dist/tui-ui/runner.d.ts +1 -1
  59. package/dist/tui-ui/runner.js +61 -68
  60. package/dist/tui-ui/state.d.ts +4 -0
  61. package/dist/tui-ui/state.js +33 -2
  62. package/docs/cli-guide.md +24 -1
  63. package/npm-shrinkwrap.json +2 -2
  64. package/package.json +1 -1
@@ -25,15 +25,5 @@ exports.TOOL_COMMANDS = [
25
25
  risk: 'read-only',
26
26
  execute: ctx => (0, context_tool_command_handlers_1.handleMcp)(ctx),
27
27
  },
28
- {
29
- name: 'safety',
30
- description: 'Show safety checker status and audit summary',
31
- category: 'tools',
32
- priority: 30,
33
- type: 'builtin',
34
- execution: 'builtin',
35
- risk: 'read-only',
36
- execute: () => (0, context_tool_command_handlers_1.showSafety)(),
37
- },
38
28
  ];
39
29
  //# sourceMappingURL=tool-commands.js.map
@@ -4,7 +4,7 @@
4
4
  * 使用 `/` 前缀的命令系统,支持 Tab 补全、命令建议、参数定义。
5
5
  * 非 `/` 前缀的输入直接作为 chat 消息处理。
6
6
  */
7
- import type { Store } from '../framework/store';
7
+ import type { AppState, Store } from '../framework/store';
8
8
  import type { LLMService } from '../services/llm';
9
9
  import type { OrionCodeCLIConfig, UIRenderer } from '../services/config';
10
10
  import type { SessionMeta } from '../services/session-storage';
@@ -32,9 +32,13 @@ export interface CommandContext {
32
32
  sessionId?: string;
33
33
  /** Lazily create or return the active session. */
34
34
  ensureSession?: () => SessionMeta;
35
+ /** Start an independent durable session and activate its runtime. */
36
+ startNewSession?: () => Promise<SessionMeta>;
35
37
  /** Switch the active session after /resume. */
36
38
  setSession?: (session: SessionMeta) => void;
37
- /** Rebind the product runtime and replay the selected durable Thread after /resume. */
39
+ /** Activate a verified Session/Thread and its read-side projection as one transition. */
40
+ activateSessionRuntime?: (session: SessionMeta, activation: ThreadSessionRuntimeActivationV1 | undefined, projection: Pick<AppState, 'conversationHistory' | 'harnessState'>) => Promise<void>;
41
+ /** Rebind an external runtime after selecting a Session. */
38
42
  restoreSessionRuntime?: (activation?: ThreadSessionRuntimeActivationV1) => Promise<void>;
39
43
  /** Notify renderer-independent runtime protocol consumers after /resume. */
40
44
  sessionRestored?: (event: RuntimeSessionRestoredEvent) => void;
@@ -52,8 +56,6 @@ export interface CommandContext {
52
56
  writeOutput?: (text: string) => void;
53
57
  /** Write one line while preserving the live input frame, when supported by the UI. */
54
58
  writeLine?: (text?: string) => void;
55
- /** Ask the active renderer to clear its viewport without deleting session data. */
56
- clearView?: () => void;
57
59
  /** Ask the active renderer to begin graceful shutdown. */
58
60
  requestShutdown?: (reason?: string) => void;
59
61
  /** Active renderer adapter identity, including non-config renderers such as print mode. */
@@ -74,30 +74,6 @@ exports.WORKFLOW_COMMANDS = [
74
74
  risk: 'read-only',
75
75
  execute: (_ctx, args) => (0, workflow_command_handlers_1.continueAsSlashChat)('research', args),
76
76
  },
77
- {
78
- name: 'security',
79
- aliases: ['audit'],
80
- description: 'Review code or dependencies for security risks',
81
- argumentHint: '[scope]',
82
- category: 'workflow',
83
- priority: 20,
84
- type: 'chat',
85
- execution: 'agent-workflow',
86
- risk: 'read-only',
87
- execute: (_ctx, args) => (0, workflow_command_handlers_1.continueAsSlashChat)('security', args),
88
- },
89
- {
90
- name: 'test-gen',
91
- aliases: ['tests'],
92
- description: 'Generate or improve tests for a target area',
93
- argumentHint: '[scope]',
94
- category: 'workflow',
95
- priority: 30,
96
- type: 'chat',
97
- execution: 'agent-workflow',
98
- risk: 'state-write',
99
- execute: (_ctx, args) => (0, workflow_command_handlers_1.continueAsSlashChat)('test-gen', args),
100
- },
101
77
  {
102
78
  name: 'todos',
103
79
  aliases: ['todo'],
@@ -863,7 +863,7 @@ async function* query(params) {
863
863
  status: planStop.code === 'task_step_blocked' ? 'blocked' : 'stopped',
864
864
  reason: { code: planStop.code, message: planStop.message },
865
865
  nextActions: [
866
- { kind: 'inspect', label: 'Inspect the current checklist', command: '/harness explain' },
866
+ { kind: 'inspect', label: 'Inspect the current checklist', command: '/context explain' },
867
867
  { kind: 'continue', label: 'Continue the current task', command: '继续' },
868
868
  ],
869
869
  };
@@ -12,4 +12,6 @@ export interface LocalVerificationReceipt {
12
12
  export declare function isLocalVerificationKind(value: unknown): value is LocalVerificationKind;
13
13
  export declare const SHELL_CONTROL_OPERATOR: RegExp;
14
14
  export declare function classifyDirectVerificationCommand(command: string): VerificationCommandKind | undefined;
15
+ /** Support an explicitly requested script without treating arbitrary script runs as checks. */
16
+ export declare function classifyVerificationSelector(command: string): VerificationCommandKind | undefined;
15
17
  //# sourceMappingURL=verification-command.d.ts.map
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SHELL_CONTROL_OPERATOR = exports.LOCAL_VERIFICATION_KINDS = void 0;
4
4
  exports.isLocalVerificationKind = isLocalVerificationKind;
5
5
  exports.classifyDirectVerificationCommand = classifyDirectVerificationCommand;
6
+ exports.classifyVerificationSelector = classifyVerificationSelector;
6
7
  exports.LOCAL_VERIFICATION_KINDS = ['test', 'build', 'lint', 'typecheck', 'diff'];
7
8
  function isLocalVerificationKind(value) {
8
9
  return exports.LOCAL_VERIFICATION_KINDS.some(kind => kind === value);
@@ -19,14 +20,25 @@ const directChecks = {
19
20
  const nonCheckingOption = /(?:^|[\s'"])(?:-h|--help|--version|--listTests|--listFilesOnly|--showConfig|--collect-only|--dry-run|--no-run|--passWithNoTests|--pass-with-no-tests|--if-present|-list)(?=[\s'"=]|$)/u;
20
21
  const nonCheckingInvocation = /^(?:npx\s+)?(?:vitest\s+list|tsc\s+(?:-v|--init))(?=\s|$)/u;
21
22
  const fileAssertion = /^test\s+-(?:e|f|d|s)\s+(?:"[^"]+"|'[^']+'|[^\s'"<>]+)$/u;
23
+ const customCheck = /^(?:(?:python3?|node)\s+(?:"[^"]+\.(?:py|[cm]?js)"|'[^']+\.(?:py|[cm]?js)'|[^\s'"<>]+\.(?:py|[cm]?js))|\.\/[^\s'"<>]+|(?:npm|pnpm|yarn|bun)\s+run\s+[\w:.-]+)(?=\s|$)/u;
24
+ function isCheckingInvocation(command) {
25
+ return (!exports.SHELL_CONTROL_OPERATOR.test(command) &&
26
+ !nonCheckingOption.test(command) &&
27
+ !nonCheckingInvocation.test(command));
28
+ }
22
29
  function classifyDirectVerificationCommand(command) {
23
30
  const normalized = command.trim();
24
- if (exports.SHELL_CONTROL_OPERATOR.test(normalized) ||
25
- nonCheckingOption.test(normalized) ||
26
- nonCheckingInvocation.test(normalized)) {
31
+ if (!isCheckingInvocation(normalized))
27
32
  return undefined;
28
- }
29
33
  return (exports.LOCAL_VERIFICATION_KINDS.find(kind => directChecks[kind].test(normalized)) ??
30
34
  (fileAssertion.test(normalized) ? 'generic' : undefined));
31
35
  }
36
+ /** Support an explicitly requested script without treating arbitrary script runs as checks. */
37
+ function classifyVerificationSelector(command) {
38
+ const normalized = command.trim();
39
+ return (classifyDirectVerificationCommand(normalized) ??
40
+ (isCheckingInvocation(normalized) && !/[<>]/u.test(normalized) && customCheck.test(normalized)
41
+ ? 'generic'
42
+ : undefined));
43
+ }
32
44
  //# sourceMappingURL=verification-command.js.map
@@ -7,6 +7,7 @@ export interface PromptAssemblyOptions {
7
7
  description?: string;
8
8
  }>;
9
9
  includeTaskTodos?: boolean;
10
+ answeringQuestion?: boolean;
10
11
  }
11
12
  export interface HarnessContextBuildResult {
12
13
  text: string;
@@ -77,7 +77,8 @@ function buildHarnessContext(state, modelId, config = {}, options = {}) {
77
77
  state.ledger.length === 0 &&
78
78
  !state.capsule &&
79
79
  !state.rootObjective &&
80
- !state.capabilityProfile) {
80
+ !state.capabilityProfile &&
81
+ !options.answeringQuestion) {
81
82
  const emptyStats = {
82
83
  createdAt: Date.now(),
83
84
  modelId,
@@ -161,7 +162,9 @@ function buildHarnessContext(state, modelId, config = {}, options = {}) {
161
162
  if (tools.length > 0) {
162
163
  pushList(coreLines, 'Relevant available tools', tools, 8);
163
164
  }
164
- const finalInstruction = 'Instruction: preserve the root objective across short feedback or refinements. Do not claim verification unless it is listed above or produced by a tool result in this turn.';
165
+ const finalInstruction = options.answeringQuestion
166
+ ? 'Answer the latest question using the task and verification context. Leave execution and checklist changes for a request to continue the work.'
167
+ : 'Instruction: preserve the root objective across short feedback or refinements. Do not claim verification unless it is listed above or produced by a tool result in this turn.';
165
168
  const coreText = coreLines.join('\n');
166
169
  const coreTokens = (0, evidence_1.estimateTokens)(coreText);
167
170
  const instructionTokens = (0, evidence_1.estimateTokens)(finalInstruction);
@@ -0,0 +1,3 @@
1
+ /** Identify a question about work without treating quoted or described work as an instruction. */
2
+ export declare function isReadOnlyQuestion(input: string): boolean;
3
+ //# sourceMappingURL=clarification.d.ts.map
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isReadOnlyQuestion = isReadOnlyQuestion;
4
+ const englishRequestPrefix = /^(?:(?:please|first|then|also|just)\s+|(?:can|could|would|will)\s+you\s+|i (?:want|would like) you to\s+)+/iu;
5
+ const chineseRequestPrefix = /^(?:(?:请|麻烦你|帮我|先|再|然后|同时)\s*)+/u;
6
+ const englishQuestion = /^(?:what|why|how|who|when|where|which)\b/iu;
7
+ const chineseQuestion = /^(?:为什么|为何|谁|怎么|如何|哪些|哪个)/u;
8
+ const embeddedQuestion = /^(?:explain|clarify|describe)(?:\s+to me)?\s+(?:what|why|how|when|where)\s+(?:i|we|you|they)\s+(?:can|could|should|must|may|would|do)\b|^(?:解释|说明)(?:一下)?\s*(?:怎么|如何|(?:为什么|为何)(?:要|需要|必须|应该|得))/iu;
9
+ const englishExplanation = /^(?:explain|clarify|describe)\b|^(?:tell me|show me)\s+(?:what|why|how|who|when|where|which)\b/iu;
10
+ const chineseExplanation = /(?:什么意思|解释(?:一下|说明)?|说明一下|能否说明)/u;
11
+ const englishStatus = /^(?:report|show(?: me)?|tell me|summarize)\s+(?:the\s+)?(?:current\s+)?(?:context(?:\s+(?:usage|size|window))?\b|(?:task|goal|session|test|build)\s+status\b|status\b|progress\b)/iu;
12
+ const chineseStatus = /^(?:(?:请|帮我|报告|汇报|查看|告诉我|展示|说一下|列出|总结)(?:一下)?\s*)*(?:当前|现在|目前)?(?:的)?\s*(?:上下文|会话|任务|目标|测试|构建|验证|进度)(?:[^??。\r\n]{0,28})(?:多少|剩余|用量|占用|状态|进度|报告一下|汇报一下|怎么样|结果)/u;
13
+ const englishExecution = /^(?:run|rerun|execute|verify|validate|check|test|build|compile|lint|typecheck|fix|implement|add|adjust|apply|edit|update|modify|change|write|create|delete|remove|replace|rename|refactor|continue|resume|retry|start|commit|merge|push|publish|deploy)\b|^(?:(?:the\s+)?(?:tests?|build|lint|ci)\b.{0,44}\b(?:must|should|needs? to|required to)\b)/iu;
14
+ const chineseExecution = /^(?:执行|运行|重新运行|跑(?:一下|测试|检查|验证|\s*(?:npm|pnpm|yarn|pytest))|重跑|验证|测试|检查|构建|编译|修复|实现|修改|更新|调整|添加|新增|删除|替换|改用|换成|改为|创建|写入|重构|提交|合并|推送|发布|部署|继续|接着|恢复|重试)|^(?:把|将).{1,100}(?:改为|换成|替换|修改|重跑|执行|运行|改成)|^(?:测试|构建|验证|检查).{0,24}(?:必须|需要|务必)(?:通过|成功)/u;
15
+ const actionConjunction = /\b(?:and then|then|and|also)\b\s*|,\s*(?=please\b|just\b)|(?:然后|并且|同时|另外|再|并)/iu;
16
+ const explicitActionConjunction = /\b(?:and then|then|and|also)\b\s+(?=please\b|(?:can|could|would|will)\s+you\b)|,\s*(?:and then|then|also)\b\s+|(?:然后|并且|同时|另外|再|并)(?=\s*(?:请|帮我|麻烦你))/iu;
17
+ function stripRequestPrefix(text) {
18
+ return text.trim().replace(englishRequestPrefix, '').replace(chineseRequestPrefix, '');
19
+ }
20
+ function requestsExecution(text) {
21
+ const action = stripRequestPrefix(text);
22
+ return englishExecution.test(action) || chineseExecution.test(action);
23
+ }
24
+ /** Identify a question about work without treating quoted or described work as an instruction. */
25
+ function isReadOnlyQuestion(input) {
26
+ const prose = input
27
+ .replace(/^[ \t]*\x60{3}[^\r\n]*\r?\n[\s\S]*?^[ \t]*\x60{3}[^\r\n]*/gmu, ' ')
28
+ .replace(/\x60[^\x60\r\n]+\x60|“[^”\r\n]+”|「[^」\r\n]+」|‘[^’\r\n]+’|"[^"\r\n]+"|(?<![\p{L}\p{N}])'[^'\r\n]+'(?![\p{L}\p{N}])/gu, ' reference ');
29
+ const clauses = prose
30
+ .split(/[!??!。;;\r\n]+|\.(?=\s|$)/u)
31
+ .map(clause => clause.trim().replace(/^(?:[-*+]|\d+[.)、])\s+/u, ''))
32
+ .filter(Boolean);
33
+ let sawQuestion = false;
34
+ for (const clause of clauses) {
35
+ const request = stripRequestPrefix(clause);
36
+ const directQuestion = englishQuestion.test(request) || chineseQuestion.test(request);
37
+ const question = directQuestion ||
38
+ englishExplanation.test(request) ||
39
+ chineseExplanation.test(request) ||
40
+ englishStatus.test(request) ||
41
+ chineseStatus.test(clause);
42
+ if (requestsExecution(clause))
43
+ return false;
44
+ // A list of verbs inside "why do we build and test?" describes what the
45
+ // user is asking about. Instructions after a sentence boundary, or with
46
+ // an explicit request marker, can still ask the agent to act.
47
+ const conjunction = directQuestion || embeddedQuestion.test(request)
48
+ ? explicitActionConjunction
49
+ : actionConjunction;
50
+ if (clause.split(conjunction).slice(1).some(requestsExecution))
51
+ return false;
52
+ sawQuestion || (sawQuestion = question);
53
+ }
54
+ return sawQuestion;
55
+ }
56
+ //# sourceMappingURL=clarification.js.map
@@ -100,7 +100,7 @@ export declare class HarnessKernel {
100
100
  getContract(): HarnessState['contract'];
101
101
  getIntentHistory(): IntentUpdate[];
102
102
  /**
103
- * Generate a structured diagnostic summary for /harness explain
103
+ * Generate a structured diagnostic summary for /context explain
104
104
  */
105
105
  explain(): {
106
106
  contract: HarnessState['contract'];
@@ -12,6 +12,7 @@ const verification_command_1 = require("../framework/verification-command");
12
12
  const assembler_1 = require("./assembler");
13
13
  const capability_profile_1 = require("./capability-profile");
14
14
  const capsule_1 = require("./capsule");
15
+ const clarification_1 = require("./clarification");
15
16
  const contract_1 = require("./contract");
16
17
  const drift_guard_1 = require("./drift-guard");
17
18
  const evidence_1 = require("./evidence");
@@ -89,6 +90,12 @@ class HarnessKernel {
89
90
  return;
90
91
  if (goalTaskId && this.goalTaskId === goalTaskId && this.contract)
91
92
  return;
93
+ const classified = (0, intent_1.classifyIntent)(input, this.toJSON());
94
+ if (!goalTaskId && classified.kind === 'clarification') {
95
+ this.intentHistory = [...this.intentHistory, classified].slice(-40);
96
+ this.touch();
97
+ return classified;
98
+ }
92
99
  const deferral = (0, task_checklist_1.requestedTaskDeferral)(input);
93
100
  if (deferral &&
94
101
  this.goalTaskId === goalTaskId &&
@@ -96,7 +103,6 @@ class HarnessKernel {
96
103
  this.deferTaskTodos(deferral);
97
104
  return;
98
105
  }
99
- const classified = (0, intent_1.classifyIntent)(input, this.toJSON());
100
106
  const ownerChanged = this.goalTaskId !== goalTaskId;
101
107
  const intent = ownerChanged
102
108
  ? {
@@ -160,8 +166,25 @@ class HarnessKernel {
160
166
  }
161
167
  observeGoalSteering(input, goalId) {
162
168
  const contract = this.contract;
163
- if (!contract || this.goalTaskId !== goalId || this.config.enabled === false)
169
+ if (!contract ||
170
+ this.goalTaskId !== goalId ||
171
+ this.config.enabled === false ||
172
+ (0, clarification_1.isReadOnlyQuestion)(input))
173
+ return;
174
+ const bound = (0, goal_verification_1.bindUnspecifiedVerification)(contract, input);
175
+ if (bound) {
176
+ this.ledger.recordUserRequirement(input);
177
+ this.contract = {
178
+ ...bound,
179
+ userIntent: input.trim(),
180
+ updatedAt: Math.max(Date.now(), contract.updatedAt + 1),
181
+ };
182
+ this.activeInstruction = input.trim();
183
+ this.goalVerificationBlocker = undefined;
184
+ this.refreshCapsule();
185
+ this.touch();
164
186
  return;
187
+ }
165
188
  const correction = (0, goal_verification_1.goalVerificationCorrection)(contract, input);
166
189
  if (!correction)
167
190
  return;
@@ -872,7 +895,7 @@ class HarnessKernel {
872
895
  return this.intentHistory;
873
896
  }
874
897
  /**
875
- * Generate a structured diagnostic summary for /harness explain
898
+ * Generate a structured diagnostic summary for /context explain
876
899
  */
877
900
  explain() {
878
901
  this.refreshEvidenceIndex();
@@ -980,14 +1003,19 @@ class HarnessKernel {
980
1003
  if (!this.contract?.criteria || !(0, verification_1.isTrustedEvidence)(entry))
981
1004
  return;
982
1005
  const kind = (0, verification_1.verificationKindForEntry)(entry, this.requireLocalVerificationReceipt);
983
- if (kind === 'generic' && entry.type !== 'verification')
1006
+ if (kind === 'generic' &&
1007
+ (entry.type !== 'verification' ||
1008
+ (this.requireLocalVerificationReceipt &&
1009
+ typeof entry.metadata?.toolReceiptDigest !== 'string'))) {
984
1010
  return;
1011
+ }
985
1012
  const workspace = this.contract.allowedScope.cwd;
986
1013
  for (const criterion of this.contract.criteria) {
987
1014
  if (!(0, verification_1.requiredVerificationKinds)(criterion.statement).includes(kind))
988
1015
  continue;
989
1016
  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)))
1017
+ if ((kind === 'generic' || checks.length) &&
1018
+ !checks.some(check => (0, verification_1.matchesRequestedCheck)(entry, check, workspace)))
991
1019
  continue;
992
1020
  this.updateCriterionEvidence(criterion.id, entry.id);
993
1021
  }
@@ -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
@@ -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,8 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.upgradeHarnessState = upgradeHarnessState;
4
4
  exports.summarizeHarnessStateForMeta = summarizeHarnessStateForMeta;
5
5
  const capsule_1 = require("./capsule");
6
+ const clarification_1 = require("./clarification");
6
7
  const contract_1 = require("./contract");
7
8
  const evidence_1 = require("./evidence");
9
+ const intent_1 = require("./intent");
8
10
  function unique(items) {
9
11
  return [...new Set(items.map(item => item.trim()).filter(Boolean))];
10
12
  }
@@ -47,7 +49,18 @@ function upgradeHarnessState(state, options = {}) {
47
49
  state?.rootObjective ??
48
50
  contract?.objective ??
49
51
  (firstUser ? firstUser.trim().replace(/\s+/g, ' ') : undefined);
50
- const activeInstruction = state?.activeInstruction ?? contract?.userIntent ?? lastUser ?? rootObjective;
52
+ const storedInstruction = state?.activeInstruction ?? contract?.userIntent ?? lastUser ?? rootObjective;
53
+ const intents = state?.intentHistory ?? [];
54
+ const matchingIntent = [...intents]
55
+ .reverse()
56
+ .find(intent => intent.taskEpoch === taskEpoch && intent.activeInstruction === storedInstruction);
57
+ const activeInstruction = (0, clarification_1.isReadOnlyQuestion)(matchingIntent?.input ?? storedInstruction ?? '')
58
+ ? ([...intents]
59
+ .reverse()
60
+ .find(intent => intent.taskEpoch === taskEpoch &&
61
+ (0, intent_1.shouldReplaceActiveInstruction)(intent) &&
62
+ !(0, clarification_1.isReadOnlyQuestion)(intent.input))?.activeInstruction ?? rootObjective)
63
+ : storedInstruction;
51
64
  const turnSummaries = state?.turnSummaries ?? [];
52
65
  const evidenceIndex = (0, evidence_1.buildEvidenceIndex)({
53
66
  ledger,
@@ -97,7 +110,7 @@ function upgradeHarnessState(state, options = {}) {
97
110
  ...(state?.taskTodoReceipts ? { taskTodoReceipts: state.taskTodoReceipts } : {}),
98
111
  rootObjective,
99
112
  activeInstruction,
100
- intentHistory: state?.intentHistory ?? [],
113
+ intentHistory: intents,
101
114
  activeConstraints: unique([
102
115
  ...(state?.activeConstraints ?? []),
103
116
  ...(contract?.constraints ?? []),
@@ -52,7 +52,7 @@ class StopController {
52
52
  {
53
53
  kind: 'inspect',
54
54
  label: 'Inspect missing criterion evidence',
55
- command: '/harness explain',
55
+ command: '/context explain',
56
56
  },
57
57
  ],
58
58
  resources: {},
@@ -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 [