pi-crew 0.9.67 → 0.10.1

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 (222) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/agents/analyst.md +1 -1
  3. package/agents/cold-verifier.md +3 -1
  4. package/agents/critic.md +1 -1
  5. package/agents/executor.md +1 -1
  6. package/agents/explorer.md +1 -1
  7. package/agents/planner.md +1 -1
  8. package/agents/reviewer.md +1 -1
  9. package/agents/security-reviewer.md +1 -1
  10. package/agents/test-engineer.md +1 -1
  11. package/agents/verifier.md +1 -1
  12. package/agents/writer.md +1 -1
  13. package/dist/index.mjs +65847 -60331
  14. package/docs/README.md +2 -0
  15. package/docs/actions-reference.md +31 -0
  16. package/docs/commands-reference.md +17 -6
  17. package/docs/resource-formats.md +13 -0
  18. package/package.json +9 -6
  19. package/schema.json +15 -1
  20. package/scripts/resource-sampler.mjs +36 -2
  21. package/skills/requirements-to-task-packet/SKILL.md +26 -0
  22. package/skills/widget-rendering/SKILL.md +7 -7
  23. package/src/agents/agent-config.ts +36 -14
  24. package/src/agents/discover-agents.ts +23 -14
  25. package/src/config/config-merge.ts +183 -0
  26. package/src/config/config-validation.ts +681 -0
  27. package/src/config/config.ts +22 -864
  28. package/src/config/defaults.ts +35 -1
  29. package/src/config/drift-detector.ts +1 -1
  30. package/src/config/env-vars.ts +691 -0
  31. package/src/config/role-tools.ts +8 -8
  32. package/src/config/sanitize-project-config.ts +172 -0
  33. package/src/config/types.ts +30 -0
  34. package/src/extension/async-notifier.ts +25 -2
  35. package/src/extension/crew-vibes/config.ts +2 -1
  36. package/src/extension/plan-orchestrate.ts +132 -0
  37. package/src/extension/registration/commands/dashboard.ts +158 -0
  38. package/src/extension/registration/commands/index.ts +35 -0
  39. package/src/extension/registration/commands/manage.ts +303 -0
  40. package/src/extension/registration/commands/run.ts +214 -0
  41. package/src/extension/registration/commands/shared.ts +631 -0
  42. package/src/extension/registration/commands/status.ts +60 -0
  43. package/src/extension/registration/commands.ts +13 -1224
  44. package/src/extension/registration/lifecycle-handlers.ts +126 -15
  45. package/src/extension/registration/subagent-tools.ts +218 -9
  46. package/src/extension/rpc-hmac.ts +5 -3
  47. package/src/extension/team-tool/api/heartbeat.ts +47 -10
  48. package/src/extension/team-tool/api/plan-approval.ts +9 -0
  49. package/src/extension/team-tool/api/task-claims.ts +109 -40
  50. package/src/extension/team-tool/cancel.ts +84 -50
  51. package/src/extension/team-tool/dispatch/index.ts +1 -0
  52. package/src/extension/team-tool/dispatch/run.ts +4 -1
  53. package/src/extension/team-tool/doctor.ts +103 -1
  54. package/src/extension/team-tool/orchestrate.ts +66 -1
  55. package/src/extension/team-tool/plans.ts +192 -0
  56. package/src/extension/team-tool/respond.ts +197 -65
  57. package/src/extension/team-tool/run-deadline.ts +16 -1
  58. package/src/extension/team-tool/run-intent.ts +63 -0
  59. package/src/extension/team-tool/run.ts +48 -18
  60. package/src/extension/team-tool/status.ts +84 -26
  61. package/src/extension/team-tool.ts +11 -2
  62. package/src/hooks/registry.ts +1 -6
  63. package/src/i18n.ts +9 -0
  64. package/src/prompt/prompt-runtime.ts +521 -2
  65. package/src/prompt/worker-events-channel.ts +173 -0
  66. package/src/runtime/README.md +8 -8
  67. package/src/runtime/async-runner.ts +7 -3
  68. package/src/runtime/background-runner.ts +42 -14
  69. package/src/runtime/broker/broker-issuer.ts +9 -2
  70. package/src/runtime/broker/crew-broker-tokens.ts +43 -6
  71. package/src/runtime/broker/crew-broker.ts +838 -10
  72. package/src/runtime/broker/wait-status-cache.ts +157 -0
  73. package/src/runtime/budget-enforcement.ts +281 -0
  74. package/src/runtime/child-pi/child-pi-spawn.ts +60 -14
  75. package/src/runtime/child-pi/child-pi-timers.ts +324 -0
  76. package/src/runtime/child-pi/child-pi.ts +97 -201
  77. package/src/runtime/child-pi/mock-fixtures.ts +16 -2
  78. package/src/runtime/crew-agent-records.ts +259 -14
  79. package/src/runtime/delegate-spawn.ts +148 -0
  80. package/src/runtime/deterministic-ast.ts +2 -1
  81. package/src/runtime/dispatch-batch.ts +945 -0
  82. package/src/runtime/finalize-run.ts +557 -0
  83. package/src/runtime/goal-workflow/adaptive-plan.ts +87 -13
  84. package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +3 -2
  85. package/src/runtime/goal-workflow/goal-state-store.ts +1 -1
  86. package/src/runtime/group-join.ts +11 -125
  87. package/src/runtime/live-session/live-session-runtime.ts +26 -1
  88. package/src/runtime/merge-gate.ts +7 -1
  89. package/src/runtime/merge-loop.ts +130 -0
  90. package/src/runtime/model/model-budget-summary.ts +53 -0
  91. package/src/runtime/model/model-fallback.ts +32 -2
  92. package/src/runtime/model/pi-args.ts +10 -0
  93. package/src/runtime/model/provider-extensions.ts +10 -0
  94. package/src/runtime/orphan-worker-registry.ts +1 -1
  95. package/src/runtime/output/output-validator.ts +45 -0
  96. package/src/runtime/parent-guard.ts +3 -1
  97. package/src/runtime/peer-dep.ts +2 -1
  98. package/src/runtime/per-write-validator.ts +0 -5
  99. package/src/runtime/pi-spawn.ts +61 -15
  100. package/src/runtime/plan-approval.ts +125 -0
  101. package/src/runtime/plan-replan.ts +151 -0
  102. package/src/runtime/recovery/checkpoint.ts +0 -18
  103. package/src/runtime/recovery/crash-recovery.ts +95 -46
  104. package/src/runtime/scheduler-context.ts +98 -0
  105. package/src/runtime/scheduling/coalesce-tasks.ts +5 -0
  106. package/src/runtime/scheduling/global-worker-cap.ts +2 -1
  107. package/src/runtime/scheduling/nested-slots.ts +70 -0
  108. package/src/runtime/scheduling/run-coalesced-task-group.ts +64 -13
  109. package/src/runtime/scheduling/task-graph-scheduler.ts +0 -10
  110. package/src/runtime/scratchpad/README.md +10 -5
  111. package/src/runtime/scratchpad/guest.ts +103 -2
  112. package/src/runtime/scratchpad/protocol.ts +13 -1
  113. package/src/runtime/scratchpad/transform.ts +206 -12
  114. package/src/runtime/settings-store.ts +219 -0
  115. package/src/runtime/spawn-policy.ts +217 -0
  116. package/src/runtime/stale-reconciler.ts +87 -6
  117. package/src/runtime/subagent-manager.ts +25 -1
  118. package/src/runtime/task-output-context.ts +230 -9
  119. package/src/runtime/task-packet.ts +23 -1
  120. package/src/runtime/task-runner/child-executor.ts +106 -7
  121. package/src/runtime/task-runner/post-execution.ts +125 -1
  122. package/src/runtime/task-runner/pre-execution.ts +39 -1
  123. package/src/runtime/task-runner/prompt-builder.ts +51 -1
  124. package/src/runtime/task-runner/retrieval-orchestrator.ts +72 -18
  125. package/src/runtime/task-runner/spec-evidence.ts +403 -0
  126. package/src/runtime/task-runner/state-helpers.ts +26 -24
  127. package/src/runtime/task-runner.ts +11 -0
  128. package/src/runtime/team-runner.ts +129 -1671
  129. package/src/runtime/verification/spec-sandbox.ts +255 -0
  130. package/src/runtime/verification/verification-gates.ts +3 -2
  131. package/src/runtime/verification/verification-worktree.ts +2 -1
  132. package/src/runtime/workflow-phase-advance.ts +100 -0
  133. package/src/runtime/workspace-tree.ts +9 -0
  134. package/src/schema/config-schema.ts +65 -25
  135. package/src/schema/sensitive-config-paths.ts +64 -0
  136. package/src/schema/team-tool-schema.ts +13 -3
  137. package/src/state/README.md +4 -10
  138. package/src/state/atomic-write.ts +20 -3
  139. package/src/state/contracts.ts +38 -0
  140. package/src/state/coordination/mailbox.ts +12 -2
  141. package/src/state/event-log/cursor.ts +223 -0
  142. package/src/state/event-log/event-log-rotation.ts +12 -4
  143. package/src/state/event-log/event-log.ts +152 -369
  144. package/src/state/event-log/sequence-cache.ts +373 -0
  145. package/src/state/event-log/worker-atomic-writer.ts +2 -1
  146. package/src/state/stores/active-run-registry.ts +3 -2
  147. package/src/state/stores/manifest-io.ts +237 -0
  148. package/src/state/stores/ownership-map.ts +162 -0
  149. package/src/state/stores/plan-store.ts +241 -0
  150. package/src/state/stores/run-cache.ts +0 -90
  151. package/src/state/stores/spec-store.ts +189 -0
  152. package/src/state/stores/state-store.ts +66 -229
  153. package/src/state/types.ts +197 -0
  154. package/src/ui/dashboard-panes/plan-pane.ts +136 -0
  155. package/src/ui/dashboard-panes/progress-pane.ts +6 -0
  156. package/src/ui/dashboard-panes/transcript-pane.ts +31 -0
  157. package/src/ui/heartbeat-aggregator.ts +9 -1
  158. package/src/ui/keybinding-map.ts +54 -13
  159. package/src/ui/powerbar-publisher.ts +52 -1
  160. package/src/ui/run-dashboard.ts +31 -5
  161. package/src/ui/run-snapshot-cache.ts +57 -30
  162. package/src/ui/snapshot-types.ts +6 -1
  163. package/src/ui/widget/widget-renderer.ts +9 -1
  164. package/src/utils/file-coalescer.ts +0 -4
  165. package/src/utils/fs-errno.ts +66 -0
  166. package/src/utils/fs-watch.ts +1 -1
  167. package/src/utils/internal-error.ts +3 -1
  168. package/src/utils/paths.ts +11 -3
  169. package/src/utils/task-name-generator.ts +1 -8
  170. package/src/workflows/discover-workflows.ts +19 -2
  171. package/src/workflows/validate-workflow.ts +7 -1
  172. package/src/workflows/workflow-config.ts +10 -0
  173. package/src/workflows/workflow-serializer.ts +3 -0
  174. package/src/worktree/worktree-manager.ts +22 -0
  175. package/src/agents/agent-search.ts +0 -98
  176. package/src/benchmark/benchmark-runner.ts +0 -313
  177. package/src/benchmark/feedback-loop.ts +0 -73
  178. package/src/config/resilient-parser.ts +0 -117
  179. package/src/extension/crew-vibes/cat-frames.ts +0 -18
  180. package/src/extension/result-watcher.ts +0 -139
  181. package/src/observability/exporters/prometheus-exporter.ts +0 -54
  182. package/src/observability/metric-retention.ts +0 -64
  183. package/src/runtime/compaction/compaction-summary.ts +0 -278
  184. package/src/runtime/errors/crew-errors.ts +0 -162
  185. package/src/runtime/live-session/intercom-bridge.ts +0 -187
  186. package/src/runtime/loop-gates.ts +0 -128
  187. package/src/runtime/metric-parser.ts +0 -36
  188. package/src/runtime/output/stream-preview.ts +0 -184
  189. package/src/runtime/output/tool-progress.ts +0 -278
  190. package/src/runtime/phase-tracker.ts +0 -385
  191. package/src/runtime/pipeline-runner.ts +0 -523
  192. package/src/runtime/process/process-lifecycle.ts +0 -491
  193. package/src/runtime/recovery/retry-runner.ts +0 -330
  194. package/src/runtime/run-drift.ts +0 -219
  195. package/src/runtime/scratchpad/snapshot-hmac.ts +0 -167
  196. package/src/runtime/task-quality.ts +0 -199
  197. package/src/runtime/task-runner/run-projection.ts +0 -128
  198. package/src/runtime/verification/post-checks.ts +0 -142
  199. package/src/state/coordination/schedule.ts +0 -166
  200. package/src/state/event-log/jsonl-writer.ts +0 -115
  201. package/src/state/hook-instinct-bridge.ts +0 -94
  202. package/src/state/hook-integrations.ts +0 -51
  203. package/src/state/session-state-map.ts +0 -51
  204. package/src/state/stores/blob-store.ts +0 -308
  205. package/src/state/stores/instinct-store.ts +0 -275
  206. package/src/state/stores/observation-store.ts +0 -176
  207. package/src/state/tiered-eval.ts +0 -480
  208. package/src/state/types-eval.ts +0 -58
  209. package/src/tools/safe-bash-extension.ts +0 -54
  210. package/src/tools/safe-bash.ts +0 -505
  211. package/src/ui/agent-management-overlay.ts +0 -160
  212. package/src/ui/crew-footer.ts +0 -102
  213. package/src/ui/crew-select-list.ts +0 -114
  214. package/src/ui/dashboard-panes/capability-pane.ts +0 -77
  215. package/src/ui/transcript-entries.ts +0 -256
  216. package/src/utils/conflict-detect.ts +0 -721
  217. package/src/utils/fingerprint.ts +0 -180
  218. package/src/utils/gh-protocol.ts +0 -556
  219. package/src/utils/project-detector.ts +0 -160
  220. package/src/utils/sse-parser.ts +0 -131
  221. package/src/workflows/cost-estimator.ts +0 -34
  222. package/src/workflows/intermediate-store.ts +0 -166
