@tea-agent/loop-agent 0.9.0 → 0.10.0-alpha.0

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 (183) hide show
  1. package/AGENTS.md +8 -0
  2. package/CHANGELOG.md +92 -11
  3. package/README.md +69 -5
  4. package/dist/application/dag/args.js +4 -14
  5. package/dist/application/dag/generate-task-dag.js +32 -2
  6. package/dist/application/dag/run-dag.js +1 -27
  7. package/dist/application/dag/validate-dag.js +2 -2
  8. package/dist/application/loop/run-action.js +0 -4
  9. package/dist/cli/command-definitions.js +7 -11
  10. package/dist/cli/program.js +9 -21
  11. package/dist/commands/cursor-prompt.js +42 -82
  12. package/dist/commands/dag-approve.js +36 -0
  13. package/dist/commands/dag-reconcile-run.js +118 -0
  14. package/dist/commands/delegate.js +75 -77
  15. package/dist/commands/doctor.js +0 -18
  16. package/dist/commands/init.js +60 -40
  17. package/dist/commands/instructions.js +7 -10
  18. package/dist/commands/loop.js +4 -20
  19. package/dist/executors/config-core.js +0 -51
  20. package/dist/executors/dag-pi-executor.js +1 -1
  21. package/dist/executors/dag.js +0 -1
  22. package/dist/executors/index.js +0 -2
  23. package/dist/executors/model-routing.js +9 -9
  24. package/dist/executors/shell-executor.js +1 -1
  25. package/dist/governance/checks.js +6 -3
  26. package/dist/governance/manifest-types.js +33 -2
  27. package/dist/infrastructure/harness/loop-action-store.js +0 -3
  28. package/dist/records/harvest.js +2 -23
  29. package/dist/records/one-shot-runs.js +1 -1
  30. package/dist/shared/artifacts-core.js +24 -5
  31. package/dist/shared/output-truncation.js +37 -0
  32. package/dist/shared/package-metadata.js +353 -0
  33. package/dist/{executors/cursor-executor.js → sidecars/cursor-prompt/executor.js} +2 -42
  34. package/dist/sidecars/cursor-prompt/index.js +3 -0
  35. package/dist/sidecars/cursor-prompt/stream.js +121 -0
  36. package/dist/task/config-types.js +29 -12
  37. package/dist/task/delegate.js +9 -21
  38. package/dist/task/runtime.js +1 -2
  39. package/dist/worker/cli.js +243 -0
  40. package/dist/worker/closeout/apply.js +73 -0
  41. package/dist/worker/closeout/preview.js +30 -0
  42. package/dist/worker/delivery/final-verification.js +194 -0
  43. package/dist/worker/delivery/git-transaction.js +354 -0
  44. package/dist/worker/delivery/package.js +502 -0
  45. package/dist/worker/feature/decision-loader.js +68 -0
  46. package/dist/worker/feature/discover.js +14 -0
  47. package/dist/worker/feature/next-action.js +74 -0
  48. package/dist/worker/feature/reducer.js +133 -0
  49. package/dist/worker/feature/review.js +502 -0
  50. package/dist/worker/feature/run.js +365 -0
  51. package/dist/worker/feature/types.js +1 -0
  52. package/dist/worker/follow-up/approve.js +270 -0
  53. package/dist/worker/follow-up/factory.js +234 -0
  54. package/dist/worker/follow-up/paths.js +25 -0
  55. package/dist/worker/follow-up/policy.js +26 -0
  56. package/dist/worker/follow-up/schema.js +93 -0
  57. package/dist/worker/follow-up/store.js +96 -0
  58. package/dist/worker/loop-agent/loop-agent-client.js +329 -126
  59. package/dist/worker/metrics/projector.js +139 -0
  60. package/dist/worker/observability/read-model.js +282 -15
  61. package/dist/worker/observe/paths.js +17 -5
  62. package/dist/worker/observe/static/app.js +443 -61
  63. package/dist/worker/observe/static/index.html +3 -1
  64. package/dist/worker/observe/static/styles.css +85 -18
  65. package/dist/worker/pool/run-store.js +14 -2
  66. package/dist/worker/pool/validation.js +59 -0
  67. package/dist/worker/preflight.js +49 -1
  68. package/dist/worker/report/morning-report.js +41 -6
  69. package/dist/worker/run-task/run-task.js +23 -13
  70. package/dist/worker/runner/run-ready.js +89 -11
  71. package/dist/worker/task-spec/schema.js +0 -1
  72. package/dist/workflows/dag/convergence/controller.js +1 -1
  73. package/dist/workflows/dag/executor-registry.js +0 -2
  74. package/dist/workflows/dag/governance-profile.js +10 -0
  75. package/dist/workflows/dag/init-hybrid.js +601 -26
  76. package/dist/workflows/dag/lifecycle.js +146 -0
  77. package/dist/workflows/dag/node-execution.js +64 -7
  78. package/dist/workflows/dag/prompt.js +16 -0
  79. package/dist/workflows/dag/report.js +2 -0
  80. package/dist/workflows/dag/runner.js +176 -119
  81. package/dist/workflows/dag/scheduler.js +7 -2
  82. package/dist/workflows/dag/skill-snapshot.js +527 -0
  83. package/dist/workflows/dag/types.js +45 -9
  84. package/dist/workflows/dag/validate.js +5 -8
  85. package/dist/workflows/loop/actions/dag-action.js +0 -2
  86. package/dist/workflows/loop/actions/shared.js +1 -1
  87. package/dist/workflows/loop/actions.js +14 -31
  88. package/dist/workflows/loop/benchmark.js +1 -1
  89. package/dist/workflows/loop/index.js +1 -1
  90. package/dist/workflows/loop/policy/auto-policy.js +22 -14
  91. package/dist/workflows/loop/policy/path-patterns.js +13 -0
  92. package/docs/README.md +35 -16
  93. package/docs/agent-dag-recovery-playbook.md +1 -1
  94. package/docs/architecture/README.md +26 -0
  95. package/docs/architecture/dag-execution.md +134 -0
  96. package/docs/architecture/evolution.md +52 -0
  97. package/docs/architecture/facts-and-state.md +58 -0
  98. package/docs/architecture/runtime-boundaries.md +41 -15
  99. package/docs/architecture/system-overview.md +93 -0
  100. package/docs/architecture/worker-and-feature.md +81 -0
  101. package/docs/cursor-prompt-sidecar.md +36 -0
  102. package/docs/decisions/README.md +13 -1
  103. package/docs/design/README.md +39 -13
  104. package/docs/development-principles.md +1 -1
  105. package/docs/exec-plans/active/README.md +2 -2
  106. package/docs/exec-plans/completed/README.md +14 -1
  107. package/docs/feature-workflow.md +44 -4
  108. package/docs/init-surface.manifest.json +63 -1
  109. package/docs/loop-agent-harness.md +65 -3
  110. package/docs/progress/README.md +27 -0
  111. package/docs/reports/README.md +74 -8
  112. package/docs/skills/README.md +2 -1
  113. package/docs/skills/vetted-skill-registry.md +2 -1
  114. package/docs/templates/agent-dag-report.schema.json +4 -2
  115. package/docs/templates/agent-dag.base.json +0 -5
  116. package/docs/templates/agent-dag.final-verification.json +0 -5
  117. package/docs/templates/agent-dag.schema.json +1 -2
  118. package/docs/templates/agent-dag.supervised-implementation.json +1 -6
  119. package/docs/templates/backend-test-dag.generate-pytest.prompt.md +131 -0
  120. package/docs/templates/backend-test-dag.json +213 -0
  121. package/docs/templates/backend-test-dag.retrospect.prompt.md +128 -0
  122. package/docs/templates/backend-test-dag.review-cases.prompt.md +85 -0
  123. package/docs/templates/frontend-design-contract.md +33 -0
  124. package/docs/templates/frontend-task-constraints.md +25 -0
  125. package/docs/templates/frontend-task-requirement.md +61 -0
  126. package/docs/templates/harness.schema.json +8 -5
  127. package/docs/templates/hybrid-dag.json +1 -6
  128. package/docs/templates/init-evolution-review.md +4 -2
  129. package/docs/templates/interactive-ui-round2-experiment.md +1 -1
  130. package/docs/templates/product-line/task.yaml +0 -1
  131. package/docs/templates/worker-dogfood-evidence.md +28 -0
  132. package/docs/templates/worker-dogfood-setup.md +20 -0
  133. package/docs/verification-matrix.md +17 -0
  134. package/examples/decision-gate-agent-dag.json +87 -33
  135. package/examples/example-dag.json +0 -5
  136. package/examples/hybrid-loop-agent-dag.json +0 -5
  137. package/harness.json +6 -11
  138. package/package.json +22 -44
  139. package/scripts/check-product-line-docs.sh +10 -3
  140. package/skills/agent-worker/SKILL.md +37 -0
  141. package/skills/agent-worker/references/agent-worker-operator.md +43 -0
  142. package/skills/frontend-design-review/SKILL.md +59 -0
  143. package/skills/frontend-design-review/references/review-checklist.md +37 -0
  144. package/skills/frontend-implementation/SKILL.md +48 -0
  145. package/skills/frontend-implementation/references/code-standards.md +34 -0
  146. package/skills/frontend-implementation/references/design-spec.md +46 -0
  147. package/skills/frontend-implementation/references/node-contracts.md +32 -0
  148. package/skills/frontend-review/SKILL.md +53 -0
  149. package/skills/frontend-review/references/review-findings.md +42 -0
  150. package/skills/frontend-verification/SKILL.md +40 -0
  151. package/skills/frontend-verification/references/verification-checklist.md +56 -0
  152. package/skills/grill-me/SKILL.md +10 -0
  153. package/skills/grill-with-docs/SKILL.md +88 -0
  154. package/skills/grill-with-docs/adr-format.md +47 -0
  155. package/skills/grill-with-docs/context-format.md +60 -0
  156. package/skills/init-capability-evolution/SKILL.md +1 -0
  157. package/skills/loop-agent/SKILL.md +11 -9
  158. package/skills/loop-agent/references/command-reference.md +28 -15
  159. package/skills/loop-agent/references/docs-converge.md +126 -0
  160. package/skills/loop-agent/references/harness-policy.md +7 -7
  161. package/skills/loop-agent/references/hybrid-dag.md +13 -15
  162. package/skills/loop-agent/references/long-running-loop.md +4 -6
  163. package/skills/loop-agent/references/multi-worktree.md +6 -6
  164. package/skills/loop-agent/references/orchestrator-and-interventions.md +3 -3
  165. package/skills/loop-agent/references/pi-subagent-assisted-mode.md +14 -11
  166. package/skills/using-git-worktrees/SKILL.md +215 -0
  167. package/dist/commands/cursor-worker.js +0 -43
  168. package/dist/cursor-worker-entry.js +0 -8
  169. package/dist/executors/cursor-artifacts.js +0 -33
  170. package/dist/executors/cursor-execution-log.js +0 -81
  171. package/dist/executors/cursor-executor-artifacts.js +0 -134
  172. package/dist/executors/cursor-run.js +0 -115
  173. package/dist/executors/cursor-tool.js +0 -94
  174. package/dist/executors/cursor-worker-client.js +0 -223
  175. package/dist/executors/cursor-worker-protocol.js +0 -18
  176. package/dist/executors/cursor-worker-server.js +0 -54
  177. package/dist/executors/cursor-worker.js +0 -3
  178. package/dist/executors/cursor.js +0 -6
  179. package/dist/executors/dag-cursor-executor.js +0 -87
  180. package/dist/workflows/loop/actions/cursor-fix.js +0 -191
  181. package/dist/workflows/loop/policy/cursor-fix-policy.js +0 -31
  182. package/docs/cursor-executor-usage.md +0 -25
  183. package/docs/dynamic-workflow-dag-engine-roadmap.md +0 -1749
