@abelxiaoxing/cadence 2.0.21 → 2.0.23

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/src/task-store.ts DELETED
@@ -1,593 +0,0 @@
1
- import { spawnSync } from "node:child_process";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import {
4
- closeSync,
5
- constants,
6
- fstatSync,
7
- fsyncSync,
8
- lstatSync,
9
- mkdirSync,
10
- openSync,
11
- readdirSync,
12
- readSync,
13
- realpathSync,
14
- renameSync,
15
- type Stats,
16
- unlinkSync,
17
- writeFileSync,
18
- } from "node:fs";
19
- import { homedir, hostname } from "node:os";
20
- import {
21
- dirname,
22
- isAbsolute,
23
- join,
24
- parse,
25
- relative,
26
- resolve,
27
- sep,
28
- } from "node:path";
29
- import {
30
- decodeCheck,
31
- decodeTask,
32
- MAX_RECORD_BYTES,
33
- object,
34
- type TaskRecord,
35
- validId,
36
- } from "./task-types.ts";
37
- import { diagnosticText } from "./verification-diagnostics.ts";
38
-
39
- function parseRecord(data: Buffer): unknown {
40
- try {
41
- return JSON.parse(data.toString("utf8"));
42
- } catch {
43
- throw new Error("Corrupt JSON state; preserved without reset");
44
- }
45
- }
46
- function absent(error: unknown): boolean {
47
- return object(error) && error.code === "ENOENT";
48
- }
49
- /** Reject links in every existing ancestor. Missing observation never creates paths.
50
- * The readonly hook inspects each existing directory synchronously, including
51
- * the root, before visiting its child. It must not await, mutate or retain state
52
- * as authority for a later call/effect. Legacy/default traversal is unchanged.
53
- */
54
- export function safeDirectory(path: string, create?: boolean): boolean;
55
- export function safeDirectory(
56
- path: string,
57
- create: false,
58
- inspectExisting: (path: string, stat: Stats) => void,
59
- ): boolean;
60
- export function safeDirectory(
61
- path: string,
62
- create = false,
63
- inspectExisting?: (path: string, stat: Stats) => void,
64
- ): boolean {
65
- const full = resolve(path);
66
- const root = parse(full).root;
67
- if (inspectExisting) {
68
- const st = lstatSync(root);
69
- if (!st.isDirectory() || st.isSymbolicLink())
70
- throw new Error("Unsafe directory");
71
- inspectExisting(root, st);
72
- }
73
- let at = root;
74
- for (const part of full.slice(root.length).split(sep).filter(Boolean)) {
75
- at = join(at, part);
76
- let existing: Stats | undefined;
77
- try {
78
- // One no-follow observation per component: a link is never reported as
79
- // a directory, and the inspection sees this same, latest observation.
80
- const checked = lstatSync(at);
81
- if (!checked.isDirectory() || checked.isSymbolicLink())
82
- throw new Error("Unsafe directory");
83
- existing = checked;
84
- } catch (error) {
85
- if (!absent(error)) throw error;
86
- if (!create) return false;
87
- try {
88
- mkdirSync(at, { mode: 0o700 });
89
- } catch (mkdirError) {
90
- if (!object(mkdirError) || mkdirError.code !== "EEXIST")
91
- throw mkdirError;
92
- }
93
- const created = lstatSync(at);
94
- if (!created.isDirectory() || created.isSymbolicLink())
95
- throw new Error("Unsafe directory");
96
- }
97
- // Outside the ENOENT handler: an inspection refusal is never absence and
98
- // must not authorize creation, even if its error happens to carry ENOENT.
99
- if (existing) inspectExisting?.(at, existing);
100
- }
101
- return true;
102
- }
103
- const transientWindows = new Set(["EPERM", "EACCES", "EBUSY"]);
104
- /** Windows refuses to replace, remove or recreate a path while another process
105
- * holds it (a polling reader, antivirus, a delete still pending), which POSIX
106
- * never does. Retry the same operation briefly; `recheck` reasserts the
107
- * caller's expected bytes before every retry, so a retry never overwrites a
108
- * change. Other errors, including EEXIST and ENOENT, keep their meaning. */
109
- export function retryWindowsFileOperation<T>(
110
- operation: () => T,
111
- recheck?: () => void,
112
- ): T {
113
- if (process.platform !== "win32") return operation();
114
- const deadline = performance.now() + 2000;
115
- for (let delay = 2; ; delay = Math.min(delay * 2, 50)) {
116
- try {
117
- return operation();
118
- } catch (error) {
119
- if (
120
- !object(error) ||
121
- !transientWindows.has(String(error.code)) ||
122
- performance.now() >= deadline
123
- )
124
- throw error;
125
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay);
126
- recheck?.();
127
- }
128
- }
129
- }
130
- /** `packaged` reads the installed package's own files (web assets, Agent
131
- * profiles). A package manager may hard-link them into its store (Bun's default
132
- * backend), so a second link is not an alias of workspace or task state; their
133
- * callers bind content instead. Every other read stays single-link. */
134
- export function readBounded(
135
- path: string,
136
- max: number,
137
- packaged = false,
138
- ): Buffer | undefined {
139
- if (!safeDirectory(dirname(path))) return undefined;
140
- let fd: number;
141
- try {
142
- const st = lstatSync(path);
143
- if (
144
- !st.isFile() ||
145
- st.isSymbolicLink() ||
146
- (!packaged && st.nlink !== 1) ||
147
- st.size > max
148
- )
149
- throw new Error("Unsafe or oversized file");
150
- fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
151
- } catch (error) {
152
- if (absent(error)) return undefined;
153
- throw error;
154
- }
155
- try {
156
- const st = fstatSync(fd);
157
- if (!st.isFile() || (!packaged && st.nlink !== 1) || st.size > max)
158
- throw new Error("Unsafe or oversized file");
159
- // Read at most max+1 even if another editor grows the file after stat.
160
- const buffer = Buffer.alloc(max + 1);
161
- let size = 0;
162
- while (size < buffer.length) {
163
- const n = readSync(fd, buffer, size, buffer.length - size, null);
164
- if (!n) break;
165
- size += n;
166
- }
167
- if (size > max) throw new Error("Oversized file");
168
- return buffer.subarray(0, size);
169
- } finally {
170
- closeSync(fd);
171
- }
172
- }
173
-
174
- /** Git observations describe the physical cwd, not inherited alternate
175
- * index/worktree overrides. Root never borrows sudo's original user's trust. */
176
- export function gitEnvironment(): NodeJS.ProcessEnv {
177
- const root = process.getuid?.() === 0;
178
- return {
179
- ...Object.fromEntries(
180
- Object.entries(process.env).filter(
181
- ([name]) => !name.startsWith("GIT_") && !(root && name === "SUDO_UID"),
182
- ),
183
- ),
184
- GIT_OPTIONAL_LOCKS: "0",
185
- LC_ALL: "C",
186
- };
187
- }
188
- /** Observation is not permission to trust another account's repository.
189
- * Even with fsmonitor/textconv/ext-diff disabled, status/diff can invoke clean
190
- * or process filters. Root therefore requires Git's own ownership check, with
191
- * no safe.directory exceptions (including inherited wildcards). No config is
192
- * written and ordinary-user trust behavior stays unchanged. */
193
- export function gitArguments(args: string[]): string[] {
194
- return process.platform !== "win32" && process.getuid?.() === 0
195
- ? ["-c", "safe.directory=", "-c", "core.fsmonitor=false", ...args]
196
- : args;
197
- }
198
- export function resolveWorkspace(cwd: string): { root: string; cwd: string } {
199
- const actual = realpathSync(cwd);
200
- const result = spawnSync(
201
- "git",
202
- gitArguments(["rev-parse", "--show-toplevel"]),
203
- {
204
- cwd: actual,
205
- env: gitEnvironment(),
206
- encoding: "utf8",
207
- timeout: 3000,
208
- maxBuffer: 8192,
209
- windowsHide: true,
210
- },
211
- );
212
- // Remove only Git's record terminator, not valid whitespace in a path.
213
- const topLevel = result.stdout?.replace(
214
- process.platform === "win32" ? /\r?\n$/ : /\n$/,
215
- "",
216
- );
217
- if (result.status === 0 && topLevel)
218
- return { root: realpathSync(topLevel), cwd: actual };
219
- if (result.error && !object(result.error))
220
- throw new Error("Cannot resolve workspace");
221
- if (result.error && object(result.error) && result.error.code !== "ENOENT")
222
- throw new Error("Workspace lookup failed");
223
- // A missing Git executable or a confirmed non-repository is an honest non-Git workspace.
224
- if (!result.error && !result.stderr.includes("not a git repository"))
225
- throw new Error("Git workspace lookup refused");
226
- return { root: actual, cwd: actual };
227
- }
228
- export function defaultStateHome(): string {
229
- const candidate =
230
- process.platform === "win32"
231
- ? process.env.LOCALAPPDATA
232
- : process.env.XDG_STATE_HOME;
233
- if (candidate && !isAbsolute(candidate))
234
- throw new Error("State home must be absolute");
235
- return (
236
- candidate ??
237
- join(
238
- homedir(),
239
- process.platform === "win32" ? "AppData/Local" : ".local/state",
240
- )
241
- );
242
- }
243
- /** Canonical bytes written by save; identity is optimistic record concurrency, not consent. */
244
- function recordText(record: TaskRecord): string {
245
- return `${JSON.stringify(record, null, 2)}\n`;
246
- }
247
- function contentIdentity(text: string | Buffer): string {
248
- return createHash("sha256").update(text).digest("hex");
249
- }
250
- export function savedRecordIdentity(record: TaskRecord): string {
251
- return contentIdentity(recordText(record));
252
- }
253
- /** Resolve ambient aliases, including a missing tail, without creating anything. */
254
- export function canonicalAmbientRoot(path: string): string {
255
- const full = resolve(path);
256
- try {
257
- return realpathSync(full);
258
- } catch (error) {
259
- if (!absent(error)) throw error;
260
- // A dangling alias is not a missing ambient directory.
261
- try {
262
- lstatSync(full);
263
- throw new Error("Dangling ambient root");
264
- } catch (statError) {
265
- if (!absent(statError)) throw statError;
266
- }
267
- const parent = dirname(full);
268
- if (parent === full) throw error;
269
- return join(canonicalAmbientRoot(parent), full.slice(parent.length));
270
- }
271
- }
272
- function privateRootFor(canonicalRoot: string, stateHome: string): string {
273
- return join(
274
- canonicalAmbientRoot(stateHome),
275
- "cadence-assistant-v1",
276
- createHash("sha256").update(canonicalRoot).digest("hex"),
277
- );
278
- }
279
- function contains(root: string, path: string): boolean {
280
- const within = relative(root, resolve(path));
281
- return (
282
- !within ||
283
- (!within.startsWith(`..${sep}`) && within !== ".." && !isAbsolute(within))
284
- );
285
- }
286
- /** Private history, locks and access material must stay outside the working
287
- * copy, or change observation, check freshness and review would see them. */
288
- export function stateHomeInside(
289
- root: string,
290
- stateHome = defaultStateHome(),
291
- ): boolean {
292
- const canonical = realpathSync(root);
293
- return contains(canonical, privateRootFor(canonical, stateHome));
294
- }
295
- /** Also exclude projects *inside* our reserved private namespace. Root access
296
- * does not turn private history/coordination into an ordinary engineering tree.
297
- * Resolves missing tails without creating anything (for explicit project mkdir). */
298
- export function privateWorkspace(
299
- requested: string,
300
- stateHome = defaultStateHome(),
301
- ): boolean {
302
- return contains(
303
- join(canonicalAmbientRoot(stateHome), "cadence-assistant-v1"),
304
- canonicalAmbientRoot(requested),
305
- );
306
- }
307
- /** A project must be explicit and outside private state. Never choose, create or
308
- * reconstruct a default workspace. The workbench itself has no project cwd. */
309
- export function effectiveWorkspace(
310
- requested: string,
311
- stateHome?: string,
312
- _home?: string,
313
- ): { workspace: string; redirected: boolean } {
314
- if (
315
- privateWorkspace(requested, stateHome) ||
316
- stateHomeInside(resolveWorkspace(requested).root, stateHome)
317
- )
318
- throw new Error(
319
- "Choose a project outside Cadence private state; no default workspace was created",
320
- );
321
- return { workspace: requested, redirected: false };
322
- }
323
- export interface CheckoutLock {
324
- schema: "cadence-assistant-lock/1";
325
- token: string;
326
- pid: number;
327
- host: string;
328
- runId: string;
329
- root: string;
330
- }
331
- export class TaskStore {
332
- readonly root: string;
333
- readonly tasks: string;
334
- readonly privateRoot: string;
335
- constructor(root: string, stateHome = defaultStateHome()) {
336
- this.root = realpathSync(root);
337
- if (privateWorkspace(this.root, stateHome))
338
- throw new Error("Private state cannot be a workspace");
339
- this.tasks = join(this.root, ".cadence", "assistant", "tasks");
340
- this.privateRoot = privateRootFor(this.root, stateHome);
341
- if (contains(this.root, this.privateRoot))
342
- throw new Error("Private state home must be outside the working copy");
343
- }
344
- get lockPath(): string {
345
- return join(this.privateRoot, "checkout.lock");
346
- }
347
- private inspectPrivate(): void {
348
- const namespace = dirname(this.privateRoot);
349
- for (const path of [namespace, this.privateRoot]) {
350
- if (!safeDirectory(path)) continue;
351
- const st = lstatSync(path);
352
- if (
353
- process.platform !== "win32" &&
354
- ((st.mode & 0o077) !== 0 ||
355
- (process.getuid && st.uid !== process.getuid()))
356
- )
357
- throw new Error("Private state permissions refused");
358
- }
359
- }
360
- private inspectPrivateFile(path: string, max: number): void {
361
- this.inspectPrivate();
362
- if (!safeDirectory(this.privateRoot)) return;
363
- try {
364
- const st = lstatSync(path);
365
- if (
366
- !st.isFile() ||
367
- st.isSymbolicLink() ||
368
- st.nlink !== 1 ||
369
- st.size > max ||
370
- (process.platform !== "win32" &&
371
- ((st.mode & 0o077) !== 0 ||
372
- (process.getuid && st.uid !== process.getuid())))
373
- )
374
- throw new Error("Unsafe private state file");
375
- } catch (error) {
376
- if (!absent(error)) throw error;
377
- }
378
- }
379
- inspectLock(): CheckoutLock | undefined {
380
- this.inspectPrivateFile(this.lockPath, 8192);
381
- const data = readBounded(this.lockPath, 8192);
382
- if (!data) return undefined;
383
- const lock: unknown = parseRecord(data);
384
- if (
385
- !object(lock) ||
386
- lock.schema !== "cadence-assistant-lock/1" ||
387
- lock.root !== this.root ||
388
- typeof lock.token !== "string" ||
389
- !validId(lock.token) ||
390
- typeof lock.runId !== "string" ||
391
- !validId(lock.runId) ||
392
- typeof lock.host !== "string" ||
393
- !Number.isInteger(lock.pid) ||
394
- Number(lock.pid) < 1
395
- )
396
- throw new Error("Unknown or corrupt coordination lock");
397
- return lock as unknown as CheckoutLock;
398
- }
399
- acquire(): CheckoutLock {
400
- this.inspectPrivate();
401
- safeDirectory(this.privateRoot, true);
402
- const lock: CheckoutLock = {
403
- schema: "cadence-assistant-lock/1",
404
- token: randomUUID(),
405
- runId: randomUUID(),
406
- pid: process.pid,
407
- host: hostname(),
408
- root: this.root,
409
- };
410
- let fd: number;
411
- try {
412
- fd = retryWindowsFileOperation(() =>
413
- openSync(this.lockPath, "wx", 0o600),
414
- );
415
- } catch {
416
- throw new Error(
417
- "Checkout busy or unresolved lock; inspect and explicitly recover only a dead owner",
418
- );
419
- }
420
- try {
421
- writeFileSync(fd, JSON.stringify(lock));
422
- fsyncSync(fd);
423
- } finally {
424
- closeSync(fd);
425
- }
426
- return lock;
427
- }
428
- assertOwner(lock: CheckoutLock): void {
429
- if (JSON.stringify(this.inspectLock()) !== JSON.stringify(lock))
430
- throw new Error("Coordination lock changed");
431
- }
432
- release(lock: CheckoutLock): void {
433
- if (lock.pid !== process.pid || lock.host !== hostname())
434
- throw new Error("Only the owning process may release a lock");
435
- this.assertOwner(lock);
436
- retryWindowsFileOperation(
437
- () => unlinkSync(this.lockPath),
438
- () => this.assertOwner(lock),
439
- );
440
- }
441
- recover(expected: CheckoutLock, acknowledgeEscapedProcesses: boolean): void {
442
- if (!acknowledgeEscapedProcesses || expected.host !== hostname())
443
- throw new Error("Recovery requires informed local-owner confirmation");
444
- this.assertOwner(expected);
445
- try {
446
- process.kill(expected.pid, 0);
447
- } catch (error) {
448
- if (!object(error) || error.code !== "ESRCH")
449
- throw new Error("Owner status unknown");
450
- this.assertOwner(expected);
451
- unlinkSync(this.lockPath);
452
- return;
453
- }
454
- throw new Error("Owner is live; stop it first");
455
- }
456
- load(id: string): TaskRecord | undefined {
457
- return this.loadSnapshot(id)?.record;
458
- }
459
- loadSnapshot(
460
- id: string,
461
- ): { record: TaskRecord; identity: string } | undefined {
462
- if (!validId(id)) throw new Error("Invalid task id");
463
- const directory = join(this.tasks, id);
464
- if (
465
- safeDirectory(directory) &&
466
- readdirSync(directory).some((name) => name !== "task.json")
467
- )
468
- throw new Error(
469
- "Unknown task directory content; preserved without reset",
470
- );
471
- const data = readBounded(
472
- join(this.tasks, id, "task.json"),
473
- MAX_RECORD_BYTES,
474
- );
475
- if (!data) return undefined;
476
- const record = decodeTask(parseRecord(data));
477
- if (record.id !== id) throw new Error("Task identity mismatch");
478
- return { record, identity: contentIdentity(data) };
479
- }
480
- list(): TaskRecord[] {
481
- if (!safeDirectory(this.tasks)) return [];
482
- const entries = readdirSync(this.tasks);
483
- if (entries.length > 1000) throw new Error("Task listing limit exceeded");
484
- return entries.map((id) => {
485
- const task = this.load(id);
486
- if (!task) throw new Error("Unknown task directory");
487
- return task;
488
- });
489
- }
490
- save(
491
- record: TaskRecord,
492
- expectedRevision: number,
493
- held?: CheckoutLock,
494
- expectedIdentity?: string,
495
- ): TaskRecord {
496
- const next = decodeTask(record);
497
- if (next.revision !== expectedRevision + 1)
498
- throw new Error("Revision conflict");
499
- const text = recordText(next);
500
- if (Buffer.byteLength(text) > MAX_RECORD_BYTES)
501
- throw new Error("Task record limit");
502
- const lock = held ?? this.acquire();
503
- if (lock.pid !== process.pid || lock.host !== hostname())
504
- throw new Error("Not the lock owner");
505
- try {
506
- this.assertOwner(lock);
507
- const current = this.loadSnapshot(next.id);
508
- if ((current?.record.revision ?? 0) !== expectedRevision)
509
- throw new Error("Revision conflict");
510
- if (current?.identity !== expectedIdentity)
511
- throw new Error("Task content changed; reopen it");
512
- const dir = join(this.tasks, next.id);
513
- safeDirectory(dir, true);
514
- // Unknown sibling state is not overwritten or cleaned.
515
- if (!current && readdirSync(dir).length)
516
- throw new Error("Unknown task directory");
517
- const temporary = join(dir, `task.${randomUUID()}.tmp`);
518
- const fd = openSync(temporary, "wx", 0o600);
519
- try {
520
- writeFileSync(fd, text);
521
- fsyncSync(fd);
522
- } finally {
523
- closeSync(fd);
524
- }
525
- this.assertOwner(lock);
526
- // Check again after preparing the replacement. External editors do not share our lock;
527
- // this detects observed conflicts, not an atomic filesystem CAS against hostile writers.
528
- const latest = readBounded(join(dir, "task.json"), MAX_RECORD_BYTES);
529
- if ((latest ? contentIdentity(latest) : undefined) !== expectedIdentity)
530
- throw new Error(
531
- "Task content changed; replacement preserved without overwrite",
532
- );
533
- retryWindowsFileOperation(
534
- () => renameSync(temporary, join(dir, "task.json")),
535
- () => {
536
- this.assertOwner(lock);
537
- const now = readBounded(join(dir, "task.json"), MAX_RECORD_BYTES);
538
- if ((now ? contentIdentity(now) : undefined) !== expectedIdentity)
539
- throw new Error(
540
- "Task content changed; replacement preserved without overwrite",
541
- );
542
- },
543
- );
544
- return next;
545
- } finally {
546
- if (!held) this.release(lock);
547
- }
548
- }
549
- checks() {
550
- const data = readBounded(
551
- join(this.root, ".cadence", "assistant", "config.json"),
552
- 32768,
553
- );
554
- if (!data) return [];
555
- const value: unknown = parseRecord(data);
556
- if (
557
- !object(value) ||
558
- value.schema !== TASK_CONFIG_SCHEMA ||
559
- !Array.isArray(value.checks) ||
560
- value.checks.length > 32 ||
561
- Object.keys(value).some((key) => !["schema", "checks"].includes(key))
562
- )
563
- throw new Error("Unknown check configuration");
564
- const checks = value.checks.map(decodeCheck);
565
- if (
566
- new Set(checks.map((check) => check.name)).size !== checks.length ||
567
- checks.some((check) => check.name === "Manual command")
568
- )
569
- throw new Error("Duplicate or reserved check name");
570
- return checks;
571
- }
572
- readLog(name: string): string {
573
- if (!/^[a-f0-9-]{36}\.log$/.test(name))
574
- throw new Error("Invalid diagnostic name");
575
- this.inspectPrivateFile(join(this.privateRoot, name), 65536);
576
- const data = readBounded(join(this.privateRoot, name), 65536);
577
- return data
578
- ? diagnosticText(data.toString("utf8"), 65536)
579
- : "Private diagnostic unavailable";
580
- }
581
- writeLog(lock: CheckoutLock, output: string): string {
582
- if (lock.pid !== process.pid || lock.host !== hostname())
583
- throw new Error("Not the lock owner");
584
- this.assertOwner(lock);
585
- const name = `${randomUUID()}.log`;
586
- writeFileSync(join(this.privateRoot, name), diagnosticText(output, 65536), {
587
- flag: "wx",
588
- mode: 0o600,
589
- });
590
- return name;
591
- }
592
- }
593
- export const TASK_CONFIG_SCHEMA = "cadence-assistant-checks/1";