@@ -1,721 +0,0 @@
1
- /**
2
- * conflict-detect.ts — Detect and resolve git merge conflicts.
3
- *
4
- * Forked from oh-my-pi packages/coding-agent/src/tools/conflict-detect.ts
5
- * with adaptations for pi-crew's needs.
6
- *
7
- * Workflow:
8
- * 1. `read` collects lines from disk as usual.
9
- * 2. `scanConflictLines` inspects those lines (no extra I/O) for
10
- * well-formed `<<<<<<<` / `=======` / `>>>>>>>` blocks.
11
- * 3. Each completed block is registered with the `ConflictHistory`,
12
- * which assigns it a stable id.
13
- * 4. The read output is returned verbatim with a short footer naming
14
- * every conflict id surfaced, and the agent calls
15
- * `write({ path: "conflict://<id>", content })` to splice the
16
- * recorded region with the chosen content.
17
- *
18
- * Marker shape is strict: only column-0 markers of the exact prefix length
19
- * followed by either EOL or a single space + label. Lines that
20
- * merely start with `<` or `=` never match.
21
- */
22
- import * as fs from "node:fs";
23
-
24
- const OURS_PREFIX = "<<<<<<<";
25
- const BASE_PREFIX = "|||||||";
26
- const SEPARATOR = "=======";
27
- const THEIRS_PREFIX = ">>>>>>>";
28
-
29
- export interface ConflictBlock {
30
- /** 1-indexed line of the `<<<<<<<` marker. */
31
- startLine: number;
32
- /** 1-indexed line of the `=======` separator. */
33
- separatorLine: number;
34
- /** 1-indexed line of `>>>>>>>` marker. */
35
- endLine: number;
36
- /** 1-indexed line of `|||||||` base marker (diff3 only). */
37
- baseLine?: number;
38
- oursLabel?: string;
39
- baseLabel?: string;
40
- theirsLabel?: string;
41
- oursLines: string[];
42
- baseLines?: string[];
43
- theirsLines: string[];
44
- }
45
-
46
- /**
47
- * Scan an already-collected array of file lines for completed conflict
48
- * blocks. `firstLineNumber` is the 1-indexed line number of `lines[0]`
49
- * (so a windowed read starting at line 200 passes `firstLineNumber: 200`).
50
- *
51
- * Only fully-closed blocks (opener + separator + closer all present in
52
- * the window) are returned. A block whose closer is past the window's
53
- * tail is dropped — the agent will see the open marker and can widen
54
- * the read.
55
- */
56
- export function scanConflictLines(lines: readonly string[], firstLineNumber: number): ConflictBlock[] {
57
- const blocks: ConflictBlock[] = [];
58
- let phase: "idle" | "ours" | "base" | "theirs" = "idle";
59
- let partial: {
60
- startLine: number;
61
- oursLabel?: string;
62
- oursLines: string[];
63
- baseLine?: number;
64
- baseLabel?: string;
65
- baseLines?: string[];
66
- separatorLine?: number;
67
- theirsLines?: string[];
68
- } | null = null;
69
-
70
- for (let i = 0; i < lines.length; i++) {
71
- // Strip a trailing CR so CRLF files (Windows) match markers/separators.
72
- // The raw line (with CR) is never needed here; content is collected from
73
- // the normalized line so storage stays consistent across LF/CRLF inputs.
74
- const rawLine = lines[i];
75
- const line = rawLine.charCodeAt(rawLine.length - 1) === 13 /* \r */ ? rawLine.slice(0, -1) : rawLine;
76
- const ln = firstLineNumber + i;
77
-
78
- const oursLabel = matchMarker(line, OURS_PREFIX);
79
- if (oursLabel !== null) {
80
- partial = {
81
- startLine: ln,
82
- oursLabel: oursLabel || undefined,
83
- oursLines: [],
84
- };
85
- phase = "ours";
86
- continue;
87
- }
88
-
89
- if (phase === "idle" || partial === null) continue;
90
-
91
- const baseLabel = matchMarker(line, BASE_PREFIX);
92
- if (baseLabel !== null) {
93
- if (phase !== "ours") {
94
- partial = null;
95
- phase = "idle";
96
- continue;
97
- }
98
- partial.baseLine = ln;
99
- partial.baseLabel = baseLabel || undefined;
100
- partial.baseLines = [];
101
- phase = "base";
102
- continue;
103
- }
104
-
105
- if (line === SEPARATOR) {
106
- if (phase === "ours" || phase === "base") {
107
- partial.separatorLine = ln;
108
- partial.theirsLines = [];
109
- phase = "theirs";
110
- } else if (phase === "theirs" && partial?.theirsLines) {
111
- // ======= inside theirs content — treat as content, not marker
112
- partial.theirsLines.push(line);
113
- } else {
114
- partial = null;
115
- phase = "idle";
116
- }
117
- continue;
118
- }
119
-
120
- const theirsLabel = matchMarker(line, THEIRS_PREFIX);
121
- if (theirsLabel !== null) {
122
- if (phase === "theirs" && partial.separatorLine !== undefined && partial.theirsLines) {
123
- blocks.push({
124
- startLine: partial.startLine,
125
- separatorLine: partial.separatorLine,
126
- endLine: ln,
127
- baseLine: partial.baseLine,
128
- oursLabel: partial.oursLabel,
129
- baseLabel: partial.baseLabel,
130
- theirsLabel: theirsLabel || undefined,
131
- oursLines: partial.oursLines,
132
- baseLines: partial.baseLines,
133
- theirsLines: partial.theirsLines,
134
- });
135
- }
136
- partial = null;
137
- phase = "idle";
138
- continue;
139
- }
140
-
141
- if (phase === "ours") partial.oursLines.push(line);
142
- else if (phase === "base" && partial.baseLines) partial.baseLines.push(line);
143
- else if (phase === "theirs" && partial.theirsLines) partial.theirsLines.push(line);
144
- }
145
-
146
- return blocks;
147
- }
148
-
149
- const SCAN_FILE_DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
150
-
151
- /**
152
- * Scan a whole file for unresolved conflict blocks.
153
- *
154
- * Reads at most `maxBytes` (default 10 MB) so this stays cheap on
155
- * pathological files. Files truncated by the cap report
156
- * `scanTruncated: true`; only complete blocks within the scanned prefix
157
- * are returned, so trailing partial markers never invent fake blocks.
158
- */
159
- export async function scanFileForConflicts(
160
- absolutePath: string,
161
- options: { maxBytes?: number } = {},
162
- ): Promise<{ blocks: ConflictBlock[]; scanTruncated: boolean }> {
163
- return scanFileForConflictsSync(absolutePath, options);
164
- }
165
-
166
- /**
167
- * Synchronous version of scanFileForConflicts.
168
- */
169
- export function scanFileForConflictsSync(
170
- absolutePath: string,
171
- options: { maxBytes?: number } = {},
172
- ): { blocks: ConflictBlock[]; scanTruncated: boolean } {
173
- const maxBytes = options.maxBytes ?? SCAN_FILE_DEFAULT_MAX_BYTES;
174
- let text: string;
175
- let scanTruncated = false;
176
- try {
177
- const stat = fs.statSync(absolutePath);
178
- if (stat.size > maxBytes) {
179
- scanTruncated = true;
180
- const fd = fs.openSync(absolutePath, "r");
181
- try {
182
- const buf = Buffer.alloc(maxBytes);
183
- fs.readSync(fd, buf, 0, maxBytes, 0);
184
- text = new TextDecoder("utf-8", { fatal: false }).decode(buf);
185
- } finally {
186
- fs.closeSync(fd);
187
- }
188
- } else {
189
- text = fs.readFileSync(absolutePath, "utf-8");
190
- }
191
- } catch {
192
- return { blocks: [], scanTruncated: false };
193
- }
194
- const lines = text.split("\n");
195
- return { blocks: scanConflictLines(lines, 1), scanTruncated };
196
- }
197
-
198
- /**
199
- * Return the label after a marker prefix when the line is a valid
200
- * column-0 marker, or `null` when it isn't. Strict shape: prefix alone,
201
- * or prefix + single space + label.
202
- */
203
- function matchMarker(line: string, prefix: string): string | null {
204
- if (!line.startsWith(prefix)) return null;
205
- if (line.length === prefix.length) return "";
206
- if (line.charCodeAt(prefix.length) !== 32 /* space */) return null;
207
- return line.slice(prefix.length + 1);
208
- }
209
-
210
- /**
211
- * Recorded conflict block keyed by a session-stable id. The history is
212
- * append-only; ids stay valid even after later writes resolve other
213
- * blocks in the same file, so retries don't depend on re-reading.
214
- */
215
- export interface ConflictEntry extends ConflictBlock {
216
- id: number;
217
- absolutePath: string;
218
- displayPath: string;
219
- }
220
-
221
- /** Per-session log of conflict regions surfaced by `read`. */
222
- export class ConflictHistory {
223
- #nextId = 1;
224
- #entries = new Map<number, ConflictEntry>();
225
-
226
- /**
227
- * Register a conflict block. Returns the (possibly pre-existing) entry
228
- * — if the same `absolutePath`+`startLine` was registered before, the
229
- * earlier id is reused so a re-read does not inflate the counter or
230
- * orphan the prior id. The recorded region is overwritten on re-read
231
- * so the splice always reflects the current marker positions on disk.
232
- */
233
- register(input: Omit<ConflictEntry, "id">): ConflictEntry {
234
- for (const existing of this.#entries.values()) {
235
- if (existing.absolutePath === input.absolutePath && existing.startLine === input.startLine) {
236
- const merged: ConflictEntry = { ...input, id: existing.id };
237
- this.#entries.set(existing.id, merged);
238
- return merged;
239
- }
240
- }
241
- const id = this.#nextId++;
242
- const entry: ConflictEntry = { ...input, id };
243
- this.#entries.set(id, entry);
244
- return entry;
245
- }
246
-
247
- get(id: number): ConflictEntry | undefined {
248
- return this.#entries.get(id);
249
- }
250
-
251
- /** Snapshot every registered entry in insertion (id) order. */
252
- entries(): ConflictEntry[] {
253
- return [...this.#entries.values()];
254
- }
255
-
256
- /** Drop a single entry by id. Used after a successful resolve. */
257
- invalidate(id: number): void {
258
- this.#entries.delete(id);
259
- }
260
-
261
- /** Drop every entry referencing `absolutePath`. Used after a successful resolve. */
262
- invalidatePath(absolutePath: string): void {
263
- for (const [id, entry] of this.#entries) {
264
- if (entry.absolutePath === absolutePath) {
265
- this.#entries.delete(id);
266
- }
267
- }
268
- }
269
-
270
- /** Number of registered conflicts. */
271
- get size(): number {
272
- return this.#entries.size;
273
- }
274
- }
275
-
276
- /** A side of a conflict block that the `read` tool can render via `conflict://N/<scope>`. */
277
- export type ConflictScope = "ours" | "theirs" | "base";
278
-
279
- const CONFLICT_SCOPES = new Set<ConflictScope>(["ours", "theirs", "base"]);
280
-
281
- /** Parsed `conflict://<N>` / `conflict://<N>/<scope>` / `conflict://*` URI. */
282
- export interface ParsedConflictUri {
283
- /** `"*"` selects every currently-registered conflict (bulk write only). */
284
- id: number | "*";
285
- scope?: ConflictScope;
286
- }
287
-
288
- const CONFLICT_URI_RE = /^conflict:\/\/(.+)$/;
289
-
290
- /**
291
- * Parse a `conflict://<N>`, `conflict://<N>/<scope>`, or `conflict://*` URI.
292
- *
293
- * Returns `null` for non-conflict paths; throws for a well-formed scheme
294
- * with an invalid id or scope.
295
- *
296
- * `*` is the bulk-write wildcard — only valid as `conflict://*` (no
297
- * scope segment).
298
- */
299
- export function parseConflictUri(raw: string): ParsedConflictUri | null {
300
- const match = raw.match(CONFLICT_URI_RE);
301
- if (!match) return null;
302
- const tail = match[1];
303
- const slashIdx = tail.indexOf("/");
304
- const idPart = slashIdx === -1 ? tail : tail.slice(0, slashIdx);
305
- const scopePart = slashIdx === -1 ? undefined : tail.slice(slashIdx + 1);
306
-
307
- if (idPart === "*") {
308
- if (scopePart !== undefined) {
309
- throw new Error(
310
- `Invalid conflict URI '${raw}': wildcard 'conflict://*' does not accept a scope segment. Drop '/${scopePart}' or use a numeric id.`,
311
- );
312
- }
313
- return { id: "*" };
314
- }
315
-
316
- if (!/^\d+$/.test(idPart)) {
317
- throw new Error(
318
- `Invalid conflict URI '${raw}': must be 'conflict://<N>', 'conflict://<N>/<scope>', or 'conflict://*' where N is a positive integer surfaced by a prior read.`,
319
- );
320
- }
321
- const id = Number.parseInt(idPart, 10);
322
- if (!Number.isFinite(id) || id < 1) {
323
- throw new Error(`Invalid conflict URI '${raw}': id must be ≥ 1.`);
324
- }
325
-
326
- let scope: ConflictScope | undefined;
327
- if (scopePart !== undefined) {
328
- if (!CONFLICT_SCOPES.has(scopePart as ConflictScope)) {
329
- throw new Error(`Invalid conflict URI '${raw}': scope must be one of 'ours', 'theirs', 'base', or omitted.`);
330
- }
331
- scope = scopePart as ConflictScope;
332
- }
333
-
334
- return { id, scope };
335
- }
336
-
337
- /**
338
- * Splice the conflict region recorded in `entry` out of `originalText`
339
- * and replace it with `replacement` (markers and all sides included).
340
- *
341
- * Works by locating the recorded marker block by content (anchored to
342
- * `entry.startLine` as the preferred match), so out-of-band edits earlier
343
- * in the file that shift line numbers don't break resolution.
344
- *
345
- * EOL preservation: lines are split keeping each line's original ending
346
- * bytes (CRLF / LF / none). Only the conflicting region is rewritten; every
347
- * other line is round-tripped byte-for-byte, so a mixed-EOL file produces a
348
- * minimal git diff (previously every line ending was normalised, rewriting
349
- * the whole file even when only a few lines conflicted).
350
- */
351
- export function spliceConflict(originalText: string, entry: ConflictEntry, replacement: string): string {
352
- // Split preserving each line's original EOL so non-conflicting lines are
353
- // round-tripped byte-for-byte (minimal git diff on mixed-EOL files).
354
- const segments = splitPreservingEol(originalText);
355
- // Content-only view (CR stripped) — identical to the old `split(/\r?\n/)`,
356
- // so conflict detection / region matching behaviour is unchanged.
357
- const lines = segments.map((s) => s.content);
358
- const expected = buildRecordedRegion(entry);
359
- const match = locateRegion(lines, expected, entry.startLine - 1);
360
- if (!match) {
361
- throw new Error(
362
- `Conflict #${entry.id} no longer present in '${entry.displayPath}': the recorded marker block can't be located. The file changed since the conflict was registered — re-read it to re-register conflicts.`,
363
- );
364
- }
365
-
366
- const trimmed = normalizeTrailingNewline(replacement);
367
- const replacementLines = trimmed.split("\n");
368
- // EOL for the inserted lines: prefer the EOL that originally terminated the
369
- // conflict region (local style); fall back to the file's dominant EOL.
370
- const regionEol = segments[match.endIdx]?.eol ?? "";
371
- const interEol = regionEol || (originalText.includes("\r\n") ? "\r\n" : "\n");
372
-
373
- const out: string[] = [];
374
- // Lines before the conflict — verbatim (original content + original EOL).
375
- for (let i = 0; i < match.startIdx; i++) out.push(segments[i].content, segments[i].eol);
376
- // Replacement lines — intermediate ones use the local EOL; the final one
377
- // reuses the boundary EOL that originally separated the region from the
378
- // following line, preserving that line's leading boundary exactly.
379
- for (let i = 0; i < replacementLines.length; i++) {
380
- out.push(replacementLines[i]);
381
- out.push(i < replacementLines.length - 1 ? interEol : regionEol);
382
- }
383
- // Lines after the conflict — verbatim.
384
- for (let i = match.endIdx + 1; i < segments.length; i++) out.push(segments[i].content, segments[i].eol);
385
- return out.join("");
386
- }
387
-
388
- /**
389
- * Split `text` into `{ content, eol }` segments keeping each line's exact
390
- * ending bytes. The `content` view equals `text.split(/\r?\n/)`, but the
391
- * original EOL (`"\r\n"`, `"\n"`, or `""` for the final line) is retained
392
- * so callers can reconstruct the text byte-for-byte.
393
- */
394
- function splitPreservingEol(text: string): { content: string; eol: string }[] {
395
- const segments: { content: string; eol: string }[] = [];
396
- const n = text.length;
397
- let i = 0;
398
- while (i <= n) {
399
- const nl = text.indexOf("\n", i);
400
- if (nl === -1) {
401
- segments.push({ content: text.slice(i), eol: "" });
402
- break;
403
- }
404
- let contentEnd = nl;
405
- let eol = "\n";
406
- if (nl > 0 && text.charCodeAt(nl - 1) === 13 /* \r */) {
407
- contentEnd = nl - 1;
408
- eol = "\r\n";
409
- }
410
- segments.push({ content: text.slice(i, contentEnd), eol });
411
- i = nl + 1;
412
- }
413
- return segments;
414
- }
415
-
416
- /** Reconstruct the recorded marker block as it should appear in the file. */
417
- function buildRecordedRegion(entry: ConflictEntry): string[] {
418
- const out: string[] = [];
419
- out.push(entry.oursLabel ? `${OURS_PREFIX} ${entry.oursLabel}` : OURS_PREFIX);
420
- out.push(...entry.oursLines);
421
- if (entry.baseLines !== undefined) {
422
- out.push(entry.baseLabel ? `${BASE_PREFIX} ${entry.baseLabel}` : BASE_PREFIX);
423
- out.push(...entry.baseLines);
424
- }
425
- out.push(SEPARATOR);
426
- out.push(...entry.theirsLines);
427
- out.push(entry.theirsLabel ? `${THEIRS_PREFIX} ${entry.theirsLabel}` : THEIRS_PREFIX);
428
- return out;
429
- }
430
-
431
- function locateRegion(
432
- lines: readonly string[],
433
- expected: readonly string[],
434
- preferredIdx: number,
435
- ): { startIdx: number; endIdx: number } | null {
436
- if (expected.length === 0 || expected.length > lines.length) return null;
437
- // Fast path: try the recorded position first.
438
- if (preferredIdx >= 0 && matchesAt(lines, preferredIdx, expected)) {
439
- return {
440
- startIdx: preferredIdx,
441
- endIdx: preferredIdx + expected.length - 1,
442
- };
443
- }
444
- let best: number | null = null;
445
- let bestDist = Number.POSITIVE_INFINITY;
446
- const limit = lines.length - expected.length;
447
- for (let i = 0; i <= limit; i++) {
448
- if (!matchesAt(lines, i, expected)) continue;
449
- const dist = Math.abs(i - preferredIdx);
450
- if (dist < bestDist) {
451
- best = i;
452
- bestDist = dist;
453
- }
454
- }
455
- if (best === null) return null;
456
- return { startIdx: best, endIdx: best + expected.length - 1 };
457
- }
458
-
459
- function matchesAt(lines: readonly string[], startIdx: number, expected: readonly string[]): boolean {
460
- if (startIdx < 0 || startIdx + expected.length > lines.length) return false;
461
- for (let i = 0; i < expected.length; i++) {
462
- if (lines[startIdx + i] !== expected[i]) return false;
463
- }
464
- return true;
465
- }
466
-
467
- function normalizeTrailingNewline(replacement: string): string {
468
- if (replacement.endsWith("\r\n")) return replacement.slice(0, -2);
469
- if (replacement.endsWith("\n")) return replacement.slice(0, -1);
470
- return replacement;
471
- }
472
-
473
- /**
474
- * Expand `@ours` / `@theirs` / `@base` / `@both` line tokens against the
475
- * recorded sections of `entry`. A token only triggers when it is the
476
- * entire content of a line (after CRLF normalisation), so `@ours` inside
477
- * actual code is left alone. Other lines pass through verbatim.
478
- *
479
- * - `@ours` → expands to the recorded `oursLines`
480
- * - `@theirs` → expands to the recorded `theirsLines`
481
- * - `@base` → expands to `baseLines`; throws if no base section
482
- * - `@both` → expands to `oursLines` then `theirsLines`
483
- */
484
- export function expandContentTokens(content: string, entry: ConflictEntry): string {
485
- const inputLines = content.split("\n");
486
- const out: string[] = [];
487
- for (const rawLine of inputLines) {
488
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
489
- switch (line) {
490
- case "@ours":
491
- out.push(...entry.oursLines);
492
- break;
493
- case "@theirs":
494
- out.push(...entry.theirsLines);
495
- break;
496
- case "@base":
497
- if (!entry.baseLines) {
498
- throw new Error(
499
- `Conflict #${entry.id} has no base section (2-way merge). \`@base\` is only valid for diff3 conflicts.`,
500
- );
501
- }
502
- out.push(...entry.baseLines);
503
- break;
504
- case "@both":
505
- out.push(...entry.oursLines, ...entry.theirsLines);
506
- break;
507
- default:
508
- out.push(rawLine);
509
- break;
510
- }
511
- }
512
- return out.join("\n");
513
- }
514
-
515
- /** Reconstruct a conflict-marker line from prefix and optional label. */
516
- function markerLine(prefix: string, label: string | undefined): string {
517
- return label && label.length > 0 ? `${prefix} ${label}` : prefix;
518
- }
519
-
520
- /**
521
- * Materialise a conflict block for `conflict://<N>` reads (and their
522
- * `/ours` / `/theirs` / `/base` scopes).
523
- *
524
- * Returns:
525
- * - `lines`: the lines to render, ordered top-to-bottom.
526
- * - `startLine`: the 1-indexed file line number `lines[0]` corresponds
527
- * to, so the read formatter can label hashline anchors.
528
- */
529
- export function renderConflictRegion(entry: ConflictEntry, scope: ConflictScope | undefined): { lines: string[]; startLine: number } {
530
- if (scope === "ours") {
531
- return { lines: [...entry.oursLines], startLine: entry.startLine + 1 };
532
- }
533
- if (scope === "theirs") {
534
- return {
535
- lines: [...entry.theirsLines],
536
- startLine: entry.separatorLine + 1,
537
- };
538
- }
539
- if (scope === "base") {
540
- if (entry.baseLines === undefined || entry.baseLine === undefined) {
541
- throw new Error(
542
- `Conflict #${entry.id} has no base section (2-way merge). 'conflict://${entry.id}/base' is only valid for diff3 conflicts.`,
543
- );
544
- }
545
- return { lines: [...entry.baseLines], startLine: entry.baseLine + 1 };
546
- }
547
- const out: string[] = [];
548
- out.push(markerLine("<<<<<<<", entry.oursLabel));
549
- out.push(...entry.oursLines);
550
- if (entry.baseLines !== undefined) {
551
- out.push(markerLine("|||||||", entry.baseLabel));
552
- out.push(...entry.baseLines);
553
- }
554
- out.push("=======");
555
- out.push(...entry.theirsLines);
556
- out.push(markerLine(">>>>>>>", entry.theirsLabel));
557
- return { lines: out, startLine: entry.startLine };
558
- }
559
-
560
- const PREVIEW_SIDE_LINES = 6;
561
-
562
- function pickLabel(entries: readonly ConflictEntry[], get: (e: ConflictEntry) => string | undefined): string | undefined {
563
- for (const e of entries) {
564
- const label = get(e);
565
- if (label && label.trim().length > 0) return label;
566
- }
567
- return undefined;
568
- }
569
-
570
- function sectionsEqual(a: readonly string[], b: readonly string[]): boolean {
571
- if (a.length !== b.length) return false;
572
- for (let i = 0; i < a.length; i++) {
573
- if (a[i] !== b[i]) return false;
574
- }
575
- return true;
576
- }
577
-
578
- function appendBody(out: string[], section: readonly string[]): void {
579
- if (section.length === 0) {
580
- out.push("(empty)");
581
- return;
582
- }
583
- const shown = section.slice(0, PREVIEW_SIDE_LINES);
584
- for (const line of shown) out.push(line);
585
- const hidden = section.length - shown.length;
586
- if (hidden > 0) out.push(`… (${hidden} more line${hidden === 1 ? "" : "s"})`);
587
- }
588
-
589
- export interface FormatConflictWarningOptions {
590
- /** Total number of conflicts in the underlying file. */
591
- totalInFile?: number;
592
- /** Display path used inside the `:conflicts` hint. */
593
- displayPath?: string;
594
- /** Whether the underlying file scan hit its byte cap. */
595
- scanTruncated?: boolean;
596
- }
597
-
598
- /**
599
- * Build a compact diff-style footer describing the conflicts registered
600
- * during a read. Designed to be appended after the file content.
601
- *
602
- * Format:
603
- *
604
- * ⚠ N unresolved conflicts detected
605
- * - ours = HEAD
606
- * - theirs = feature/x
607
- * NOTICE: …
608
- *
609
- * ──── #1 L42-48 ────
610
- * <<< ours
611
- * …ours body…
612
- * === base ≡ ours
613
- * >>> theirs
614
- * …theirs body…
615
- */
616
- export function formatConflictWarning(entries: readonly ConflictEntry[], options: FormatConflictWarningOptions = {}): string {
617
- if (entries.length === 0) return "";
618
- const total = options.totalInFile ?? entries.length;
619
- const partial = total > entries.length;
620
- const out: string[] = [];
621
- out.push("");
622
- const word = total === 1 ? "conflict" : "conflicts";
623
- if (partial) {
624
- const hintPath = options.displayPath ?? "<file>";
625
- out.push(
626
- `⚠ ${entries.length} of ${total} unresolved ${word} visible in this window (read \`${hintPath}:conflicts\` for the full list).`,
627
- );
628
- } else {
629
- out.push(`⚠ ${total} unresolved ${word} detected`);
630
- }
631
- if (options.scanTruncated) {
632
- out.push("- note: file scan hit the byte cap; additional conflicts may exist beyond the scanned prefix.");
633
- }
634
-
635
- const oursLabel = pickLabel(entries, (e) => e.oursLabel);
636
- const theirsLabel = pickLabel(entries, (e) => e.theirsLabel);
637
- const baseLabel = pickLabel(entries, (e) => (e.baseLines !== undefined ? e.baseLabel : undefined));
638
- const anyBase = entries.some((e) => e.baseLines !== undefined);
639
- if (oursLabel) out.push(`- ours = ${oursLabel}`);
640
- if (theirsLabel) out.push(`- theirs = ${theirsLabel}`);
641
- if (anyBase) out.push(`- base = ${baseLabel ?? "(no label)"}`);
642
- out.push(
643
- 'NOTICE: Inspect a block by reading `conflict://<N>` (add `/ours` / `/theirs` / `/base` to render a single side). Resolve with `write({ path: "conflict://<N>", content })`, or bulk-resolve every registered conflict with `write({ path: "conflict://*", content })`.',
644
- );
645
- out.push(
646
- "`content` shorthand: a line that is exactly `@ours` / `@theirs` / `@base` / `@both` expands to that recorded section. Non-token lines pass through verbatim.",
647
- );
648
-
649
- for (const entry of entries) {
650
- const range = entry.startLine === entry.endLine ? `L${entry.startLine}` : `L${entry.startLine}-${entry.endLine}`;
651
- out.push("");
652
- out.push(`──── #${entry.id} ${range} ────`);
653
-
654
- const baseEqualsOurs = entry.baseLines !== undefined && sectionsEqual(entry.baseLines, entry.oursLines);
655
- const baseEqualsTheirs = entry.baseLines !== undefined && sectionsEqual(entry.baseLines, entry.theirsLines);
656
- const theirsEqualsOurs = sectionsEqual(entry.theirsLines, entry.oursLines);
657
-
658
- out.push("<<< ours");
659
- appendBody(out, entry.oursLines);
660
-
661
- if (entry.baseLines !== undefined) {
662
- if (baseEqualsOurs) {
663
- out.push("=== base ≡ ours");
664
- } else if (baseEqualsTheirs) {
665
- out.push("=== base ≡ theirs");
666
- } else {
667
- out.push("=== base");
668
- appendBody(out, entry.baseLines);
669
- }
670
- }
671
-
672
- if (theirsEqualsOurs) {
673
- out.push(">>> theirs ≡ ours");
674
- } else {
675
- out.push(">>> theirs");
676
- appendBody(out, entry.theirsLines);
677
- }
678
- }
679
- return out.join("\n");
680
- }
681
-
682
- /**
683
- * Render a single-line-per-block index of every conflict in a file.
684
- * Used by `<path>:conflicts` selector.
685
- */
686
- export function formatConflictSummary(
687
- entries: readonly ConflictEntry[],
688
- options: { displayPath: string; scanTruncated?: boolean } = {
689
- displayPath: "",
690
- },
691
- ): string {
692
- const lines: string[] = [];
693
- const total = entries.length;
694
- const word = total === 1 ? "conflict" : "conflicts";
695
- lines.push(`⚠ ${total} unresolved ${word} in ${options.displayPath || "<file>"}`);
696
- if (options.scanTruncated) {
697
- lines.push("- note: file scan hit the byte cap; additional conflicts may exist beyond the scanned prefix.");
698
- }
699
- const oursLabel = pickLabel(entries, (e) => e.oursLabel);
700
- const theirsLabel = pickLabel(entries, (e) => e.theirsLabel);
701
- const baseLabel = pickLabel(entries, (e) => (e.baseLines !== undefined ? e.baseLabel : undefined));
702
- const anyBase = entries.some((e) => e.baseLines !== undefined);
703
- if (oursLabel) lines.push(`- ours = ${oursLabel}`);
704
- if (theirsLabel) lines.push(`- theirs = ${theirsLabel}`);
705
- if (anyBase) lines.push(`- base = ${baseLabel ?? "(no label)"}`);
706
- lines.push(
707
- 'NOTICE: Bulk-resolve with `write({ path: "conflict://*", content })`, or address a single block with `write({ path: "conflict://<N>", content })`.',
708
- );
709
- lines.push(
710
- "`content` shorthand: `@ours` / `@theirs` / `@base` / `@both` lines expand to the recorded sections. Non-token lines pass through verbatim.",
711
- );
712
- lines.push("");
713
- const idWidth = String(entries[entries.length - 1]?.id ?? 1).length;
714
- for (const entry of entries) {
715
- const range = entry.startLine === entry.endLine ? `L${entry.startLine}` : `L${entry.startLine}-${entry.endLine}`;
716
- const idCell = `#${String(entry.id).padStart(idWidth, " ")}`;
717
- const kind = entry.baseLines !== undefined ? " (3-way)" : "";
718
- lines.push(`${idCell} ${range}${kind}`);
719
- }
720
- return lines.join("\n");
721
- }