@@ -62,20 +62,23 @@ pi -p --no-session --no-context-files --no-skills --tools subagent "Reply with e
62
62
 
63
63
  **Agents**(`.pi/agents/`)
64
64
 
65
- | Agent | Role | Model |
66
- |-------|------|-------|
67
- | `loop-agent-scout` | Read-only recon:code、tests、docs、governance | `cursor/composer-2.5` |
68
- | `loop-agent-planner` | Implementation planning:最小可执行 plan | `cursor/composer-2.5` |
69
- | `loop-agent-reviewer` | Strict review:scope drift、verification gap、contract break | `cursor/composer-2.5` |
70
- | `loop-agent-worker` | General execution:bounded implementation 与 fix | `cursor/composer-2.5` |
65
+ | Agent | Role | 对应阶段 |
66
+ |-------|------|----------|
67
+ | `loop-agent-scout` | 只读侦察:code、tests、docs、governance | Scout |
68
+ | `loop-agent-planner` | 最小可执行计划;强调验证与回退 | Plan |
69
+ | `loop-agent-reviewer` | 严格审查:范围漂移、验证缺口、契约破坏 | Verify / Review |
70
+ | `loop-agent-worker` | 有界实现与修补 | Implement |
71
71
 
72
- **Prompt Templates**(`.pi/prompts/`):输入 `/loop-agent-*` 调用
72
+ 另有通用 agents:`scout` / `planner` / `worker` / `reviewer`(中文提示,可被通用 prompt 模板调用)。模型以各 agent frontmatter 为准(当前仓库默认对齐 `harness.json` 的 Pi executor)。
73
+
74
+ **Prompt Templates**(`.pi/prompts/`):输入 `/loop-agent-*` 或通用模板名调用
73
75
 
