@abelxiaoxing/cadence 2.0.50 → 2.1.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.
- package/README.de.md +72 -76
- package/README.es.md +71 -75
- package/README.fr.md +72 -76
- package/README.ja.md +83 -101
- package/README.ko.md +81 -97
- package/README.md +69 -82
- package/README.pt-BR.md +72 -76
- package/README.ru.md +72 -77
- package/README.zh-CN.md +72 -79
- package/docs/conversation-mode.md +26 -6
- package/docs/history.md +15 -2
- package/docs/reuse-and-distribution.md +1 -0
- package/package.json +8 -2
- package/src/cadence-instructions.ts +5 -5
- package/src/cadence-mode.ts +49 -7
- package/src/coordinator-tools.mjs +39 -5
- package/src/model-preview.mjs +4 -1
- package/src/native-build.ts +1 -1
- package/src/sdk-worker.mjs +80 -59
- package/src/service/contracts/models.ts +6 -0
- package/src/service/contracts/workbench.ts +218 -17
- package/src/service/contracts/workflow.ts +309 -30
- package/src/service/knowledge-store.ts +496 -0
- package/src/service/project-knowledge.ts +539 -0
- package/src/service/workflow-git.ts +773 -0
- package/src/service-host.mjs +4588 -2279
- package/src/session-entries.mjs +3 -1
- package/src/session-file.mjs +26 -0
- package/src/session-rename.mjs +94 -0
- package/src/session-sharing.ts +3 -1
- package/src/worker-inputs.mjs +144 -0
- package/src/worker-toolkit.mjs +26 -1
- package/web/dist/assets/cadence.css +1 -1
- package/web/dist/assets/cadence.js +31 -22
- package/web/dist/manifest.json +7 -7
|
@@ -0,0 +1,773 @@
|
|
|
1
|
+
/** Workflow Git observations and exact write scopes. In-run observations spawn
|
|
2
|
+
* asynchronously so a large repository never stalls the owner's event loop;
|
|
3
|
+
* admission keeps a small names-only synchronous observation. Contents are
|
|
4
|
+
* hashed by streaming, never buffered as a diff. No config writes. */
|
|
5
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import {
|
|
8
|
+
closeSync,
|
|
9
|
+
constants,
|
|
10
|
+
existsSync,
|
|
11
|
+
fstatSync,
|
|
12
|
+
lstatSync,
|
|
13
|
+
openSync,
|
|
14
|
+
readdirSync,
|
|
15
|
+
readlinkSync,
|
|
16
|
+
readSync,
|
|
17
|
+
realpathSync,
|
|
18
|
+
type Stats,
|
|
19
|
+
} from "node:fs";
|
|
20
|
+
import { lstat, open, readdir, readlink } from "node:fs/promises";
|
|
21
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
22
|
+
import {
|
|
23
|
+
gitArguments,
|
|
24
|
+
gitEnvironment,
|
|
25
|
+
readBounded,
|
|
26
|
+
safeDirectory,
|
|
27
|
+
} from "../workspace.ts";
|
|
28
|
+
|
|
29
|
+
import { ContractError } from "./contracts/core.ts";
|
|
30
|
+
import {
|
|
31
|
+
type DeliveryTarget,
|
|
32
|
+
type WorkflowPlan,
|
|
33
|
+
workflowCovers,
|
|
34
|
+
workflowPath,
|
|
35
|
+
} from "./contracts/workflow.ts";
|
|
36
|
+
import { hash } from "./private-files.ts";
|
|
37
|
+
|
|
38
|
+
/** Names-only Git output (one entry per changed path). */
|
|
39
|
+
const NAMES_BYTES = 64 * 1024 * 1024;
|
|
40
|
+
const SYNC_MS = 30_000;
|
|
41
|
+
const READ_MS = 120_000;
|
|
42
|
+
/** Larger files use a stat identity instead of a full content hash. */
|
|
43
|
+
const HASH_BYTES = 64 * 1024 * 1024;
|
|
44
|
+
const CHUNK = 1024 * 1024;
|
|
45
|
+
|
|
46
|
+
/** A refusal with an explanation; the public code stays one of ERROR_CODES. */
|
|
47
|
+
export class WorkflowRefusal extends ContractError {
|
|
48
|
+
constructor(
|
|
49
|
+
code: "conflict" | "stale" | "forbidden" | "invalid",
|
|
50
|
+
readonly detail: string,
|
|
51
|
+
) {
|
|
52
|
+
super(code);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function gitRead(cwd: string, args: string[]): string {
|
|
57
|
+
const r = spawnSync("git", gitArguments(args), {
|
|
58
|
+
cwd,
|
|
59
|
+
env: gitEnvironment(),
|
|
60
|
+
encoding: "utf8",
|
|
61
|
+
timeout: SYNC_MS,
|
|
62
|
+
maxBuffer: NAMES_BYTES,
|
|
63
|
+
windowsHide: true,
|
|
64
|
+
});
|
|
65
|
+
if (r.error || r.status !== 0) throw new ContractError("unavailable");
|
|
66
|
+
return r.stdout;
|
|
67
|
+
}
|
|
68
|
+
/** Synchronous read where exit 1 is an answer (check-ignore), not a failure. */
|
|
69
|
+
function gitAnswer(cwd: string, args: string[]): string | null {
|
|
70
|
+
const r = spawnSync("git", gitArguments(args), {
|
|
71
|
+
cwd,
|
|
72
|
+
env: gitEnvironment(),
|
|
73
|
+
encoding: "utf8",
|
|
74
|
+
timeout: SYNC_MS,
|
|
75
|
+
maxBuffer: NAMES_BYTES,
|
|
76
|
+
windowsHide: true,
|
|
77
|
+
});
|
|
78
|
+
if (r.error || (r.status !== 0 && r.status !== 1))
|
|
79
|
+
throw new ContractError("unavailable");
|
|
80
|
+
return r.status === 0 ? r.stdout : null;
|
|
81
|
+
}
|
|
82
|
+
/** Asynchronous bounded Git read; the exit code is returned for callers that branch on it. */
|
|
83
|
+
export function gitRun(
|
|
84
|
+
cwd: string,
|
|
85
|
+
args: string[],
|
|
86
|
+
timeoutMs = READ_MS,
|
|
87
|
+
): Promise<{ code: number | null; stdout: string }> {
|
|
88
|
+
return new Promise((done, fail) => {
|
|
89
|
+
const child = spawn("git", gitArguments(args), {
|
|
90
|
+
cwd,
|
|
91
|
+
env: gitEnvironment(),
|
|
92
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
93
|
+
windowsHide: true,
|
|
94
|
+
});
|
|
95
|
+
const chunks: Buffer[] = [];
|
|
96
|
+
let bytes = 0,
|
|
97
|
+
broken = false;
|
|
98
|
+
const timer = setTimeout(() => {
|
|
99
|
+
broken = true;
|
|
100
|
+
child.kill("SIGKILL");
|
|
101
|
+
}, timeoutMs);
|
|
102
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
103
|
+
bytes += chunk.length;
|
|
104
|
+
if (bytes > NAMES_BYTES) {
|
|
105
|
+
broken = true;
|
|
106
|
+
child.kill("SIGKILL");
|
|
107
|
+
} else chunks.push(chunk);
|
|
108
|
+
});
|
|
109
|
+
child.once("error", () => {
|
|
110
|
+
broken = true;
|
|
111
|
+
});
|
|
112
|
+
child.once("close", (code) => {
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
if (broken) fail(new ContractError("unavailable"));
|
|
115
|
+
else done({ code, stdout: Buffer.concat(chunks).toString("utf8") });
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
export async function gitText(
|
|
120
|
+
cwd: string,
|
|
121
|
+
args: string[],
|
|
122
|
+
timeoutMs = READ_MS,
|
|
123
|
+
): Promise<string> {
|
|
124
|
+
const r = await gitRun(cwd, args, timeoutMs);
|
|
125
|
+
if (r.code !== 0) throw new ContractError("unavailable");
|
|
126
|
+
return r.stdout;
|
|
127
|
+
}
|
|
128
|
+
export async function gitHead(cwd: string): Promise<string> {
|
|
129
|
+
return (await gitText(cwd, ["rev-parse", "--verify", "HEAD"])).trim();
|
|
130
|
+
}
|
|
131
|
+
function contains(root: string, path: string): boolean {
|
|
132
|
+
const within = relative(root, path);
|
|
133
|
+
return (
|
|
134
|
+
!within ||
|
|
135
|
+
(!within.startsWith(`..${sep}`) && within !== ".." && !isAbsolute(within))
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
/** Either directory containing the other: worktrees never nest with the checkout. */
|
|
139
|
+
export function nested(a: string, b: string): boolean {
|
|
140
|
+
return contains(a, b) || contains(b, a);
|
|
141
|
+
}
|
|
142
|
+
export function safeWorkflowFile(cwd: string, name: string): string {
|
|
143
|
+
workflowPath(name);
|
|
144
|
+
const p = resolve(cwd, name);
|
|
145
|
+
if (relative(cwd, p).startsWith("..")) throw new ContractError("forbidden");
|
|
146
|
+
safeDirectory(dirname(p));
|
|
147
|
+
try {
|
|
148
|
+
const st = lstatSync(p);
|
|
149
|
+
if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
|
|
150
|
+
throw new ContractError("forbidden");
|
|
151
|
+
} catch (e) {
|
|
152
|
+
if (!(e instanceof Error && "code" in e && e.code === "ENOENT")) throw e;
|
|
153
|
+
}
|
|
154
|
+
return p;
|
|
155
|
+
}
|
|
156
|
+
/** A declared target may be an absent path, a regular file or a directory scope. */
|
|
157
|
+
function declaredTarget(cwd: string, name: string): void {
|
|
158
|
+
workflowPath(name);
|
|
159
|
+
const p = resolve(cwd, name);
|
|
160
|
+
if (relative(cwd, p).startsWith("..")) throw new ContractError("forbidden");
|
|
161
|
+
safeDirectory(dirname(p));
|
|
162
|
+
try {
|
|
163
|
+
const st = lstatSync(p);
|
|
164
|
+
if (
|
|
165
|
+
st.isSymbolicLink() ||
|
|
166
|
+
(!st.isFile() && !st.isDirectory()) ||
|
|
167
|
+
(st.isFile() && st.nlink !== 1)
|
|
168
|
+
)
|
|
169
|
+
throw new ContractError("forbidden");
|
|
170
|
+
} catch (e) {
|
|
171
|
+
if (!(e instanceof Error && "code" in e && e.code === "ENOENT")) throw e;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const absent = (e: unknown) =>
|
|
175
|
+
e instanceof Error &&
|
|
176
|
+
"code" in e &&
|
|
177
|
+
(e.code === "ENOENT" || e.code === "ENOTDIR");
|
|
178
|
+
/** Directory scopes are observed by content, bounded: a larger tree must be
|
|
179
|
+
* declared through narrower paths. Nested repositories are not traversed. */
|
|
180
|
+
const DIRECTORY_ENTRIES = 20_000;
|
|
181
|
+
/** Inside a directory scope larger files use a stat identity. */
|
|
182
|
+
const DIRECTORY_HASH_BYTES = 1024 * 1024;
|
|
183
|
+
function quickIdentity(st: Stats, hashBytes: number): string | undefined {
|
|
184
|
+
if (!st.isFile()) return `special:${st.mode}`;
|
|
185
|
+
if (st.size > hashBytes)
|
|
186
|
+
return `stat:${st.size}:${st.mtimeMs}:${st.ctimeMs}:${st.ino}`;
|
|
187
|
+
return undefined;
|
|
188
|
+
}
|
|
189
|
+
function fileIdentity(p: string, st: Stats, hashBytes: number): string | null {
|
|
190
|
+
if (st.isSymbolicLink()) return `link:${hash(readlinkSync(p))}`;
|
|
191
|
+
const quick = quickIdentity(st, hashBytes);
|
|
192
|
+
if (quick) return quick;
|
|
193
|
+
let fd: number;
|
|
194
|
+
try {
|
|
195
|
+
fd = openSync(p, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
196
|
+
} catch (e) {
|
|
197
|
+
if (absent(e)) return null;
|
|
198
|
+
throw e;
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
if (!fstatSync(fd).isFile()) throw new ContractError("stale");
|
|
202
|
+
const digest = createHash("sha256"),
|
|
203
|
+
buffer = Buffer.alloc(CHUNK);
|
|
204
|
+
for (let n = readSync(fd, buffer); n > 0; n = readSync(fd, buffer))
|
|
205
|
+
digest.update(buffer.subarray(0, n));
|
|
206
|
+
return `sha256:${digest.digest("hex")}`;
|
|
207
|
+
} finally {
|
|
208
|
+
closeSync(fd);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
async function fileIdentityAsync(
|
|
212
|
+
p: string,
|
|
213
|
+
st: Stats,
|
|
214
|
+
hashBytes: number,
|
|
215
|
+
signal?: AbortSignal,
|
|
216
|
+
): Promise<string | null> {
|
|
217
|
+
if (st.isSymbolicLink()) return `link:${hash(await readlink(p))}`;
|
|
218
|
+
const quick = quickIdentity(st, hashBytes);
|
|
219
|
+
if (quick) return quick;
|
|
220
|
+
let handle: Awaited<ReturnType<typeof open>>;
|
|
221
|
+
try {
|
|
222
|
+
handle = await open(
|
|
223
|
+
p,
|
|
224
|
+
constants.O_RDONLY |
|
|
225
|
+
(constants.O_NOFOLLOW ?? 0) |
|
|
226
|
+
(constants.O_NONBLOCK ?? 0),
|
|
227
|
+
);
|
|
228
|
+
} catch (e) {
|
|
229
|
+
if (absent(e)) return null;
|
|
230
|
+
throw e;
|
|
231
|
+
}
|
|
232
|
+
try {
|
|
233
|
+
const before = await handle.stat();
|
|
234
|
+
const same = (a: Stats, b: Stats) =>
|
|
235
|
+
a.isFile() &&
|
|
236
|
+
b.isFile() &&
|
|
237
|
+
a.dev === b.dev &&
|
|
238
|
+
a.ino === b.ino &&
|
|
239
|
+
a.size === b.size &&
|
|
240
|
+
a.mtimeMs === b.mtimeMs &&
|
|
241
|
+
a.ctimeMs === b.ctimeMs;
|
|
242
|
+
if (!same(st, before)) throw new ContractError("stale");
|
|
243
|
+
const digest = createHash("sha256"),
|
|
244
|
+
buffer = Buffer.alloc(CHUNK);
|
|
245
|
+
let remaining = before.size;
|
|
246
|
+
while (remaining > 0) {
|
|
247
|
+
if (signal?.aborted) throw new ContractError("stale");
|
|
248
|
+
const { bytesRead } = await handle.read(
|
|
249
|
+
buffer,
|
|
250
|
+
0,
|
|
251
|
+
Math.min(CHUNK, remaining),
|
|
252
|
+
null,
|
|
253
|
+
);
|
|
254
|
+
if (!bytesRead) throw new ContractError("stale");
|
|
255
|
+
digest.update(buffer.subarray(0, bytesRead));
|
|
256
|
+
remaining -= bytesRead;
|
|
257
|
+
}
|
|
258
|
+
if (!same(before, await handle.stat()) || !same(before, await lstat(p)))
|
|
259
|
+
throw new ContractError("stale");
|
|
260
|
+
return `sha256:${digest.digest("hex")}`;
|
|
261
|
+
} finally {
|
|
262
|
+
await handle.close();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
const tooLarge = (name: string) =>
|
|
266
|
+
new WorkflowRefusal(
|
|
267
|
+
"invalid",
|
|
268
|
+
`Declared directory ${name} has more than ${DIRECTORY_ENTRIES} entries; declare narrower write paths.`,
|
|
269
|
+
);
|
|
270
|
+
function directoryIdentity(root: string, name: string): string {
|
|
271
|
+
const rows: string[] = [];
|
|
272
|
+
let count = 0;
|
|
273
|
+
const visit = (directory: string, prefix: string) => {
|
|
274
|
+
for (const entry of readdirSync(directory).sort()) {
|
|
275
|
+
if (entry === ".git") continue;
|
|
276
|
+
if (++count > DIRECTORY_ENTRIES) throw tooLarge(name);
|
|
277
|
+
const full = join(directory, entry),
|
|
278
|
+
relative = `${prefix}${entry}`;
|
|
279
|
+
const st = lstatSync(full);
|
|
280
|
+
if (st.isDirectory()) {
|
|
281
|
+
rows.push(`${relative}/`);
|
|
282
|
+
visit(full, `${relative}/`);
|
|
283
|
+
} else
|
|
284
|
+
rows.push(
|
|
285
|
+
`${relative}\0${fileIdentity(full, st, DIRECTORY_HASH_BYTES)}`,
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
visit(root, "");
|
|
290
|
+
return `directory:${hash(rows.join("\n"))}`;
|
|
291
|
+
}
|
|
292
|
+
async function directoryIdentityAsync(
|
|
293
|
+
root: string,
|
|
294
|
+
name: string,
|
|
295
|
+
contentOnly = false,
|
|
296
|
+
signal?: AbortSignal,
|
|
297
|
+
): Promise<string> {
|
|
298
|
+
const rows: string[] = [];
|
|
299
|
+
let count = 0;
|
|
300
|
+
const visit = async (directory: string, prefix: string) => {
|
|
301
|
+
for (const entry of (await readdir(directory)).sort()) {
|
|
302
|
+
if (signal?.aborted) throw new ContractError("stale");
|
|
303
|
+
if (entry === ".git") continue;
|
|
304
|
+
if (++count > DIRECTORY_ENTRIES) throw tooLarge(name);
|
|
305
|
+
const full = join(directory, entry),
|
|
306
|
+
relative = `${prefix}${entry}`;
|
|
307
|
+
const st = await lstat(full);
|
|
308
|
+
if (st.isDirectory()) {
|
|
309
|
+
rows.push(`${relative}/`);
|
|
310
|
+
await visit(full, `${relative}/`);
|
|
311
|
+
} else
|
|
312
|
+
rows.push(
|
|
313
|
+
`${relative}\0${await fileIdentityAsync(full, st, contentOnly ? Infinity : DIRECTORY_HASH_BYTES, signal)}`,
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
await visit(root, "");
|
|
318
|
+
return `directory:${hash(rows.join("\n"))}`;
|
|
319
|
+
}
|
|
320
|
+
/** Streaming content identity: no size ceiling makes a target unplannable.
|
|
321
|
+
* A directory's identity covers its contents unless `walk` is false (a Git
|
|
322
|
+
* scope pinned by HEAD plus the dirty check needs no tree walk). */
|
|
323
|
+
export function pathIdentity(
|
|
324
|
+
cwd: string,
|
|
325
|
+
name: string,
|
|
326
|
+
walk = true,
|
|
327
|
+
): string | null {
|
|
328
|
+
const p = resolve(cwd, name);
|
|
329
|
+
if (relative(cwd, p).startsWith("..")) throw new ContractError("forbidden");
|
|
330
|
+
let st: Stats;
|
|
331
|
+
try {
|
|
332
|
+
st = lstatSync(p);
|
|
333
|
+
} catch (e) {
|
|
334
|
+
if (absent(e)) return null;
|
|
335
|
+
throw e;
|
|
336
|
+
}
|
|
337
|
+
if (st.isDirectory()) return walk ? directoryIdentity(p, name) : "directory";
|
|
338
|
+
return fileIdentity(p, st, HASH_BYTES);
|
|
339
|
+
}
|
|
340
|
+
export async function pathIdentityAsync(
|
|
341
|
+
cwd: string,
|
|
342
|
+
name: string,
|
|
343
|
+
contentOnly = false,
|
|
344
|
+
signal?: AbortSignal,
|
|
345
|
+
): Promise<string | null> {
|
|
346
|
+
if (signal?.aborted) throw new ContractError("stale");
|
|
347
|
+
const p = resolve(cwd, name);
|
|
348
|
+
if (relative(cwd, p).startsWith("..")) throw new ContractError("forbidden");
|
|
349
|
+
let st: Stats;
|
|
350
|
+
try {
|
|
351
|
+
st = await lstat(p);
|
|
352
|
+
} catch (e) {
|
|
353
|
+
if (absent(e)) return null;
|
|
354
|
+
throw e;
|
|
355
|
+
}
|
|
356
|
+
if (st.isDirectory())
|
|
357
|
+
return directoryIdentityAsync(p, name, contentOnly, signal);
|
|
358
|
+
return fileIdentityAsync(p, st, contentOnly ? Infinity : HASH_BYTES, signal);
|
|
359
|
+
}
|
|
360
|
+
export function contentsIdentity(cwd: string, paths: readonly string[]) {
|
|
361
|
+
return hash(JSON.stringify(paths.map((p) => [p, pathIdentity(cwd, p)])));
|
|
362
|
+
}
|
|
363
|
+
export async function contentsIdentityAsync(
|
|
364
|
+
cwd: string,
|
|
365
|
+
paths: readonly string[],
|
|
366
|
+
): Promise<string> {
|
|
367
|
+
const rows = [];
|
|
368
|
+
for (const p of paths) rows.push([p, await pathIdentityAsync(cwd, p)]);
|
|
369
|
+
return hash(JSON.stringify(rows));
|
|
370
|
+
}
|
|
371
|
+
/** Verification crosses worktrees: inode, timestamps and other placement metadata
|
|
372
|
+
* cannot identify source bytes. Stream every file, retaining directory entry bounds. */
|
|
373
|
+
export async function sourceIdentityAsync(
|
|
374
|
+
cwd: string,
|
|
375
|
+
paths: readonly string[],
|
|
376
|
+
signal?: AbortSignal,
|
|
377
|
+
): Promise<string> {
|
|
378
|
+
const rows = [];
|
|
379
|
+
for (const p of paths)
|
|
380
|
+
rows.push([p, await pathIdentityAsync(cwd, p, true, signal)]);
|
|
381
|
+
return hash(JSON.stringify(rows));
|
|
382
|
+
}
|
|
383
|
+
const names = (s: string) => s.split("\0").filter(Boolean);
|
|
384
|
+
const CHANGED = [
|
|
385
|
+
[
|
|
386
|
+
"diff",
|
|
387
|
+
"--name-only",
|
|
388
|
+
"-z",
|
|
389
|
+
"--no-renames",
|
|
390
|
+
"--no-ext-diff",
|
|
391
|
+
"--no-textconv",
|
|
392
|
+
"HEAD",
|
|
393
|
+
"--",
|
|
394
|
+
],
|
|
395
|
+
// HEAD -> working tree alone can hide staged bytes when the worktree
|
|
396
|
+
// was restored to HEAD. The commit consumes the index, not that view.
|
|
397
|
+
[
|
|
398
|
+
"diff",
|
|
399
|
+
"--cached",
|
|
400
|
+
"--name-only",
|
|
401
|
+
"-z",
|
|
402
|
+
"--no-renames",
|
|
403
|
+
"--no-ext-diff",
|
|
404
|
+
"--no-textconv",
|
|
405
|
+
"HEAD",
|
|
406
|
+
"--",
|
|
407
|
+
],
|
|
408
|
+
["ls-files", "--others", "--exclude-standard", "-z"],
|
|
409
|
+
];
|
|
410
|
+
export function workflowChanged(cwd: string): string[] {
|
|
411
|
+
return [...new Set(CHANGED.flatMap((args) => names(gitRead(cwd, args))))];
|
|
412
|
+
}
|
|
413
|
+
export async function changedPaths(cwd: string): Promise<string[]> {
|
|
414
|
+
const outputs = await Promise.all(CHANGED.map((args) => gitText(cwd, args)));
|
|
415
|
+
return [...new Set(outputs.flatMap(names))];
|
|
416
|
+
}
|
|
417
|
+
/** A changed path overlaps a scope when either contains the other. */
|
|
418
|
+
export function overlapping(
|
|
419
|
+
scope: readonly string[],
|
|
420
|
+
changed: readonly string[],
|
|
421
|
+
): string[] {
|
|
422
|
+
return changed
|
|
423
|
+
.filter(
|
|
424
|
+
(p) =>
|
|
425
|
+
workflowCovers(scope, p) || scope.some((q) => q.startsWith(`${p}/`)),
|
|
426
|
+
)
|
|
427
|
+
.sort();
|
|
428
|
+
}
|
|
429
|
+
const list = (paths: readonly string[]) =>
|
|
430
|
+
`${paths.slice(0, 32).join(", ")}${paths.length > 32 ? ` and ${paths.length - 32} more` : ""}`;
|
|
431
|
+
const INDEX_FLAGS = ["ls-files", "-v", "-z"];
|
|
432
|
+
/** assume-unchanged/skip-worktree can hide real bytes even from git status. */
|
|
433
|
+
function indexHidden(output: string): string[] {
|
|
434
|
+
return names(output)
|
|
435
|
+
.filter((row) => row.startsWith("S ") || /^[a-z] /u.test(row))
|
|
436
|
+
.map((row) => row.slice(2));
|
|
437
|
+
}
|
|
438
|
+
function assertVisibleIndex(paths: string[]): void {
|
|
439
|
+
if (paths.length)
|
|
440
|
+
throw new WorkflowRefusal(
|
|
441
|
+
"conflict",
|
|
442
|
+
`Git index flags hide these paths: ${list(paths)}. Correct them explicitly; Cadence never clears flags or assumes hidden contents are clean.`,
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
export async function assertWorkflowScope(
|
|
446
|
+
cwd: string,
|
|
447
|
+
allowed: readonly string[],
|
|
448
|
+
): Promise<string[]> {
|
|
449
|
+
assertVisibleIndex(indexHidden(await gitText(cwd, INDEX_FLAGS)));
|
|
450
|
+
const changes = await changedPaths(cwd);
|
|
451
|
+
const outside = changes.filter((name) => !workflowCovers(allowed, name));
|
|
452
|
+
if (outside.length)
|
|
453
|
+
throw new WorkflowRefusal(
|
|
454
|
+
"forbidden",
|
|
455
|
+
`Changes outside the approved write scope were preserved, not committed: ${list(outside.sort())}`,
|
|
456
|
+
);
|
|
457
|
+
for (const name of changes) safeWorkflowFile(cwd, name);
|
|
458
|
+
return changes;
|
|
459
|
+
}
|
|
460
|
+
/** A task commit must extend its observed baseline and contain only its scope. */
|
|
461
|
+
export async function assertWorkflowCommit(
|
|
462
|
+
cwd: string,
|
|
463
|
+
before: string,
|
|
464
|
+
commit: string,
|
|
465
|
+
allowed: readonly string[],
|
|
466
|
+
): Promise<string[]> {
|
|
467
|
+
if (
|
|
468
|
+
(await gitText(cwd, ["show", "-s", "--format=%P", commit])).trim() !==
|
|
469
|
+
before
|
|
470
|
+
)
|
|
471
|
+
throw new ContractError("stale");
|
|
472
|
+
const changed = await committedPaths(cwd, before, commit);
|
|
473
|
+
const outside = changed.filter((name) => !workflowCovers(allowed, name));
|
|
474
|
+
if (outside.length)
|
|
475
|
+
throw new WorkflowRefusal(
|
|
476
|
+
"forbidden",
|
|
477
|
+
`Commit contains files outside the approved scope: ${list(outside)}`,
|
|
478
|
+
);
|
|
479
|
+
for (const name of changed) safeWorkflowFile(cwd, name);
|
|
480
|
+
return changed;
|
|
481
|
+
}
|
|
482
|
+
export async function committedPaths(
|
|
483
|
+
cwd: string,
|
|
484
|
+
from: string,
|
|
485
|
+
to: string,
|
|
486
|
+
): Promise<string[]> {
|
|
487
|
+
return names(
|
|
488
|
+
await gitText(cwd, [
|
|
489
|
+
"diff",
|
|
490
|
+
"--name-only",
|
|
491
|
+
"-z",
|
|
492
|
+
"--no-renames",
|
|
493
|
+
"--no-ext-diff",
|
|
494
|
+
"--no-textconv",
|
|
495
|
+
from,
|
|
496
|
+
to,
|
|
497
|
+
"--",
|
|
498
|
+
]),
|
|
499
|
+
).sort();
|
|
500
|
+
}
|
|
501
|
+
/** Canonical shared repository plus filesystem incarnation; linked checkouts
|
|
502
|
+
* must not be mistaken for independent ref namespaces. */
|
|
503
|
+
export function repositoryIdentity(cwd: string): {
|
|
504
|
+
repository: string;
|
|
505
|
+
repositoryIdentity: string;
|
|
506
|
+
} {
|
|
507
|
+
const repository = realpathSync(
|
|
508
|
+
resolve(
|
|
509
|
+
cwd,
|
|
510
|
+
gitRead(cwd, ["rev-parse", "--git-common-dir"]).replace(/\r?\n$/u, ""),
|
|
511
|
+
),
|
|
512
|
+
);
|
|
513
|
+
const st = lstatSync(repository);
|
|
514
|
+
if (!st.isDirectory()) throw new ContractError("stale");
|
|
515
|
+
return {
|
|
516
|
+
repository,
|
|
517
|
+
repositoryIdentity: hash(JSON.stringify([repository, st.dev, st.ino])),
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
export function deliveryTarget(
|
|
521
|
+
cwd: string,
|
|
522
|
+
source: { head: string; branch: string },
|
|
523
|
+
): DeliveryTarget {
|
|
524
|
+
const gitDir = gitRead(cwd, ["rev-parse", "--absolute-git-dir"]).replace(
|
|
525
|
+
/\r?\n$/u,
|
|
526
|
+
"",
|
|
527
|
+
);
|
|
528
|
+
for (const name of [
|
|
529
|
+
"MERGE_HEAD",
|
|
530
|
+
"CHERRY_PICK_HEAD",
|
|
531
|
+
"REVERT_HEAD",
|
|
532
|
+
"rebase-apply",
|
|
533
|
+
"rebase-merge",
|
|
534
|
+
"sequencer",
|
|
535
|
+
"BISECT_START",
|
|
536
|
+
"index.lock",
|
|
537
|
+
"HEAD.lock",
|
|
538
|
+
]) {
|
|
539
|
+
if (existsSync(join(gitDir, name)))
|
|
540
|
+
throw new WorkflowRefusal(
|
|
541
|
+
"conflict",
|
|
542
|
+
"Finish the existing Git operation before planning isolated delivery.",
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
return {
|
|
546
|
+
...repositoryIdentity(cwd),
|
|
547
|
+
checkoutRoot: realpathSync(cwd),
|
|
548
|
+
head: source.head,
|
|
549
|
+
branch: source.branch,
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
export function assertRepository(target: DeliveryTarget): void {
|
|
553
|
+
const actual = repositoryIdentity(target.checkoutRoot);
|
|
554
|
+
if (
|
|
555
|
+
actual.repository !== target.repository ||
|
|
556
|
+
actual.repositoryIdentity !== target.repositoryIdentity
|
|
557
|
+
)
|
|
558
|
+
throw new ContractError("stale");
|
|
559
|
+
}
|
|
560
|
+
/** Includes ignored files everywhere: ordinary worktree removal deletes them. */
|
|
561
|
+
export async function worktreeResidue(cwd: string): Promise<string[]> {
|
|
562
|
+
const residue = names(
|
|
563
|
+
await gitText(cwd, [
|
|
564
|
+
"status",
|
|
565
|
+
"--porcelain=v1",
|
|
566
|
+
"-z",
|
|
567
|
+
"-uall",
|
|
568
|
+
"--ignored=traditional",
|
|
569
|
+
"--no-renames",
|
|
570
|
+
]),
|
|
571
|
+
)
|
|
572
|
+
.map((row) => row.slice(3))
|
|
573
|
+
.filter(Boolean)
|
|
574
|
+
.sort();
|
|
575
|
+
return [
|
|
576
|
+
...new Set([...residue, ...indexHidden(await gitText(cwd, INDEX_FLAGS))]),
|
|
577
|
+
].sort();
|
|
578
|
+
}
|
|
579
|
+
/** Committed changes need scope checks too; a clean index is not authority to
|
|
580
|
+
* adopt an externally substituted integration history. */
|
|
581
|
+
export async function assertCommittedScope(
|
|
582
|
+
cwd: string,
|
|
583
|
+
base: string,
|
|
584
|
+
candidate: string,
|
|
585
|
+
scope: readonly string[],
|
|
586
|
+
): Promise<void> {
|
|
587
|
+
if (
|
|
588
|
+
(await gitRun(cwd, ["merge-base", "--is-ancestor", base, candidate]))
|
|
589
|
+
.code !== 0
|
|
590
|
+
)
|
|
591
|
+
throw new ContractError("stale");
|
|
592
|
+
const outside = (await committedPaths(cwd, base, candidate)).filter(
|
|
593
|
+
(path) => !workflowCovers(scope, path),
|
|
594
|
+
);
|
|
595
|
+
if (outside.length)
|
|
596
|
+
throw new WorkflowRefusal(
|
|
597
|
+
"forbidden",
|
|
598
|
+
`Candidate contains committed files outside the approved scope: ${list(outside)}`,
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
/** A sealed candidate cannot acquire even staged-only edits during checks. */
|
|
602
|
+
export async function assertCandidate(
|
|
603
|
+
cwd: string,
|
|
604
|
+
candidate: string,
|
|
605
|
+
): Promise<void> {
|
|
606
|
+
if ((await gitHead(cwd)) !== candidate) throw new ContractError("stale");
|
|
607
|
+
await assertWorkflowScope(cwd, []);
|
|
608
|
+
}
|
|
609
|
+
/** Consent observation: branch/HEAD, declared target contents and project
|
|
610
|
+
* guidance, plus a refusal when a declared target is already dirty. Unrelated
|
|
611
|
+
* dirty files are not part of it: they never block planning or delivery. */
|
|
612
|
+
export function workflowObservation(
|
|
613
|
+
cwd: string,
|
|
614
|
+
plan?: WorkflowPlan,
|
|
615
|
+
): { identity: string; head: string; branch: string } {
|
|
616
|
+
const declared = [
|
|
617
|
+
...new Set([
|
|
618
|
+
...(plan?.tasks.flatMap((t) => t.writes) ?? []),
|
|
619
|
+
...(plan?.knowledge ?? []),
|
|
620
|
+
]),
|
|
621
|
+
];
|
|
622
|
+
for (const p of declared) declaredTarget(cwd, p);
|
|
623
|
+
const paths = [...new Set([".cadence/project.md", "AGENTS.md", ...declared])];
|
|
624
|
+
const working = plan?.delivery === "working-copy";
|
|
625
|
+
const contents = paths.map((p) => [p, pathIdentity(cwd, p, working)]);
|
|
626
|
+
if (working) {
|
|
627
|
+
// The ordinary bounded working-copy observation is additionally taken by the
|
|
628
|
+
// service; this exact per-write identity refuses substituted direct targets.
|
|
629
|
+
return { identity: hash(JSON.stringify(contents)), head: "", branch: "" };
|
|
630
|
+
}
|
|
631
|
+
// Refuse unsupported Git before any local-delivery observation can trigger
|
|
632
|
+
// a partial clone's implicit object download. Ordinary non-Git mode is unchanged.
|
|
633
|
+
gitRead(cwd, ["--no-lazy-fetch", "--version"]);
|
|
634
|
+
const head = gitRead(cwd, ["rev-parse", "--verify", "HEAD"]).trim();
|
|
635
|
+
const branch = gitRead(cwd, ["symbolic-ref", "HEAD"]).trim();
|
|
636
|
+
if (!/^refs\/heads\//u.test(branch) || !/^[a-f0-9]{40,64}$/u.test(head))
|
|
637
|
+
throw new ContractError("invalid");
|
|
638
|
+
if (plan) {
|
|
639
|
+
assertVisibleIndex(
|
|
640
|
+
overlapping(declared, indexHidden(gitRead(cwd, INDEX_FLAGS))),
|
|
641
|
+
);
|
|
642
|
+
// A task cannot implicitly adopt dirty inputs as its committed baseline.
|
|
643
|
+
const dirty = overlapping(declared, workflowChanged(cwd));
|
|
644
|
+
if (dirty.length)
|
|
645
|
+
throw new WorkflowRefusal(
|
|
646
|
+
"conflict",
|
|
647
|
+
`Declared write targets have uncommitted changes: ${list(dirty)}. Commit, stash or leave them out of the plan; Cadence never adopts dirty inputs.`,
|
|
648
|
+
);
|
|
649
|
+
// An ignored target is never committed: its edit could only be lost with
|
|
650
|
+
// the worktree. Local merge refuses it; working-copy delivery edits in place.
|
|
651
|
+
const ignored = gitAnswer(cwd, ["check-ignore", "--", ...declared]);
|
|
652
|
+
if (ignored !== null)
|
|
653
|
+
throw new WorkflowRefusal(
|
|
654
|
+
"invalid",
|
|
655
|
+
`Declared write targets are ignored by Git and cannot be delivered by local merge: ${list(
|
|
656
|
+
((names) =>
|
|
657
|
+
names.length ? names : ignored.split("\n").filter(Boolean))(
|
|
658
|
+
declared.filter((p) => ignored.split("\n").includes(p)),
|
|
659
|
+
).sort(),
|
|
660
|
+
)}. Use working-copy delivery or change the ignore rules.`,
|
|
661
|
+
);
|
|
662
|
+
gitRead(cwd, ["var", "GIT_AUTHOR_IDENT"]);
|
|
663
|
+
gitRead(cwd, ["var", "GIT_COMMITTER_IDENT"]);
|
|
664
|
+
}
|
|
665
|
+
return {
|
|
666
|
+
head,
|
|
667
|
+
branch,
|
|
668
|
+
identity: hash(JSON.stringify({ head, branch, contents })),
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
/** Only what a safe fast-forward needs: the same branch and HEAD, and no dirty
|
|
672
|
+
* declared/generated target. Unrelated user changes are left to `merge --ff-only`. */
|
|
673
|
+
export async function assertTarget(
|
|
674
|
+
cwd: string,
|
|
675
|
+
expected: { head: string; branch: string },
|
|
676
|
+
scope: readonly string[],
|
|
677
|
+
): Promise<void> {
|
|
678
|
+
const head = await gitHead(cwd);
|
|
679
|
+
const branch = (await gitText(cwd, ["symbolic-ref", "HEAD"])).trim();
|
|
680
|
+
if (head !== expected.head || branch !== expected.branch)
|
|
681
|
+
throw new WorkflowRefusal(
|
|
682
|
+
"stale",
|
|
683
|
+
`The target branch changed during the run (expected ${expected.branch} at ${expected.head.slice(0, 12)}); nothing was integrated.`,
|
|
684
|
+
);
|
|
685
|
+
assertVisibleIndex(
|
|
686
|
+
overlapping(scope, indexHidden(await gitText(cwd, INDEX_FLAGS))),
|
|
687
|
+
);
|
|
688
|
+
const dirty = overlapping(scope, await changedPaths(cwd));
|
|
689
|
+
if (dirty.length)
|
|
690
|
+
throw new WorkflowRefusal(
|
|
691
|
+
"conflict",
|
|
692
|
+
`Declared targets changed in the checkout during the run: ${list(dirty)}. Nothing was integrated; the candidate is retained.`,
|
|
693
|
+
);
|
|
694
|
+
}
|
|
695
|
+
export async function tracked(cwd: string, name: string): Promise<boolean> {
|
|
696
|
+
return (
|
|
697
|
+
(await gitRun(cwd, ["ls-files", "--error-unmatch", "--", name])).code === 0
|
|
698
|
+
);
|
|
699
|
+
}
|
|
700
|
+
/** Where a generated note can land: through the candidate when a fast-forward
|
|
701
|
+
* can deliver it, otherwise written directly after integration. */
|
|
702
|
+
export async function documentPlacement(
|
|
703
|
+
cwd: string,
|
|
704
|
+
name: string,
|
|
705
|
+
): Promise<"commit" | "direct"> {
|
|
706
|
+
const dirty =
|
|
707
|
+
(await changedPaths(cwd)).includes(name) ||
|
|
708
|
+
indexHidden(await gitText(cwd, INDEX_FLAGS)).includes(name);
|
|
709
|
+
if (await tracked(cwd, name)) return dirty ? "direct" : "commit";
|
|
710
|
+
if ((await gitRun(cwd, ["check-ignore", "-q", "--", name])).code === 0)
|
|
711
|
+
return "direct";
|
|
712
|
+
return (await pathIdentityAsync(cwd, name)) === null ? "commit" : "direct";
|
|
713
|
+
}
|
|
714
|
+
/** Working-copy scope evidence: identity of every changed path plus `extra`.
|
|
715
|
+
* Outside a Git work tree only `extra` (the declared targets) is observable. */
|
|
716
|
+
export async function workingSnapshot(
|
|
717
|
+
cwd: string,
|
|
718
|
+
extra: readonly string[],
|
|
719
|
+
): Promise<{ git: boolean; paths: Map<string, string | null> }> {
|
|
720
|
+
let changed: string[] = [];
|
|
721
|
+
const inside = await gitRun(cwd, ["rev-parse", "--is-inside-work-tree"]);
|
|
722
|
+
const git = inside.code === 0 && inside.stdout.trim() === "true";
|
|
723
|
+
if (git) {
|
|
724
|
+
const born = await gitRun(cwd, ["rev-parse", "--verify", "HEAD"]);
|
|
725
|
+
changed =
|
|
726
|
+
born.code === 0
|
|
727
|
+
? await changedPaths(cwd)
|
|
728
|
+
: names(
|
|
729
|
+
await gitText(cwd, [
|
|
730
|
+
"ls-files",
|
|
731
|
+
"--cached",
|
|
732
|
+
"--others",
|
|
733
|
+
"--exclude-standard",
|
|
734
|
+
"-z",
|
|
735
|
+
]),
|
|
736
|
+
);
|
|
737
|
+
changed.push(...indexHidden(await gitText(cwd, INDEX_FLAGS)));
|
|
738
|
+
}
|
|
739
|
+
const paths = new Map<string, string | null>();
|
|
740
|
+
for (const p of new Set([...changed, ...extra]))
|
|
741
|
+
paths.set(p, await pathIdentityAsync(cwd, p));
|
|
742
|
+
return { git, paths };
|
|
743
|
+
}
|
|
744
|
+
export function snapshotChanges(
|
|
745
|
+
before: Map<string, string | null>,
|
|
746
|
+
after: Map<string, string | null>,
|
|
747
|
+
): string[] {
|
|
748
|
+
return [...new Set([...before.keys(), ...after.keys()])]
|
|
749
|
+
.filter((p) => (before.get(p) ?? null) !== (after.get(p) ?? null))
|
|
750
|
+
.sort();
|
|
751
|
+
}
|
|
752
|
+
/** Existing package dependencies must be provisioned by plan.setup, never copied implicitly. */
|
|
753
|
+
export async function assertWorktree(root: string, cwd: string): Promise<void> {
|
|
754
|
+
if (!safeDirectory(cwd)) throw new ContractError("stale");
|
|
755
|
+
const real = (p: string) => realpathSync(resolve(p));
|
|
756
|
+
if (
|
|
757
|
+
real((await gitText(cwd, ["rev-parse", "--show-toplevel"])).trim()) !==
|
|
758
|
+
real(cwd)
|
|
759
|
+
)
|
|
760
|
+
throw new ContractError("stale");
|
|
761
|
+
const common = async (p: string) =>
|
|
762
|
+
real(
|
|
763
|
+
resolve(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()),
|
|
764
|
+
);
|
|
765
|
+
if ((await common(root)) !== (await common(cwd)))
|
|
766
|
+
throw new ContractError("stale");
|
|
767
|
+
const marker = resolve(cwd, ".git");
|
|
768
|
+
if (
|
|
769
|
+
!lstatSync(marker).isFile() ||
|
|
770
|
+
!(readBounded(marker, 8192)?.toString("utf8") ?? "").startsWith("gitdir: ")
|
|
771
|
+
)
|
|
772
|
+
throw new ContractError("stale");
|
|
773
|
+
}
|