@abelxiaoxing/cadence 1.8.4 → 2.0.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 (202) hide show
  1. package/README.md +324 -117
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/agents/design-explorer.md +14 -18
  4. package/agents/diagnosis-worker.md +14 -14
  5. package/agents/implementation-worker.md +16 -17
  6. package/config/workflow-task.example.json +7 -0
  7. package/docs/remote-access.md +60 -0
  8. package/docs/reuse-and-distribution.md +44 -0
  9. package/docs/service-management.md +108 -0
  10. package/licenses/bundled-web.txt +6245 -0
  11. package/licenses/pi-web-ui-MIT.txt +21 -0
  12. package/licenses/pi-web-ui-reuse.md +22 -0
  13. package/package.json +94 -21
  14. package/src/index.ts +21 -1802
  15. package/src/native-build.ts +6 -0
  16. package/src/native-client.ts +103 -0
  17. package/src/native-export.ts +58 -0
  18. package/src/native-history.ts +359 -0
  19. package/src/operator-cli.mjs +453 -1937
  20. package/src/plan-proposal.ts +87 -0
  21. package/src/sdk-worker.mjs +549 -0
  22. package/src/service/contracts/active.ts +82 -0
  23. package/src/service/contracts/budget.ts +148 -0
  24. package/src/service/contracts/build.ts +67 -0
  25. package/src/service/contracts/capture.ts +48 -0
  26. package/src/service/contracts/core.ts +33 -0
  27. package/src/service/contracts/current.ts +261 -0
  28. package/src/service/contracts/domain.ts +68 -0
  29. package/src/service/contracts/history.ts +2245 -0
  30. package/src/service/contracts/models.ts +139 -0
  31. package/src/service/coordination.ts +862 -0
  32. package/src/service/private-files.ts +204 -0
  33. package/src/service-cli.mjs +5592 -0
  34. package/src/service-client.ts +747 -0
  35. package/src/service-contract.ts +245 -0
  36. package/src/service-host.mjs +22382 -0
  37. package/src/service-http-client.ts +425 -0
  38. package/src/service-wire.ts +372 -0
  39. package/src/task-shell.ts +1045 -0
  40. package/src/task-store.ts +479 -0
  41. package/src/task-types.ts +184 -0
  42. package/src/verification-diagnostics.ts +29 -72
  43. package/src/worker-capture.mjs +1197 -0
  44. package/src/worker-public.mjs +1753 -0
  45. package/src/worker-redaction.mjs +608 -0
  46. package/src/worker-tools.mjs +202 -0
  47. package/web/dist/assets/KaTeX_AMS-Regular.ttf +0 -0
  48. package/web/dist/assets/KaTeX_AMS-Regular.woff +0 -0
  49. package/web/dist/assets/KaTeX_AMS-Regular.woff2 +0 -0
  50. package/web/dist/assets/KaTeX_Caligraphic-Bold.ttf +0 -0
  51. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff +0 -0
  52. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff2 +0 -0
  53. package/web/dist/assets/KaTeX_Caligraphic-Regular.ttf +0 -0
  54. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff +0 -0
  55. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff2 +0 -0
  56. package/web/dist/assets/KaTeX_Fraktur-Bold.ttf +0 -0
  57. package/web/dist/assets/KaTeX_Fraktur-Bold.woff +0 -0
  58. package/web/dist/assets/KaTeX_Fraktur-Bold.woff2 +0 -0
  59. package/web/dist/assets/KaTeX_Fraktur-Regular.ttf +0 -0
  60. package/web/dist/assets/KaTeX_Fraktur-Regular.woff +0 -0
  61. package/web/dist/assets/KaTeX_Fraktur-Regular.woff2 +0 -0
  62. package/web/dist/assets/KaTeX_Main-Bold.ttf +0 -0
  63. package/web/dist/assets/KaTeX_Main-Bold.woff +0 -0
  64. package/web/dist/assets/KaTeX_Main-Bold.woff2 +0 -0
  65. package/web/dist/assets/KaTeX_Main-BoldItalic.ttf +0 -0
  66. package/web/dist/assets/KaTeX_Main-BoldItalic.woff +0 -0
  67. package/web/dist/assets/KaTeX_Main-BoldItalic.woff2 +0 -0
  68. package/web/dist/assets/KaTeX_Main-Italic.ttf +0 -0
  69. package/web/dist/assets/KaTeX_Main-Italic.woff +0 -0
  70. package/web/dist/assets/KaTeX_Main-Italic.woff2 +0 -0
  71. package/web/dist/assets/KaTeX_Main-Regular.ttf +0 -0
  72. package/web/dist/assets/KaTeX_Main-Regular.woff +0 -0
  73. package/web/dist/assets/KaTeX_Main-Regular.woff2 +0 -0
  74. package/web/dist/assets/KaTeX_Math-BoldItalic.ttf +0 -0
  75. package/web/dist/assets/KaTeX_Math-BoldItalic.woff +0 -0
  76. package/web/dist/assets/KaTeX_Math-BoldItalic.woff2 +0 -0
  77. package/web/dist/assets/KaTeX_Math-Italic.ttf +0 -0
  78. package/web/dist/assets/KaTeX_Math-Italic.woff +0 -0
  79. package/web/dist/assets/KaTeX_Math-Italic.woff2 +0 -0
  80. package/web/dist/assets/KaTeX_SansSerif-Bold.ttf +0 -0
  81. package/web/dist/assets/KaTeX_SansSerif-Bold.woff +0 -0
  82. package/web/dist/assets/KaTeX_SansSerif-Bold.woff2 +0 -0
  83. package/web/dist/assets/KaTeX_SansSerif-Italic.ttf +0 -0
  84. package/web/dist/assets/KaTeX_SansSerif-Italic.woff +0 -0
  85. package/web/dist/assets/KaTeX_SansSerif-Italic.woff2 +0 -0
  86. package/web/dist/assets/KaTeX_SansSerif-Regular.ttf +0 -0
  87. package/web/dist/assets/KaTeX_SansSerif-Regular.woff +0 -0
  88. package/web/dist/assets/KaTeX_SansSerif-Regular.woff2 +0 -0
  89. package/web/dist/assets/KaTeX_Script-Regular.ttf +0 -0
  90. package/web/dist/assets/KaTeX_Script-Regular.woff +0 -0
  91. package/web/dist/assets/KaTeX_Script-Regular.woff2 +0 -0
  92. package/web/dist/assets/KaTeX_Size1-Regular.ttf +0 -0
  93. package/web/dist/assets/KaTeX_Size1-Regular.woff +0 -0
  94. package/web/dist/assets/KaTeX_Size1-Regular.woff2 +0 -0
  95. package/web/dist/assets/KaTeX_Size2-Regular.ttf +0 -0
  96. package/web/dist/assets/KaTeX_Size2-Regular.woff +0 -0
  97. package/web/dist/assets/KaTeX_Size2-Regular.woff2 +0 -0
  98. package/web/dist/assets/KaTeX_Size3-Regular.ttf +0 -0
  99. package/web/dist/assets/KaTeX_Size3-Regular.woff +0 -0
  100. package/web/dist/assets/KaTeX_Size3-Regular.woff2 +0 -0
  101. package/web/dist/assets/KaTeX_Size4-Regular.ttf +0 -0
  102. package/web/dist/assets/KaTeX_Size4-Regular.woff +0 -0
  103. package/web/dist/assets/KaTeX_Size4-Regular.woff2 +0 -0
  104. package/web/dist/assets/KaTeX_Typewriter-Regular.ttf +0 -0
  105. package/web/dist/assets/KaTeX_Typewriter-Regular.woff +0 -0
  106. package/web/dist/assets/KaTeX_Typewriter-Regular.woff2 +0 -0
  107. package/web/dist/assets/cadence.css +2 -0
  108. package/web/dist/assets/cadence.js +7 -0
  109. package/web/dist/assets/markdown.js +296 -0
  110. package/web/dist/assets/react.js +9 -0
  111. package/web/dist/assets/rolldown-runtime.js +1 -0
  112. package/web/dist/assets/timeline-client.js +41 -0
  113. package/web/dist/assets/vis-timeline.css +1274 -0
  114. package/web/dist/assets/vis-timeline.js +32 -0
  115. package/web/dist/index.html +18 -0
  116. package/web/dist/manifest.json +505 -0
  117. package/config/plan-draft.example.json +0 -125
  118. package/config/plan-draft.multiple-tasks.example.json +0 -375
  119. package/config/plan-draft.quick.example.json +0 -78
  120. package/prompts/abel-design.md +0 -382
  121. package/prompts/abel-diagnose.md +0 -71
  122. package/prompts/abel-implement.md +0 -284
  123. package/prompts/abel-init.md +0 -52
  124. package/src/activation.ts +0 -44
  125. package/src/activity-contracts.ts +0 -82
  126. package/src/agent-registry.ts +0 -53
  127. package/src/apply-transaction.ts +0 -1437
  128. package/src/artifact-store.ts +0 -213
  129. package/src/build-windows-job.mjs +0 -95
  130. package/src/candidate-artifact.ts +0 -143
  131. package/src/candidate-context.ts +0 -289
  132. package/src/candidate-patch.ts +0 -271
  133. package/src/candidate-workspace.ts +0 -80
  134. package/src/canonical.ts +0 -16
  135. package/src/change-contract-schema.ts +0 -191
  136. package/src/change-contract.ts +0 -324
  137. package/src/change-verification.ts +0 -1617
  138. package/src/contracts.ts +0 -2466
  139. package/src/control-contracts.ts +0 -382
  140. package/src/delivery-compiler.ts +0 -1805
  141. package/src/delivery-revision.ts +0 -42
  142. package/src/design-control.ts +0 -1299
  143. package/src/design-diagnostics.ts +0 -181
  144. package/src/design-journal.ts +0 -1773
  145. package/src/directory-sync.ts +0 -36
  146. package/src/durable-contracts.ts +0 -227
  147. package/src/durable-workflow.ts +0 -822
  148. package/src/evidence-draft.ts +0 -122
  149. package/src/execution-profile.ts +0 -64
  150. package/src/execution-retention.ts +0 -77
  151. package/src/file-snapshot.ts +0 -163
  152. package/src/implement-continuation.ts +0 -559
  153. package/src/implement-graph.ts +0 -690
  154. package/src/implement-plan.ts +0 -72
  155. package/src/install-config.d.mts +0 -6
  156. package/src/isolation-backend.ts +0 -353
  157. package/src/model-source.ts +0 -22
  158. package/src/openspec-cli.ts +0 -494
  159. package/src/operator-cli-entry.mjs +0 -24
  160. package/src/operator-tools.ts +0 -309
  161. package/src/package-candidate-process.ts +0 -206
  162. package/src/package-candidate.ts +0 -24
  163. package/src/package-delivery.ts +0 -486
  164. package/src/package-state.ts +0 -320
  165. package/src/package-verification.ts +0 -635
  166. package/src/package-workflow.ts +0 -305
  167. package/src/packet-runtime.ts +0 -459
  168. package/src/phase-execution.ts +0 -2163
  169. package/src/pi-adapter.ts +0 -19
  170. package/src/plan-draft-summary.ts +0 -527
  171. package/src/plan-draft.ts +0 -502
  172. package/src/remove-path.ts +0 -32
  173. package/src/run-state.ts +0 -420
  174. package/src/run-store.ts +0 -1179
  175. package/src/safe-path.ts +0 -77
  176. package/src/scoped-grep-worker.mjs +0 -23
  177. package/src/scoped-tools.ts +0 -775
  178. package/src/single-task-draft.ts +0 -142
  179. package/src/sqlite-schema.ts +0 -171
  180. package/src/state-root.ts +0 -215
  181. package/src/storage-schema.ts +0 -360
  182. package/src/subagent-activity.ts +0 -1417
  183. package/src/subagent-process.ts +0 -476
  184. package/src/task-ledger.ts +0 -1338
  185. package/src/transport-budget.ts +0 -50
  186. package/src/verification-capability.ts +0 -1191
  187. package/src/verification-environment-io.ts +0 -389
  188. package/src/verification-environment.ts +0 -162
  189. package/src/verification-identity.ts +0 -77
  190. package/src/verification-scan.ts +0 -64
  191. package/src/windows-job-backend.ts +0 -419
  192. package/src/windows-job.c +0 -149
  193. package/src/workflow-engine.ts +0 -28
  194. package/src/workflow-policy.ts +0 -1670
  195. package/src/workflow-recovery-policy.ts +0 -97
  196. package/src/workflow-scheduling.ts +0 -105
  197. package/src/workflow-state-machine.ts +0 -4341
  198. package/src/workflow-status.ts +0 -576
  199. package/src/workspace-io-entry.mjs +0 -76
  200. package/src/workspace-io-worker.mjs +0 -1312
  201. package/src/workspace-io.ts +0 -89
  202. package/src/workspace-store.ts +0 -634