74
76
  | Template | Flow |
75
77
  |----------|------|
76
- | `loop-agent-scout-and-plan` | scout → planner chain |
77
- | `loop-agent-analyze-wide` | 3 parallel scouts → analysis |
78
- | `loop-agent-review-only` | 独立 review plan/implementation/verification |
79
- | `loop-agent-implement-and-review` | worker → reviewer → worker loop |
78
+ | `loop-agent-scout-and-plan` | parallel scout → planner |
79
+ | `loop-agent-analyze-wide` | 3 parallel scouts → 结构化分析 |
80
+ | `loop-agent-review-only` | 独立审查计划/实现/验证 |
81
+ | `loop-agent-implement-and-review` | worker → reviewer → worker |
82
+ | `scout-and-plan` / `implement` / `implement-and-review` | 通用 chain(调用 `scout`/`planner`/`worker`/`reviewer`) |
80
83
 
81
84
  传 `agentScope: "both"` + `confirmProjectAgents: false` 以访问 repo-local agents。
@@ -0,0 +1,215 @@
1
+ ---
2
+ name: using-git-worktrees
3
+ description: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback
4
+ ---
5
+
6
+ # Using Git Worktrees
7
+
8
+ ## Overview
9
+
10
+ Ensure work happens in an isolated workspace. Prefer your platform's native worktree tools. Fall back to manual git worktrees only when no native tool is available.
11
+
12
+ **Core principle:** Detect existing isolation first. Then use native tools. Then fall back to git. Never fight the harness.
13
+
14
+ **Announce at start:** "I'm using the using-git-worktrees skill to set up an isolated workspace."
15
+
16
+ ## Step 0: Detect Existing Isolation
17
+
18
+ **Before creating anything, check if you are already in an isolated workspace.**
19
+
20
+ ```bash
21
+ GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
22
+ GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
23
+ BRANCH=$(git branch --show-current)
24
+ ```
25
+
26
+ **Submodule guard:** `GIT_DIR != GIT_COMMON` is also true inside git submodules. Before concluding "already in a worktree," verify you are not in a submodule:
27
+
28
+ ```bash
29
+ # If this returns a path, you're in a submodule, not a worktree — treat as normal repo
30
+ git rev-parse --show-superproject-working-tree 2>/dev/null
31
+ ```
32
+
33
+ **If `GIT_DIR != GIT_COMMON` (and not a submodule):** You are already in a linked worktree. Skip to Step 3 (Project Setup). Do NOT create another worktree.
34
+
35
+ Report with branch state:
36
+ - On a branch: "Already in isolated workspace at `<path>` on branch `<name>`."
37
+ - Detached HEAD: "Already in isolated workspace at `<path>` (detached HEAD, externally managed). Branch creation needed at finish time."
38
+
39
+ **If `GIT_DIR == GIT_COMMON` (or in a submodule):** You are in a normal repo checkout.
40
+
41
+ Has the user already indicated their worktree preference in your instructions? If not, ask for consent before creating a worktree:
42
+
43
+ > "Would you like me to set up an isolated worktree? It protects your current branch from changes."
44
+
45
+ Honor any existing declared preference without asking. If the user declines consent, work in place and skip to Step 3.
46
+
47
+ ## Step 1: Create Isolated Workspace
48
+
49
+ **You have two mechanisms. Try them in this order.**
50
+
51
+ ### 1a. Native Worktree Tools (preferred)
52
+
53
+ The user has asked for an isolated workspace (Step 0 consent). Do you already have a way to create a worktree? It might be a tool with a name like `EnterWorktree`, `WorktreeCreate`, a `/worktree` command, or a `--worktree` flag. If you do, use it and skip to Step 3.
54
+
55
+ Native tools handle directory placement, branch creation, and cleanup automatically. Using `git worktree add` when you have a native tool creates phantom state your harness can't see or manage.
56
+
57
+ Only proceed to Step 1b if you have no native worktree tool available.
58
+
59
+ ### 1b. Git Worktree Fallback
60
+
61
+ **Only use this if Step 1a does not apply** — you have no native worktree tool available. Create a worktree manually using git.
62
+
63
+ #### Directory Selection
64
+
65
+ Follow this priority order. Explicit user preference always beats observed filesystem state.
66
+
67
+ 1. **Check your instructions for a declared worktree directory preference.** If the user has already specified one, use it without asking.
68
+
69
+ 2. **Check for an existing project-local worktree directory:**
70
+ ```bash
71
+ ls -d .worktrees 2>/dev/null # Preferred (hidden)
72
+ ls -d worktrees 2>/dev/null # Alternative
73
+ ```
74
+ If found, use it. If both exist, `.worktrees` wins.
75
+
76
+ 3. **Check for an existing global directory:**
77
+ ```bash
78
+ project=$(basename "$(git rev-parse --show-toplevel)")
79
+ ls -d ~/.worktrees 2>/dev/null
80
+ ```
81
+ If found, use it.
82
+
83
+ 4. **If there is no other guidance available**, default to `.worktrees/` at the project root.
84
+
85
+ #### Safety Verification (project-local directories only)
86
+
87
+ **MUST verify directory is ignored before creating worktree:**
88
+
89
+ ```bash
90
+ git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null
91
+ ```
92
+
93
+ **If NOT ignored:** Add to .gitignore, commit the change, then proceed.
94
+
95
+ **Why critical:** Prevents accidentally committing worktree contents to repository.
96
+
97
+ Global directories (`~/.worktrees/`) need no verification.
98
+
99
+ #### Create the Worktree
100
+
101
+ ```bash
102
+ project=$(basename "$(git rev-parse --show-toplevel)")
103
+
104
+ # Determine path based on chosen location
105
+ # For project-local: path="$LOCATION/$BRANCH_NAME"
106
+ # For global: path="~/.worktrees/$BRANCH_NAME"
107
+
108
+ git worktree add "$path" -b "$BRANCH_NAME"
109
+ cd "$path"
110
+ ```
111
+
112
+ **Sandbox fallback:** If `git worktree add` fails with a permission error (sandbox denial), tell the user the sandbox blocked worktree creation and you're working in the current directory instead. Then run setup and baseline tests in place.
113
+
114
+ ## Step 3: Project Setup
115
+
116
+ Auto-detect and run appropriate setup:
117
+
118
+ ```bash
119
+ # Node.js
120
+ if [ -f package.json ]; then npm install; fi
121
+
122
+ # Rust
123
+ if [ -f Cargo.toml ]; then cargo build; fi
124
+
125
+ # Python
126
+ if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
127
+ if [ -f pyproject.toml ]; then poetry install; fi
128
+
129
+ # Go
130
+ if [ -f go.mod ]; then go mod download; fi
131
+ ```
132
+
133
+ ## Step 4: Verify Clean Baseline
134
+
135
+ Run tests to ensure workspace starts clean:
136
+
137
+ ```bash
138
+ # Use project-appropriate command
139
+ npm test / cargo test / pytest / go test ./...
140
+ ```
141
+
142
+ **If tests fail:** Report failures, ask whether to proceed or investigate.
143
+
144
+ **If tests pass:** Report ready.
145
+
146
+ ### Report
147
+
148
+ ```
149
+ Worktree ready at <full-path>
150
+ Tests passing (<N> tests, 0 failures)
151
+ Ready to implement <feature-name>
152
+ ```
153
+
154
+ ## Quick Reference
155
+
156
+ | Situation | Action |
157
+ |-----------|--------|
158
+ | Already in linked worktree | Skip creation (Step 0) |
159
+ | In a submodule | Treat as normal repo (Step 0 guard) |
160
+ | Native worktree tool available | Use it (Step 1a) |
161
+ | No native tool | Git worktree fallback (Step 1b) |
162
+ | `.worktrees/` exists | Use it (verify ignored) |
163
+ | `worktrees/` exists | Use it (verify ignored) |
164
+ | Both exist | Use `.worktrees/` |
165
+ | Neither exists | Check instruction file, then default `.worktrees/` |
166
+ | Global path exists | Use it (backward compat) |
167
+ | Directory not ignored | Add to .gitignore + commit |
168
+ | Permission error on create | Sandbox fallback, work in place |
169
+ | Tests fail during baseline | Report failures + ask |
170
+ | No package.json/Cargo.toml | Skip dependency install |
171
+
172
+ ## Common Mistakes
173
+
174
+ ### Fighting the harness
175
+
176
+ - **Problem:** Using `git worktree add` when the platform already provides isolation
177
+ - **Fix:** Step 0 detects existing isolation. Step 1a defers to native tools.
178
+
179
+ ### Skipping detection
180
+
181
+ - **Problem:** Creating a nested worktree inside an existing one
182
+ - **Fix:** Always run Step 0 before creating anything
183
+
184
+ ### Skipping ignore verification
185
+
186
+ - **Problem:** Worktree contents get tracked, pollute git status
187
+ - **Fix:** Always use `git check-ignore` before creating project-local worktree
188
+
189
+ ### Assuming directory location
190
+
191
+ - **Problem:** Creates inconsistency, violates project conventions
192
+ - **Fix:** Follow priority: existing > global legacy > instruction file > default
193
+
194
+ ### Proceeding with failing tests
195
+
196
+ - **Problem:** Can't distinguish new bugs from pre-existing issues
197
+ - **Fix:** Report failures, get explicit permission to proceed
198
+
199
+ ## Red Flags
200
+
201
+ **Never:**
202
+ - Create a worktree when Step 0 detects existing isolation
203
+ - Use `git worktree add` when you have a native worktree tool (e.g., `EnterWorktree`). This is the #1 mistake — if you have it, use it.
204
+ - Skip Step 1a by jumping straight to Step 1b's git commands
205
+ - Create worktree without verifying it's ignored (project-local)
206
+ - Skip baseline test verification
207
+ - Proceed with failing tests without asking
208
+
209
+ **Always:**
210
+ - Run Step 0 detection first
211
+ - Prefer native tools over git fallback
212
+ - Follow directory priority: existing > global legacy > instruction file > default
213
+ - Verify directory is ignored for project-local
214
+ - Auto-detect and run project setup
215
+ - Verify clean test baseline
@@ -1,43 +0,0 @@
1
- import { executeCursorTaskViaWorker, getCursorWorkerEntryPath, isCursorWorkerChild, isCursorWorkerEnabled, isCursorWorkerRunning, stopCursorWorker, } from '../executors/cursor-worker-client.js';
2
- export function parseCursorWorkerArgs(args) {
3
- const action = args[0];
4
- if (action === 'status' || action === 'stop' || action === 'ping') {
5
- return { action };
6
- }
7
- throw new Error('usage: cursor-worker <status|stop|ping>');
8
- }
9
- export async function runCursorWorker(repoRoot, rawArgs) {
10
- const { action } = parseCursorWorkerArgs(rawArgs);
11
- if (action === 'status') {
12
- console.log(JSON.stringify({
13
- enabled: isCursorWorkerEnabled(),
14
- running: isCursorWorkerRunning(),
15
- child: isCursorWorkerChild(),
16
- entry: getCursorWorkerEntryPath(),
17
- repoRoot,
18
- }, null, 2));
19
- return;
20
- }
21
- if (action === 'stop') {
22
- await stopCursorWorker();
23
- console.log('cursor worker stopped');
24
- return;
25
- }
26
- if (action === 'ping') {
27
- if (!isCursorWorkerEnabled()) {
28
- console.error('Set CURSOR_USE_WORKER=1 to enable the worker path.');
29
- }
30
- try {
31
- const result = await executeCursorTaskViaWorker({
32
- task: 'Reply with exactly: WORKER_PING_OK',
33
- cwd: repoRoot,
34
- model: 'default',
35
- timeoutMs: 120_000,
36
- });
37
- console.log(JSON.stringify({ ok: result.ok, stdout: result.stdout.trim() }, null, 2));
38
- }
39
- finally {
40
- await stopCursorWorker();
41
- }
42
- }
43
- }
@@ -1,8 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Long-lived Cursor SDK worker (NDJSON on stdin/stdout).
4
- * Spawned by cursor-worker-client when CURSOR_USE_WORKER=1.
5
- */
6
- import { runCursorWorkerOnStreams } from './executors/cursor-worker-server.js';
7
- process.env.CURSOR_WORKER_CHILD = '1';
8
- await runCursorWorkerOnStreams(process.stdin, process.stdout);
@@ -1,33 +0,0 @@
1
- const MODIFY_LOG_MARKERS = ['修改摘要', '修改文件', '验证', '风险'];
2
- const VERIFY_RESULT_MARKERS = ['命令', 'exit', 'pass', 'fail', '未运行'];
3
- export function validateCursorModifyLog(content) {
4
- const trimmed = content.trim();
5
- if (!trimmed)
6
- return ['修改记录.md is empty'];
7
- if (!trimmed.includes('# 修改记录'))
8
- return ['修改记录.md missing heading: # 修改记录'];
9
- const missing = MODIFY_LOG_MARKERS.filter((marker) => !trimmed.includes(marker));
10
- return missing.map((marker) => `修改记录.md missing section marker: ${marker}`);
11
- }
12
- export function validateCursorVerifyResult(content) {
13
- const trimmed = content.trim();
14
- if (!trimmed)
15
- return ['验证结果.md is empty'];
16
- if (!trimmed.includes('# 验证结果'))
17
- return ['验证结果.md missing heading: # 验证结果'];
18
- const hasCommandMarker = VERIFY_RESULT_MARKERS.some((marker) => trimmed.toLowerCase().includes(marker.toLowerCase()));
19
- if (!hasCommandMarker) {
20
- return ['验证结果.md missing verification command / exit / pass-fail evidence'];
21
- }
22
- return [];
23
- }
24
- export function validateCursorArtifacts(modifyLog, verifyResult) {
25
- return [
26
- ...validateCursorModifyLog(modifyLog),
27
- ...validateCursorVerifyResult(verifyResult),
28
- ];
29
- }
30
- export function isEmptyArtifactTemplate(content, templateMarker) {
31
- const trimmed = content.trim();
32
- return trimmed.includes(templateMarker) && trimmed.split('\n').filter((line) => line.trim().length > 0).length <= 3;
33
- }
@@ -1,81 +0,0 @@
1
- import { access, appendFile, mkdir } from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { buildCursorPrompt, buildRedactedExecutorRecord, } from './cursor-executor.js';
4
- import { appendExecutorRecord } from '../shared/logger.js';
5
- export function resolveDelegateExecutionMode(executor) {
6
- if (executor === 'pi')
7
- return 'pi-worktree';
8
- if (executor === 'cursor')
9
- return 'direct';
10
- return undefined;
11
- }
12
- export function buildCursorExecutionLogRecord(input) {
13
- const base = buildRedactedExecutorRecord({
14
- executor: 'cursor',
15
- model: input.model,
16
- durationMs: input.result.durationMs,
17
- failureCategory: input.result.failureCategory,
18
- ok: input.result.ok,
19
- status: input.result.status,
20
- prompt: input.prompt,
21
- result: input.result,
22
- apiKey: input.apiKey,
23
- });
24
- return {
25
- ...base,
26
- channel: input.context.channel,
27
- executionMode: input.context.executionMode,
28
- cwd: input.context.cwd,
29
- taskId: input.context.taskId,
30
- dagRunId: input.context.dagRunId,
31
- dagNodeId: input.context.dagNodeId,
32
- recordedAt: new Date().toISOString(),
33
- };
34
- }
35
- export async function persistCursorExecutionLog(logsDir, record, fileName = 'executor.jsonl') {
36
- await mkdir(logsDir, { recursive: true });
37
- await appendFile(path.join(logsDir, fileName), `${JSON.stringify(record)}\n`, 'utf-8');
38
- }
39
- /** Append a unified record to `<taskDir>/logs/executor.jsonl`. */
40
- export async function appendCursorExecutionLog(taskDir, record) {
41
- await appendExecutorRecord(taskDir, record);
42
- }
43
- export async function persistCursorToolExecution(cwd, input) {
44
- try {
45
- await access(path.join(cwd, '.harness'));
46
- }
47
- catch {
48
- return;
49
- }
50
- const cacheDir = path.join(cwd, '.harness', 'cache');
51
- const record = buildCursorExecutionLogRecord({
52
- context: { channel: 'tool', cwd },
53
- model: input.model,
54
- prompt: buildCursorPrompt(input.task),
55
- result: input.result,
56
- apiKey: input.apiKey,
57
- });
58
- await persistCursorExecutionLog(cacheDir, record, 'cursor-executions.jsonl');
59
- }
60
- export function formatCursorFailureMessage(category) {
61
- switch (category) {
62
- case 'missing-api-key':
63
- return 'CURSOR_API_KEY is not set.';
64
- case 'auth':
65
- return 'Cursor API authentication failed.';
66
- case 'network':
67
- return 'Cursor API network error.';
68
- case 'timeout':
69
- return 'Cursor execution timed out.';
70
- case 'invalid-output':
71
- return 'Cursor output or artifacts are invalid.';
72
- case 'path-violation':
73
- return 'Cursor task violated path boundaries.';
74
- case 'nonzero-exit':
75
- return 'Cursor agent did not complete successfully.';
76
- case 'success':
77
- return 'OK';
78
- default:
79
- return 'Cursor execution failed.';
80
- }
81
- }
@@ -1,134 +0,0 @@
1
- import path from "node:path";
2
- import { writeTextArtifactFile } from "../infrastructure/harness/artifact-store.js";
3
- import { redactPromptForLog, truncateOutput, } from "./cursor-executor.js";
4
- import { formatCursorFailureMessage, } from "./cursor-execution-log.js";
5
- const SUMMARY_STDOUT_MAX = 4_000;
6
- const SUMMARY_STDERR_MAX = 2_000;
7
- export function buildPromptRedactedMarkdown(prompt) {
8
- const redacted = redactPromptForLog(prompt);
9
- return [
10
- "# Cursor prompt (redacted)",
11
- "",
12
- `- ${redacted}`,
13
- "",
14
- "Full prompt text is not stored. See `logs/executor.jsonl` for the same hash reference.",
15
- "",
16
- ].join("\n");
17
- }
18
- export function buildCursorRecoverySteps(input) {
19
- const taskId = input.taskId ?? "<task-id>";
20
- const session = input.sessionName ?? `task-${taskId}`;
21
- const lines = ["## Recovery steps", ""];
22
- if (input.failureCategory) {
23
- lines.push(`- **Failure**: ${formatCursorFailureMessage(input.failureCategory)} (\`${input.failureCategory}\`)`);
24
- lines.push("");
25
- }
26
- if (input.channel === "delegate") {
27
- lines.push("### Retry in-process (direct SDK)");
28
- lines.push("```bash");
29
- lines.push("cd .");
30
- lines.push(`npm run dev -- delegate ${taskId} --executor cursor --auto-run`);
31
- lines.push("```");
32
- if (input.worktreePath) {
33
- lines.push("");
34
- lines.push(`- Worktree: \`${input.worktreePath}\``);
35
- }
36
- lines.push("");
37
- lines.push("### Promote evidence");
38
- lines.push("```bash");
39
- lines.push(`npm run dev -- promote-run ${taskId} --run-id <run-id>`);
40
- lines.push(`npm run dev -- closeout task ${taskId}`);
41
- lines.push("```");
42
- lines.push("");
43
- lines.push("### After closeout");
44
- lines.push("```bash");
45
- lines.push(`npm run dev -- harvest ${taskId}`);
46
- lines.push("```");
47
- }
48
- else if (input.channel === "dag") {
49
- lines.push("### Re-run DAG node");
50
- lines.push("- Fix upstream outputs or prompts in the DAG JSON, then re-run `run-dag` with a new `--run-id`.");
51
- lines.push("- Inspect `executor.jsonl` and per-node `result.summary.md` under `.harness/dag-runs/completed/<run-id>/` (or `active/<run-id>/` while the run is still in progress).");
52
- }
53
- else {
54
- lines.push("### Pi cursor tool");
55
- lines.push("- Retry with a clearer `task` and correct `cwd`.");
56
- lines.push("- Check `.harness/cache/cursor-executions.jsonl` when cwd contains `.harness`.");
57
- }
58
- if (input.failureCategory === "missing-api-key") {
59
- lines.push("");
60
- lines.push("- Export `CURSOR_API_KEY` before retrying.");
61
- }
62
- return lines;
63
- }
64
- function formatTokenUsage(result) {
65
- const rows = [];
66
- if (result.tokensUsed !== undefined) {
67
- rows.push(`| tokensUsed | ${result.tokensUsed} |`);
68
- }
69
- const usage = result.details?.usage;
70
- if (typeof usage?.inputTokens === "number") {
71
- rows.push(`| inputTokens | ${usage.inputTokens} |`);
72
- }
73
- if (typeof usage?.outputTokens === "number") {
74
- rows.push(`| outputTokens | ${usage.outputTokens} |`);
75
- }
76
- if (typeof usage?.totalTokens === "number" &&
77
- result.tokensUsed === undefined) {
78
- rows.push(`| totalTokens | ${usage.totalTokens} |`);
79
- }
80
- return rows;
81
- }
82
- export function buildResultSummaryMarkdown(input) {
83
- const stdout = truncateOutput(input.result.stdout, SUMMARY_STDOUT_MAX);
84
- const stderr = truncateOutput(input.result.stderr || "", SUMMARY_STDERR_MAX);
85
- const recovery = input.recoveryLines ??
86
- buildCursorRecoverySteps({
87
- channel: input.context.channel,
88
- taskId: input.context.taskId,
89
- sessionName: input.context.taskId
90
- ? `task-${input.context.taskId}`
91
- : undefined,
92
- worktreePath: input.context.cwd,
93
- failureCategory: input.result.ok
94
- ? undefined
95
- : input.result.failureCategory,
96
- });
97
- const meta = [
98
- "# Cursor execution summary",
99
- "",
100
- "## Run metadata",
101
- "",
102
- `| Field | Value |`,
103
- `|-------|-------|`,
104
- `| channel | ${input.context.channel} |`,
105
- ];
106
- if (input.context.executionMode)
107
- meta.push(`| executionMode | ${input.context.executionMode} |`);
108
- if (input.context.taskId)
109
- meta.push(`| taskId | ${input.context.taskId} |`);
110
- if (input.context.dagRunId)
111
- meta.push(`| dagRunId | ${input.context.dagRunId} |`);
112
- if (input.context.dagNodeId)
113
- meta.push(`| dagNodeId | ${input.context.dagNodeId} |`);
114
- meta.push(`| cwd | ${input.context.cwd} |`, `| model | ${input.model} |`, `| ok | ${input.result.ok} |`, `| status | ${input.result.status} |`, `| failureCategory | ${input.result.failureCategory} |`, `| durationMs | ${input.result.durationMs} |`, ...formatTokenUsage(input.result), "", "## Prompt reference", "", `- ${redactPromptForLog(input.prompt)}`, "", "## Output", "");
115
- if (stdout.text.trim()) {
116
- meta.push("### stdout", "", "```text", stdout.text, "```", "");
117
- if (stdout.truncated)
118
- meta.push("_(stdout truncated)_", "");
119
- }
120
- if (stderr.text.trim()) {
121
- meta.push("### stderr", "", "```text", stderr.text, "```", "");
122
- if (stderr.truncated)
123
- meta.push("_(stderr truncated)_", "");
124
- }
125
- meta.push(...recovery, "");
126
- return meta.join("\n");
127
- }
128
- export async function writeCursorExecutorArtifacts(artifactsDir, input) {
129
- const promptPath = path.join(artifactsDir, "prompt.redacted.md");
130
- const summaryPath = path.join(artifactsDir, "result.summary.md");
131
- await writeTextArtifactFile(promptPath, buildPromptRedactedMarkdown(input.prompt));
132
- await writeTextArtifactFile(summaryPath, buildResultSummaryMarkdown(input));
133
- return { promptPath, summaryPath };
134
- }
@@ -1,115 +0,0 @@
1
- import { readFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { validateCursorArtifacts } from './cursor-artifacts.js';
4
- import { buildCursorPrompt, executeCursorTask, } from './cursor-executor.js';
5
- import { writeCursorExecutorArtifacts } from './cursor-executor-artifacts.js';
6
- import { appendCursorExecutionLog, buildCursorExecutionLogRecord, } from './cursor-execution-log.js';
7
- import { assertCursorExecutorAvailable, resolveCursorExecutorConfig, resolveCursorModelForTaskConfig, } from './config-core.js';
8
- import { appendWorkflowLog } from '../shared/logger.js';
9
- import { getTaskDir, getTaskPaths, loadTaskConfig } from '../task/runtime.js';
10
- export async function runCursorDelegatedTask(repoRoot, taskId, manifest, options = {}) {
11
- const taskConfig = await loadTaskConfig(repoRoot, taskId);
12
- if (taskConfig.executor !== 'cursor') {
13
- throw new Error(`runCursorDelegatedTask requires executor=cursor, got "${taskConfig.executor ?? 'pi'}"`);
14
- }
15
- assertCursorExecutorAvailable(manifest);
16
- const cursorConfig = resolveCursorExecutorConfig(manifest);
17
- const taskDir = getTaskDir(repoRoot, taskId);
18
- const userTask = await buildCursorTaskDescription(repoRoot, taskId);
19
- const model = resolveCursorModelForTaskConfig(taskConfig, cursorConfig);
20
- await appendWorkflowLog(taskDir, `cursor executor start model=${model}`);
21
- const result = await executeCursorTask({
22
- task: userTask,
23
- cwd: repoRoot,
24
- model,
25
- timeoutMs: taskConfig.timeoutMs,
26
- runHook: options.runHook,
27
- });
28
- const prompt = buildCursorPrompt(userTask);
29
- const executionContext = {
30
- channel: 'delegate',
31
- cwd: repoRoot,
32
- executionMode: options.executionMode ?? 'direct',
33
- taskId,
34
- };
35
- await appendCursorExecutionLog(taskDir, buildCursorExecutionLogRecord({
36
- context: executionContext,
37
- model,
38
- prompt,
39
- result,
40
- }));
41
- await writeCursorExecutorArtifacts(path.join(taskDir, 'logs'), {
42
- prompt,
43
- model,
44
- context: executionContext,
45
- result,
46
- });
47
- const artifactIssues = await validateCursorTaskArtifacts(repoRoot, taskId);
48
- if (!result.ok) {
49
- await appendWorkflowLog(taskDir, `cursor executor failed category=${result.failureCategory}`);
50
- return result;
51
- }
52
- if (artifactIssues.length > 0) {
53
- await appendWorkflowLog(taskDir, `cursor artifact validation failed: ${artifactIssues.join('; ')}`);
54
- return {
55
- ...result,
56
- ok: false,
57
- status: 'failed',
58
- failureCategory: 'invalid-output',
59
- stderr: artifactIssues.join('\n'),
60
- details: {
61
- ...(result.details ?? {}),
62
- artifactIssues,
63
- },
64
- };
65
- }
66
- const postRun = options.postRun ?? 'none';
67
- if (postRun === 'verify') {
68
- const message = 'Cursor direct run no longer runs legacy sequential verify; use DAG verification, promote-run, or closeout.';
69
- await appendWorkflowLog(taskDir, `cursor post-run verify rejected: ${message}`);
70
- return {
71
- ...result,
72
- ok: false,
73
- status: 'failed',
74
- failureCategory: 'nonzero-exit',
75
- stderr: message,
76
- details: {
77
- ...(result.details ?? {}),
78
- postRunFailed: true,
79
- },
80
- };
81
- }
82
- await appendWorkflowLog(taskDir, 'cursor executor completed; one-shot evidence only');
83
- return result;
84
- }
85
- async function buildCursorTaskDescription(repoRoot, taskId) {
86
- const paths = getTaskPaths(repoRoot, taskId);
87
- const taskConfig = await loadTaskConfig(repoRoot, taskId);
88
- const requirement = await readFile(path.join(paths.sourceDir, '需求.md'), 'utf-8');
89
- const constraints = await readFile(path.join(paths.sourceDir, '执行约束.md'), 'utf-8');
90
- return [
91
- `# Task ${taskId}`,
92
- '',
93
- '## 需求.md',
94
- requirement.trim(),
95
- '',
96
- '## 执行约束.md',
97
- constraints.trim(),
98
- '',
99
- '## Path boundaries',
100
- `- allowedPaths: ${(taskConfig.allowedPaths ?? []).join(', ') || '(read-only; no code writes outside .harness/tasks/)'}`,
101
- `- forbiddenPaths: ${(taskConfig.forbiddenPaths ?? []).join(', ') || '(none)'}`,
102
- '',
103
- '## Required artifacts',
104
- '- artifacts/修改记录.md must include 修改摘要 / 修改文件 / 验证 / 风险',
105
- '- artifacts/验证结果.md must include commands, exit code, pass/fail',
106
- ].join('\n');
107
- }
108
- async function validateCursorTaskArtifacts(repoRoot, taskId) {
109
- const paths = getTaskPaths(repoRoot, taskId);
110
- const modifyLogPath = path.join(paths.taskDir, 'artifacts', '修改记录.md');
111
- const verifyResultPath = path.join(paths.taskDir, 'artifacts', '验证结果.md');
112
- const modifyLog = await readFile(modifyLogPath, 'utf-8');
113
- const verifyResult = await readFile(verifyResultPath, 'utf-8');
114
- return validateCursorArtifacts(modifyLog, verifyResult);
115
- }