@@ -1,289 +0,0 @@
1
- import { isAgentsPath, isValidRelativePath } from "./contracts.ts";
2
- import type { BeginCandidateInput, TaskLedger } from "./task-ledger.ts";
3
- export type CandidateContextRequestCode =
4
- | "approved-context-needed"
5
- | "task-split-needed"
6
- | "boundary-review-needed";
7
-
8
- export type CandidateContextRef =
9
- | { kind: "requested-path"; path: string; access: "read" | "write" }
10
- | { kind: "source-citation"; path: string; line: number }
11
- | { kind: "contract-diagnostic"; ref: string };
12
-
13
- export type CandidateContextRefInput = string | CandidateContextRef;
14
-
15
- export type CandidateArtifactSubmissionResult =
16
- | {
17
- kind: "sealed-candidate";
18
- candidateId: string;
19
- state: "sealed";
20
- artifactHash: string;
21
- bytes: number;
22
- paths: string[];
23
- replayed?: true;
24
- }
25
- | {
26
- kind: "context-request";
27
- candidateId: string;
28
- code: CandidateContextRequestCode;
29
- refs: CandidateContextRef[];
30
- };
31
-
32
- export type CandidateContextRequest = Extract<
33
- CandidateArtifactSubmissionResult,
34
- { kind: "context-request" }
35
- >;
36
-
37
- export interface CandidateContextBoundary {
38
- phase: "red" | "green" | "refactor";
39
- readPaths: readonly string[];
40
- writePaths: readonly string[];
41
- deletePaths?: readonly string[];
42
- taskPaths: readonly string[];
43
- contextReadRoots?: readonly string[];
44
- redWritePaths: readonly string[];
45
- agents: {
46
- impact: "none" | "update-existing" | "create-index" | "remove-index";
47
- target?: string;
48
- };
49
- }
50
-
51
- export interface ClassifiedCandidateContextRequest {
52
- kind: "paused" | "retryable" | "approval-needed";
53
- code:
54
- | "approved-context-needed"
55
- | "task-split-needed"
56
- | "boundary-review-needed"
57
- | "red-artifact-constraint"
58
- | "agents-context-needed"
59
- | "agents-write-parent-owned"
60
- | "agents-contract-insufficient";
61
- contextRequest: {
62
- code: CandidateContextRequestCode;
63
- refs: CandidateContextRef[];
64
- };
65
- }
66
-
67
- const LEGACY_CITATION = /^(.*):(\d+)$/u;
68
- const LEGACY_DIAGNOSTIC =
69
- /^(?:phase-contract|task-contract|sealed-contract|workflow-contract)\.[a-z0-9._-]+$/iu;
70
-
71
- function validDiagnosticRef(value: unknown): value is string {
72
- return (
73
- typeof value === "string" &&
74
- value.length > 0 &&
75
- value.length <= 512 &&
76
- value.trim() === value &&
77
- !/[\r\n\0]/u.test(value)
78
- );
79
- }
80
-
81
- function normalizeCandidateContextRef(
82
- input: CandidateContextRefInput,
83
- ): CandidateContextRef {
84
- if (typeof input === "string") {
85
- const citation = LEGACY_CITATION.exec(input);
86
- if (citation && isValidRelativePath(citation[1])) {
87
- const line = Number(citation[2]);
88
- if (Number.isSafeInteger(line) && line >= 1) {
89
- return { kind: "source-citation", path: citation[1], line };
90
- }
91
- }
92
- if (LEGACY_DIAGNOSTIC.test(input)) {
93
- return { kind: "contract-diagnostic", ref: input };
94
- }
95
- if (!isValidRelativePath(input)) {
96
- throw new Error("context request refs are invalid");
97
- }
98
- return { kind: "requested-path", path: input, access: "read" };
99
- }
100
- if (!input || typeof input !== "object" || Array.isArray(input)) {
101
- throw new Error("context request refs are invalid");
102
- }
103
- if (
104
- input.kind === "requested-path" &&
105
- Object.keys(input).length === 3 &&
106
- isValidRelativePath(input.path) &&
107
- (input.access === "read" || input.access === "write")
108
- ) {
109
- return { ...input };
110
- }
111
- if (
112
- input.kind === "source-citation" &&
113
- Object.keys(input).length === 3 &&
114
- isValidRelativePath(input.path) &&
115
- Number.isSafeInteger(input.line) &&
116
- input.line >= 1
117
- ) {
118
- return { ...input };
119
- }
120
- if (
121
- input.kind === "contract-diagnostic" &&
122
- Object.keys(input).length === 2 &&
123
- validDiagnosticRef(input.ref)
124
- ) {
125
- return { ...input };
126
- }
127
- throw new Error("context request refs are invalid");
128
- }
129
-
130
- export function normalizeCandidateContextRefs(
131
- value: unknown,
132
- ): CandidateContextRef[] {
133
- if (!Array.isArray(value) || value.length === 0 || value.length > 32) {
134
- throw new Error("context request refs are invalid");
135
- }
136
- const refs = value.map((entry) =>
137
- normalizeCandidateContextRef(entry as CandidateContextRefInput),
138
- );
139
- const identities = refs.map((ref) => JSON.stringify(ref));
140
- if (new Set(identities).size !== refs.length) {
141
- throw new Error("context request refs are invalid");
142
- }
143
- return refs;
144
- }
145
-
146
- function contextRefWithinBoundary(relative: string, approved: string): boolean {
147
- return (
148
- approved === "." ||
149
- relative === approved ||
150
- relative.startsWith(`${approved}/`)
151
- );
152
- }
153
-
154
- function normalizedBoundary(
155
- boundary: readonly string[] | CandidateContextBoundary,
156
- ): CandidateContextBoundary {
157
- if (!Array.isArray(boundary)) return boundary as CandidateContextBoundary;
158
- return {
159
- phase: "green",
160
- readPaths: boundary,
161
- writePaths: [],
162
- deletePaths: [],
163
- taskPaths: boundary,
164
- redWritePaths: [],
165
- agents: { impact: "none" },
166
- };
167
- }
168
-
169
- function pathWithinAny(relative: string, approved: readonly string[]): boolean {
170
- return approved.some((path) => contextRefWithinBoundary(relative, path));
171
- }
172
-
173
- export function permitsContextRead(
174
- relative: string,
175
- roots: readonly string[],
176
- ): boolean {
177
- // Dynamic discovery never grants hidden credentials or a directory tree.
178
- return (
179
- isValidRelativePath(relative) &&
180
- relative.split("/").every((part) => !part.startsWith(".")) &&
181
- !/\.(?:pem|key|p12|pfx)$/iu.test(relative) &&
182
- pathWithinAny(relative, roots)
183
- );
184
- }
185
-
186
- export function classifyCandidateContextRequest(
187
- request: {
188
- kind: "context-request";
189
- candidateId: string;
190
- code: CandidateContextRequestCode;
191
- refs: readonly CandidateContextRefInput[];
192
- },
193
- inputBoundary: readonly string[] | CandidateContextBoundary,
194
- ): ClassifiedCandidateContextRequest {
195
- const refs = normalizeCandidateContextRefs(request.refs);
196
- const boundary = normalizedBoundary(inputBoundary);
197
- const phasePaths = [
198
- ...boundary.readPaths,
199
- ...boundary.writePaths,
200
- ...(boundary.deletePaths ?? []),
201
- ];
202
- const requested = refs.filter(
203
- (ref): ref is Extract<CandidateContextRef, { kind: "requested-path" }> =>
204
- ref.kind === "requested-path",
205
- );
206
- const ordinaryRequested = requested.filter((ref) => !isAgentsPath(ref.path));
207
- const outsideOrdinary = ordinaryRequested.filter(
208
- (ref) =>
209
- !(
210
- ref.access === "read" &&
211
- permitsContextRead(ref.path, boundary.contextReadRoots ?? [])
212
- ) &&
213
- !pathWithinAny(
214
- ref.path,
215
- ref.access === "write"
216
- ? [...boundary.writePaths, ...(boundary.deletePaths ?? [])]
217
- : [...phasePaths, ...boundary.taskPaths],
218
- ),
219
- );
220
- const agentsRequested = requested.filter((ref) => isAgentsPath(ref.path));
221
- const agentsWrites = agentsRequested.filter((ref) => ref.access === "write");
222
- const citedRedArtifacts = refs.filter(
223
- (ref): ref is Extract<CandidateContextRef, { kind: "source-citation" }> =>
224
- ref.kind === "source-citation" &&
225
- pathWithinAny(ref.path, boundary.redWritePaths) &&
226
- !pathWithinAny(ref.path, [
227
- ...boundary.writePaths,
228
- ...(boundary.deletePaths ?? []),
229
- ]),
230
- );
231
- const requestedRedArtifacts = outsideOrdinary.filter(
232
- (ref) =>
233
- pathWithinAny(ref.path, boundary.redWritePaths) &&
234
- pathWithinAny(ref.path, boundary.taskPaths),
235
- );
236
- const redArtifactConstraint =
237
- boundary.phase === "green" &&
238
- (citedRedArtifacts.length > 0 || requestedRedArtifacts.length > 0) &&
239
- outsideOrdinary.every((ref) => requestedRedArtifacts.includes(ref)) &&
240
- agentsRequested.every((ref) => ref.access === "read");
241
-
242
- let classification: Pick<ClassifiedCandidateContextRequest, "kind" | "code">;
243
- if (outsideOrdinary.length > 0 && !redArtifactConstraint) {
244
- classification = {
245
- kind: "approval-needed",
246
- code: "boundary-review-needed",
247
- };
248
- } else if (agentsWrites.length > 0) {
249
- const targetMismatch = agentsWrites.some(
250
- (ref) =>
251
- boundary.agents.impact === "none" ||
252
- boundary.agents.target === undefined ||
253
- ref.path !== boundary.agents.target,
254
- );
255
- classification = targetMismatch
256
- ? { kind: "approval-needed", code: "agents-contract-insufficient" }
257
- : { kind: "paused", code: "agents-write-parent-owned" };
258
- } else if (redArtifactConstraint) {
259
- classification = { kind: "retryable", code: "red-artifact-constraint" };
260
- } else if (agentsRequested.length > 0) {
261
- classification = { kind: "paused", code: "agents-context-needed" };
262
- } else {
263
- classification = {
264
- kind: "retryable",
265
- code:
266
- request.code === "task-split-needed"
267
- ? "task-split-needed"
268
- : "approved-context-needed",
269
- };
270
- }
271
- return {
272
- ...classification,
273
- contextRequest: {
274
- code: request.code,
275
- refs,
276
- },
277
- };
278
- }
279
-
280
- export interface CandidateArtifactSubmission {
281
- ledger: Pick<
282
- TaskLedger,
283
- "beginCandidate" | "appendCandidateSegment" | "sealCandidate"
284
- >;
285
- identity: BeginCandidateInput;
286
- workspaceRoot: string;
287
- writePaths: readonly string[];
288
- deletePaths: readonly string[];
289
- }
@@ -1,271 +0,0 @@
1
- import { lstatSync, readFileSync } from "node:fs";
2
- import path from "node:path";
3
- import { generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
4
- import { compareCanonicalStrings } from "./canonical.ts";
5
-
6
- import { isValidRelativePath } from "./contracts.ts";
7
- import { observeSafePath } from "./safe-path.ts";
8
-
9
- export type CandidatePatchOperation =
10
- | {
11
- kind: "replace";
12
- path: string;
13
- oldText: string;
14
- newText: string;
15
- }
16
- | { kind: "rewrite"; path: string; content: string }
17
- | {
18
- kind: "create";
19
- path: string;
20
- content: string;
21
- mode: "regular" | "executable";
22
- }
23
- | { kind: "delete"; path: string };
24
-
25
- interface CandidateFileState {
26
- path: string;
27
- base: string | null;
28
- current: string | null;
29
- mode: "100644" | "100755";
30
- }
31
-
32
- function exactKeys(value: object, expected: readonly string[]): boolean {
33
- const actual = Object.keys(value).sort();
34
- return (
35
- actual.length === expected.length &&
36
- [...expected].sort().every((key, index) => actual[index] === key)
37
- );
38
- }
39
-
40
- function safeText(value: unknown, maxBytes: number): value is string {
41
- if (typeof value !== "string" || value.includes("\0")) return false;
42
- const encoded = Buffer.from(value, "utf8");
43
- return encoded.byteLength <= maxBytes && encoded.toString("utf8") === value;
44
- }
45
-
46
- function renderFileDiff(state: CandidateFileState): string {
47
- if (state.base === state.current) return "";
48
- if (state.base === null && state.current === "") {
49
- throw new Error("candidate-empty-file-create-unsupported");
50
- }
51
- if (state.current === null && state.base === "") {
52
- throw new Error("candidate-empty-file-delete-unsupported");
53
- }
54
- const output: string[] = [`diff --git a/${state.path} b/${state.path}`];
55
- if (state.base === null) output.push(`new file mode ${state.mode}`);
56
- if (state.current === null) output.push(`deleted file mode ${state.mode}`);
57
- const generated = generateUnifiedPatch(
58
- state.path,
59
- state.base ?? "",
60
- state.current ?? "",
61
- 3,
62
- );
63
- const generatedHeaders = `--- ${state.path}\n+++ ${state.path}\n`;
64
- if (!generated.startsWith(generatedHeaders)) {
65
- throw new Error("candidate-patch-diff-invalid");
66
- }
67
- output.push(state.base === null ? "--- /dev/null" : `--- a/${state.path}`);
68
- output.push(state.current === null ? "+++ /dev/null" : `+++ b/${state.path}`);
69
- return `${output.join("\n")}\n${generated.slice(generatedHeaders.length)}`;
70
- }
71
-
72
- function occurrenceCount(value: string, search: string): number {
73
- let count = 0;
74
- let offset = 0;
75
- for (;;) {
76
- const found = value.indexOf(search, offset);
77
- if (found < 0) return count;
78
- count += 1;
79
- if (count > 1) return count;
80
- offset = found + 1;
81
- }
82
- }
83
-
84
- export function compileCandidatePatch(input: {
85
- root: string;
86
- writePaths: readonly string[];
87
- deletePaths: readonly string[];
88
- operations: readonly CandidatePatchOperation[];
89
- maxBytes: number;
90
- }): string {
91
- if (
92
- !path.isAbsolute(input.root) ||
93
- !Number.isSafeInteger(input.maxBytes) ||
94
- input.maxBytes < 1 ||
95
- !Array.isArray(input.operations) ||
96
- input.operations.length < 1 ||
97
- input.operations.length > 128
98
- ) {
99
- throw new Error("candidate-patch-invalid");
100
- }
101
- const writePaths = new Set(input.writePaths);
102
- const deletePaths = new Set(input.deletePaths);
103
- const states = new Map<string, CandidateFileState>();
104
-
105
- const requirePath = (relative: unknown): string => {
106
- if (
107
- !isValidRelativePath(relative) ||
108
- relative === "." ||
109
- relative.trim() !== relative ||
110
- /[\r\n\t]/u.test(relative)
111
- ) {
112
- throw new Error("candidate-patch-path-invalid");
113
- }
114
- return relative;
115
- };
116
- const load = (relative: string): CandidateFileState => {
117
- const existing = states.get(relative);
118
- if (existing) return existing;
119
- const observation = observeSafePath(input.root, relative);
120
- if (observation.kind === "directory" || observation.kind === "unsafe") {
121
- throw new Error("candidate-patch-path-unsafe");
122
- }
123
- let base: string | null = null;
124
- let mode: CandidateFileState["mode"] = "100644";
125
- if (observation.kind === "file") {
126
- const target = path.join(input.root, relative);
127
- const stat = lstatSync(target);
128
- if (stat.size > input.maxBytes) {
129
- throw new Error("candidate-patch-source-too-large");
130
- }
131
- const bytes = readFileSync(target);
132
- try {
133
- base = new TextDecoder("utf-8", {
134
- fatal: true,
135
- ignoreBOM: true,
136
- }).decode(bytes);
137
- } catch {
138
- throw new Error("candidate-patch-source-invalid");
139
- }
140
- if (base.includes("\0")) {
141
- throw new Error("candidate-patch-source-invalid");
142
- }
143
- mode = stat.mode & 0o111 ? "100755" : "100644";
144
- }
145
- const state = { path: relative, base, current: base, mode };
146
- states.set(relative, state);
147
- return state;
148
- };
149
-
150
- for (const [operationIndex, operation] of input.operations.entries()) {
151
- if (
152
- !operation ||
153
- typeof operation !== "object" ||
154
- Array.isArray(operation)
155
- ) {
156
- throw new Error("candidate-patch-operation-invalid");
157
- }
158
- switch (operation.kind) {
159
- case "replace": {
160
- if (
161
- !exactKeys(operation, ["kind", "path", "oldText", "newText"]) ||
162
- !safeText(operation.oldText, input.maxBytes) ||
163
- operation.oldText.length === 0 ||
164
- !safeText(operation.newText, input.maxBytes)
165
- ) {
166
- throw new Error("candidate-patch-replace-invalid");
167
- }
168
- const relative = requirePath(operation.path);
169
- const reject = (reason: string, hint: string): never => {
170
- throw new Error(
171
- JSON.stringify({
172
- code: "candidate-patch-replace-invalid",
173
- operationIndex,
174
- ...(relative.length <= 512 && !/[\p{Cc}\p{Cf}]/u.test(relative)
175
- ? { path: relative }
176
- : {}),
177
- reason,
178
- hint,
179
- }),
180
- );
181
- };
182
- if (!writePaths.has(relative)) {
183
- reject(
184
- "path-not-authorized",
185
- "Use only approved write paths; request context instead of widening authority.",
186
- );
187
- }
188
- const state = load(relative);
189
- const current =
190
- state.current ??
191
- reject(
192
- "file-not-found",
193
- "Use create for a new approved file, or correct the path.",
194
- );
195
- const occurrences = occurrenceCount(current, operation.oldText);
196
- if (occurrences !== 1) {
197
- reject(
198
- occurrences === 0 ? "old-text-not-found" : "old-text-ambiguous",
199
- "Read the approved file and supply exact unique oldText, including enough surrounding context. Operations are applied in order.",
200
- );
201
- }
202
- state.current = current.replace(operation.oldText, operation.newText);
203
- break;
204
- }
205
- case "rewrite": {
206
- if (
207
- !exactKeys(operation, ["kind", "path", "content"]) ||
208
- !safeText(operation.content, input.maxBytes)
209
- ) {
210
- throw new Error("candidate-patch-rewrite-invalid");
211
- }
212
- const relative = requirePath(operation.path);
213
- if (!writePaths.has(relative)) {
214
- throw new Error("candidate-patch-rewrite-invalid");
215
- }
216
- const state = load(relative);
217
- if (state.current === null) {
218
- throw new Error("candidate-patch-rewrite-invalid");
219
- }
220
- state.current = operation.content;
221
- break;
222
- }
223
- case "create": {
224
- if (
225
- !exactKeys(operation, ["kind", "path", "content", "mode"]) ||
226
- !safeText(operation.content, input.maxBytes) ||
227
- operation.content.length === 0 ||
228
- (operation.mode !== "regular" && operation.mode !== "executable")
229
- ) {
230
- throw new Error("candidate-patch-create-invalid");
231
- }
232
- const relative = requirePath(operation.path);
233
- if (!writePaths.has(relative)) {
234
- throw new Error("candidate-patch-create-invalid");
235
- }
236
- const state = load(relative);
237
- if (state.base !== null || state.current !== null) {
238
- throw new Error("candidate-patch-create-invalid");
239
- }
240
- state.current = operation.content;
241
- state.mode = operation.mode === "executable" ? "100755" : "100644";
242
- break;
243
- }
244
- case "delete": {
245
- if (!exactKeys(operation, ["kind", "path"])) {
246
- throw new Error("candidate-patch-delete-invalid");
247
- }
248
- const relative = requirePath(operation.path);
249
- if (!deletePaths.has(relative)) {
250
- throw new Error("candidate-patch-delete-invalid");
251
- }
252
- const state = load(relative);
253
- if (state.base === null || state.current === null) {
254
- throw new Error("candidate-patch-delete-invalid");
255
- }
256
- state.current = null;
257
- break;
258
- }
259
- default:
260
- throw new Error("candidate-patch-operation-invalid");
261
- }
262
- }
263
-
264
- const diff = [...states.values()]
265
- .filter((state) => state.base !== state.current)
266
- .sort((left, right) => compareCanonicalStrings(left.path, right.path))
267
- .map(renderFileDiff)
268
- .join("");
269
- if (diff.length === 0) throw new Error("candidate-patch-empty");
270
- return diff;
271
- }
@@ -1,80 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { lstatSync, readFileSync } from "node:fs";
3
- import path from "node:path";
4
- import { observeSafePath } from "./safe-path.ts";
5
-
6
- export function runGitApply(
7
- root: string,
8
- diff: Uint8Array,
9
- checkOnly: boolean,
10
- signal: AbortSignal,
11
- ): Promise<"ok" | "failed" | "cancelled"> {
12
- if (signal.aborted) return Promise.resolve("cancelled");
13
- return new Promise((resolve) => {
14
- let settled = false;
15
- const settle = (value: "ok" | "failed" | "cancelled") => {
16
- if (settled) return;
17
- settled = true;
18
- signal.removeEventListener("abort", abort);
19
- resolve(value);
20
- };
21
- const child = spawn(
22
- "git",
23
- [
24
- // Candidate patches bind exact bytes, independent of host checkout
25
- // preferences. Git's Windows autocrlf default must not rewrite them.
26
- "-c",
27
- "core.autocrlf=false",
28
- "-c",
29
- "core.eol=lf",
30
- "apply",
31
- ...(checkOnly ? ["--check"] : []),
32
- "--recount",
33
- "--whitespace=nowarn",
34
- "-",
35
- ],
36
- { cwd: root, shell: false, stdio: ["pipe", "ignore", "ignore"] },
37
- );
38
- const abort = () => {
39
- child.kill("SIGTERM");
40
- settle("cancelled");
41
- };
42
- signal.addEventListener("abort", abort, { once: true });
43
- child.once("error", () => settle(signal.aborted ? "cancelled" : "failed"));
44
- child.once("close", (code) =>
45
- settle(signal.aborted ? "cancelled" : code === 0 ? "ok" : "failed"),
46
- );
47
- child.stdin.on("error", () => undefined);
48
- child.stdin.end(Buffer.from(diff));
49
- });
50
- }
51
- export function revisionChanges(
52
- root: string,
53
- paths: readonly string[],
54
- ): Record<
55
- string,
56
- { kind: "absent" } | { kind: "file"; bytes: Uint8Array; mode: number }
57
- > {
58
- const changes: Record<
59
- string,
60
- { kind: "absent" } | { kind: "file"; bytes: Uint8Array; mode: number }
61
- > = {};
62
- for (const relative of [...new Set(paths)].sort()) {
63
- const observation = observeSafePath(root, relative);
64
- if (observation.kind === "absent") {
65
- changes[relative] = { kind: "absent" };
66
- continue;
67
- }
68
- if (observation.kind !== "file") {
69
- throw new Error("workflow-candidate-path-unsafe");
70
- }
71
- const target = path.join(root, ...relative.split("/"));
72
- const stat = lstatSync(target);
73
- changes[relative] = {
74
- kind: "file",
75
- bytes: readFileSync(target),
76
- mode: stat.mode & 0o777,
77
- };
78
- }
79
- return changes;
80
- }
package/src/canonical.ts DELETED
@@ -1,16 +0,0 @@
1
- /** Canonical identity ordering is UTF-16 code-unit order, never host collation. */
2
- export function compareCanonicalStrings(left: string, right: string): number {
3
- return left < right ? -1 : left > right ? 1 : 0;
4
- }
5
-
6
- export function canonicalJson(value: unknown): string {
7
- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
8
- if (value && typeof value === "object") {
9
- return `{${Object.entries(value as Record<string, unknown>)
10
- .filter(([, entry]) => entry !== undefined)
11
- .sort(([left], [right]) => compareCanonicalStrings(left, right))
12
- .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)
13
- .join(",")}}`;
14
- }
15
- return JSON.stringify(value) ?? "null";
16
- }