cadre-ai 2.1.0 → 2.2.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.
@@ -1,3365 +0,0 @@
1
- #!/usr/bin/env node
2
- // AUTO-GENERATED by pnpm build from src/*.ts -- do not edit by hand.
3
- // Edit TypeScript sources under src/ instead.
4
- "use strict";
5
- var __create = Object.create;
6
- var __defProp = Object.defineProperty;
7
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
- var __getOwnPropNames = Object.getOwnPropertyNames;
9
- var __getProtoOf = Object.getPrototypeOf;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
-
33
- // src/cadre-job-runner.ts
34
- var cadre_job_runner_exports = {};
35
- __export(cadre_job_runner_exports, {
36
- readStdin: () => readStdin,
37
- runJob: () => runJob,
38
- runJobRunner: () => runJobRunner
39
- });
40
- module.exports = __toCommonJS(cadre_job_runner_exports);
41
- var import_node_path23 = __toESM(require("node:path"));
42
-
43
- // src/guards.ts
44
- function isRecord(value) {
45
- return typeof value === "object" && value !== null && !Array.isArray(value);
46
- }
47
- function asJsonObject(value) {
48
- return isRecord(value) ? value : {};
49
- }
50
- function asString(value, fallback = "") {
51
- return typeof value === "string" ? value : fallback;
52
- }
53
- function asOptionalString(value) {
54
- return typeof value === "string" ? value : void 0;
55
- }
56
- function asNumber(value, fallback = 0) {
57
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
58
- }
59
- function asStringArray(value) {
60
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
61
- }
62
- function errorMessage(error) {
63
- return error instanceof Error ? error.message : String(error);
64
- }
65
- function errorCode(error) {
66
- return isRecord(error) && typeof error.code === "string" ? error.code : void 0;
67
- }
68
-
69
- // src/core/infrastructure/runtime/json-store.ts
70
- var import_node_fs2 = __toESM(require("node:fs"));
71
- var import_node_path2 = __toESM(require("node:path"));
72
- var import_node_crypto = __toESM(require("node:crypto"));
73
-
74
- // src/core/infrastructure/runtime/locking.ts
75
- var import_node_fs = __toESM(require("node:fs"));
76
- var import_node_path = __toESM(require("node:path"));
77
- var import_node_os = __toESM(require("node:os"));
78
-
79
- // src/core/domain/lease-policy.ts
80
- var STALE_LEASE_MS = 30 * 60 * 1e3;
81
- var LOCK_STALE_MS = STALE_LEASE_MS;
82
-
83
- // src/core/infrastructure/runtime/system.ts
84
- var import_node_child_process = require("node:child_process");
85
- function gitIdentity(root) {
86
- for (const key of ["user.email", "user.name"]) {
87
- const result = (0, import_node_child_process.spawnSync)("git", ["config", key], {
88
- cwd: root,
89
- encoding: "utf8"
90
- });
91
- if (result.status === 0 && result.stdout.trim()) {
92
- return result.stdout.trim();
93
- }
94
- }
95
- return null;
96
- }
97
- function runCommand(command, args, options = {}) {
98
- const result = (0, import_node_child_process.spawnSync)(command, args, {
99
- cwd: options.cwd,
100
- encoding: "utf8",
101
- shell: options.shell === true,
102
- timeout: options.timeoutMs,
103
- maxBuffer: options.maxBuffer || 10 * 1024 * 1024
104
- });
105
- const commandResult = {
106
- ok: result.status === 0,
107
- status: result.status,
108
- signal: result.signal || null,
109
- stdout: result.stdout || "",
110
- stderr: result.stderr || "",
111
- command: options.shell === true ? command : [command, ...args].join(" "),
112
- args
113
- };
114
- if (options.cwd !== void 0) commandResult.cwd = options.cwd;
115
- return commandResult;
116
- }
117
- function parsePorcelainFiles(text) {
118
- return String(text || "").split(/\r?\n/).filter(Boolean).flatMap((line) => {
119
- const raw = line.slice(3).trim();
120
- if (!raw) return [];
121
- if (raw.includes(" -> ")) return [raw.split(" -> ").pop() ?? ""];
122
- return [raw.replace(/^"|"$/g, "")];
123
- }).filter(Boolean);
124
- }
125
- function isControlPlaneFile(file) {
126
- const normalized = String(file || "").replace(/\\/g, "/").replace(/^\.\//, "");
127
- if (!normalized) return true;
128
- if (normalized.startsWith("cadre/")) return true;
129
- if (normalized === ".gitattributes" || normalized === ".gitmodules") return true;
130
- if (normalized === "cadre-merge-train.gitlab-ci.yml") return true;
131
- if (normalized === ".gitlab-ci.yml") return true;
132
- if (normalized.startsWith(".github/workflows/cadre-")) return true;
133
- return false;
134
- }
135
- function controlPlaneSyncSafety(root, mode, remote, branch) {
136
- const status = runCommand("git", ["status", "--porcelain"], { cwd: root });
137
- const dirtyFiles = parsePorcelainFiles(status.stdout);
138
- const unsafeDirtyFiles = dirtyFiles.filter((file) => !isControlPlaneFile(file));
139
- const safety = {
140
- ok: true,
141
- mode,
142
- remote,
143
- branch,
144
- dirty_files: dirtyFiles,
145
- unsafe_dirty_files: unsafeDirtyFiles,
146
- ahead_files: [],
147
- unsafe_ahead_files: [],
148
- warnings: []
149
- };
150
- if (!status.ok) {
151
- return { ...safety, ok: false, reason: "Unable to inspect git status", status };
152
- }
153
- if (unsafeDirtyFiles.length > 0) {
154
- return {
155
- ...safety,
156
- ok: false,
157
- reason: "Working tree has non-control-plane changes; refusing control-plane sync"
158
- };
159
- }
160
- if (mode !== "post") return safety;
161
- const remoteRef = `${remote}/${branch}`;
162
- const fetch = runCommand("git", ["fetch", "--quiet", remote, branch], { cwd: root });
163
- const rev = runCommand("git", ["rev-parse", "--verify", remoteRef], { cwd: root });
164
- let diff;
165
- if (fetch.ok && rev.ok) {
166
- diff = runCommand("git", ["diff", "--name-only", `${remoteRef}..HEAD`], { cwd: root });
167
- } else {
168
- return {
169
- ...safety,
170
- ok: false,
171
- reason: `Unable to verify ${remoteRef}; refusing control-plane post-sync rather than classifying only the last commit`,
172
- fetch,
173
- rev
174
- };
175
- }
176
- const aheadFiles = diff.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
177
- const unsafeAheadFiles = aheadFiles.filter((file) => !isControlPlaneFile(file));
178
- safety.ahead_files = aheadFiles;
179
- safety.unsafe_ahead_files = unsafeAheadFiles;
180
- if (!diff.ok) {
181
- return { ...safety, ok: false, reason: "Unable to classify unpushed commits", diff };
182
- }
183
- if (unsafeAheadFiles.length > 0) {
184
- return {
185
- ...safety,
186
- ok: false,
187
- reason: "Unpushed commits include non-control-plane files; refusing control-plane push"
188
- };
189
- }
190
- return safety;
191
- }
192
-
193
- // src/core/infrastructure/runtime/locking.ts
194
- function lockRoot(root) {
195
- return import_node_path.default.join(root, "cadre", ".locks");
196
- }
197
- function processAlive(pid) {
198
- const numeric = Number(pid);
199
- if (!Number.isInteger(numeric) || numeric <= 0) return false;
200
- try {
201
- process.kill(numeric, 0);
202
- return true;
203
- } catch (error) {
204
- return errorCode(error) === "EPERM";
205
- }
206
- }
207
- function readLockInfo(lockDir) {
208
- return readJson(import_node_path.default.join(lockDir, "owner.json"), null) ?? {};
209
- }
210
- function lockIsStale(info, nowMs = Date.now()) {
211
- const stamp = Date.parse(info.updated_at || info.acquired_at || "");
212
- if (Number.isFinite(stamp) && nowMs - stamp > LOCK_STALE_MS) return true;
213
- if (info.pid && !processAlive(info.pid)) return true;
214
- return false;
215
- }
216
- function acquireLock(root, name, options = {}) {
217
- const now = utcNow();
218
- const dir = import_node_path.default.join(lockRoot(root), `${safeName(name)}.lock`);
219
- import_node_fs.default.mkdirSync(import_node_path.default.dirname(dir), { recursive: true });
220
- for (let attempt = 1; attempt <= Number(options.retries || 3); attempt += 1) {
221
- try {
222
- import_node_fs.default.mkdirSync(dir);
223
- const info = {
224
- name,
225
- pid: process.pid,
226
- owner: options.owner || gitIdentity(root) || null,
227
- acquired_at: now,
228
- updated_at: now,
229
- hostname: import_node_os.default.hostname()
230
- };
231
- writeJson(import_node_path.default.join(dir, "owner.json"), info);
232
- return { ok: true, dir, info, attempts: attempt };
233
- } catch (error) {
234
- if (errorCode(error) !== "EEXIST") {
235
- return { ok: false, dir, error: errorMessage(error), attempts: attempt };
236
- }
237
- const current = readLockInfo(dir);
238
- if (lockIsStale(current)) {
239
- try {
240
- import_node_fs.default.rmSync(dir, { recursive: true, force: true });
241
- continue;
242
- } catch (removeError) {
243
- return {
244
- ok: false,
245
- dir,
246
- conflict: true,
247
- stale: true,
248
- holder: current,
249
- error: errorMessage(removeError),
250
- attempts: attempt
251
- };
252
- }
253
- }
254
- return {
255
- ok: false,
256
- dir,
257
- conflict: true,
258
- stale: false,
259
- holder: current,
260
- error: `Lock already held: ${name}`,
261
- attempts: attempt
262
- };
263
- }
264
- }
265
- return { ok: false, dir, conflict: true, error: `Unable to acquire lock: ${name}` };
266
- }
267
- function releaseLock(lock) {
268
- if (!lock || !lock.ok || !lock.dir) return { ok: true, skipped: true };
269
- try {
270
- import_node_fs.default.rmSync(lock.dir, { recursive: true, force: true });
271
- return { ok: true };
272
- } catch (error) {
273
- return { ok: false, error: errorMessage(error) };
274
- }
275
- }
276
- function withLock(root, name, fn, options = {}) {
277
- const lock = acquireLock(root, name, options);
278
- if (!lock.ok) return { ok: false, stage: "lock", lock };
279
- try {
280
- const value = fn(lock);
281
- if (value && typeof value === "object" && !Array.isArray(value)) {
282
- return Object.prototype.hasOwnProperty.call(value, "ok") ? { ...value, lock } : { ok: true, value, lock };
283
- }
284
- return { ok: true, value, lock };
285
- } catch (error) {
286
- return { ok: false, stage: "locked_operation", error: errorMessage(error), lock };
287
- } finally {
288
- releaseLock(lock);
289
- }
290
- }
291
- function trackLockName(trackId) {
292
- return `track:${trackId}`;
293
- }
294
- function withTrackLock(root, trackId, fn, options = {}) {
295
- return withLock(root, trackLockName(trackId), fn, options);
296
- }
297
-
298
- // src/core/infrastructure/runtime/json-store.ts
299
- function readJson(file, fallback) {
300
- try {
301
- return JSON.parse(import_node_fs2.default.readFileSync(file, "utf8"));
302
- } catch {
303
- return fallback;
304
- }
305
- }
306
- function writeJson(file, value) {
307
- const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
308
- import_node_fs2.default.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
309
- `);
310
- import_node_fs2.default.renameSync(tmp, file);
311
- }
312
- function safeName(value) {
313
- return String(value || "lock").replace(/[^A-Za-z0-9_.-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 160) || "lock";
314
- }
315
- function textHash(text) {
316
- return import_node_crypto.default.createHash("sha256").update(String(text || "")).digest("hex");
317
- }
318
- function patchJsonFileUnlocked(file, patcher, options = {}) {
319
- const retries = Number(options.retries || 5);
320
- for (let attempt = 1; attempt <= retries; attempt += 1) {
321
- let beforeText;
322
- try {
323
- beforeText = import_node_fs2.default.readFileSync(file, "utf8");
324
- } catch (error) {
325
- return { ok: false, file, error: `Unable to read JSON file: ${errorMessage(error)}` };
326
- }
327
- let before;
328
- try {
329
- before = asJsonObject(JSON.parse(beforeText || "{}"));
330
- } catch (error) {
331
- return { ok: false, file, error: `Invalid JSON: ${errorMessage(error)}` };
332
- }
333
- const beforeHash = textHash(beforeText);
334
- let next;
335
- try {
336
- next = patcher({ ...before }, before);
337
- } catch (error) {
338
- return { ok: false, file, error: `JSON patcher failed: ${errorMessage(error)}` };
339
- }
340
- if (!next || typeof next !== "object") {
341
- return { ok: false, file, error: "JSON patcher must return an object" };
342
- }
343
- let latestText;
344
- try {
345
- latestText = import_node_fs2.default.readFileSync(file, "utf8");
346
- } catch (error) {
347
- return { ok: false, file, error: `Unable to re-read JSON file: ${errorMessage(error)}` };
348
- }
349
- if (textHash(latestText) !== beforeHash) continue;
350
- writeJson(file, next);
351
- return {
352
- ok: true,
353
- file,
354
- attempts: attempt,
355
- before_hash: beforeHash,
356
- after_hash: textHash(`${JSON.stringify(next, null, 2)}
357
- `),
358
- value: next
359
- };
360
- }
361
- return {
362
- ok: false,
363
- file,
364
- error: `JSON file changed during patch after ${retries} retries`,
365
- conflict: true
366
- };
367
- }
368
- function patchJsonFile(file, patcher, options = {}) {
369
- if (options.root && options.lockName && options.lock !== false) {
370
- return withLock(options.root, options.lockName, () => patchJsonFileUnlocked(file, patcher, { ...options, lock: false }), options.lockOptions || {});
371
- }
372
- return patchJsonFileUnlocked(file, patcher, options);
373
- }
374
- function utcNow() {
375
- return (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
376
- }
377
- function fileExists(file) {
378
- try {
379
- return import_node_fs2.default.existsSync(file);
380
- } catch {
381
- return false;
382
- }
383
- }
384
- function ensureParent(file) {
385
- import_node_fs2.default.mkdirSync(import_node_path2.default.dirname(file), { recursive: true });
386
- }
387
- function appendJsonl(file, value) {
388
- ensureParent(file);
389
- import_node_fs2.default.appendFileSync(file, `${JSON.stringify(value)}
390
- `);
391
- }
392
-
393
- // src/core/application/runtime/plan-docs.ts
394
- var import_node_path18 = __toESM(require("node:path"));
395
-
396
- // src/core/infrastructure/runtime/project-config.ts
397
- var import_node_path3 = __toESM(require("node:path"));
398
- function loadTopology(root) {
399
- const reposPath = import_node_path3.default.join(root, "cadre", "repos.json");
400
- const configPath2 = import_node_path3.default.join(root, "cadre", "config.json");
401
- const repos = readJson(reposPath, null);
402
- const config = readJson(configPath2, {});
403
- const polyrepo = Boolean(repos && repos.mode === "polyrepo");
404
- return {
405
- polyrepo,
406
- repos: asJsonObject(repos || {}),
407
- config,
408
- defaultRepo: polyrepo ? asString(repos?.default_repo, ".") : "."
409
- };
410
- }
411
- function loadPackageJson(root) {
412
- return readJson(import_node_path3.default.join(root, "package.json"), null);
413
- }
414
- function configuredCoverageCommand(root, args = {}, workingRoot = root) {
415
- if (args.command) return String(args.command);
416
- const topology = loadTopology(root);
417
- const config = topology.config || {};
418
- for (const key of ["coverage_command", "test_coverage_command", "test_command"]) {
419
- const value = config[key];
420
- if (typeof value === "string" && value.trim()) return value.trim();
421
- }
422
- const pkg = loadPackageJson(workingRoot);
423
- const scripts = isRecord(pkg?.scripts) ? pkg.scripts : null;
424
- if (scripts) {
425
- for (const name of ["coverage", "test:coverage", "test:cov", "test"]) {
426
- if (scripts[name]) {
427
- if (fileExists(import_node_path3.default.join(workingRoot, "pnpm-lock.yaml"))) return `pnpm ${name}`;
428
- if (fileExists(import_node_path3.default.join(workingRoot, "yarn.lock"))) return `yarn ${name}`;
429
- return `npm run ${name}`;
430
- }
431
- }
432
- }
433
- if (fileExists(import_node_path3.default.join(workingRoot, "pyproject.toml")) || fileExists(import_node_path3.default.join(workingRoot, "pytest.ini"))) {
434
- return "pytest --cov --cov-report=term";
435
- }
436
- if (fileExists(import_node_path3.default.join(workingRoot, "go.mod"))) return "go test ./...";
437
- return null;
438
- }
439
- function parseCoveragePercent(text) {
440
- const source = String(text || "");
441
- const patterns = [
442
- /All files[^|\n]*(?:\|[^|\n]*){3,}\|\s*([0-9]+(?:\.[0-9]+)?)\s*(?:\||$)/i,
443
- /\bStatements\s*:\s*([0-9]+(?:\.[0-9]+)?)%/i,
444
- /\bLines\s*:\s*([0-9]+(?:\.[0-9]+)?)%/i,
445
- /\bTOTAL\b[^\n%]*\s([0-9]+(?:\.[0-9]+)?)%/i,
446
- /\bcoverage[^0-9%]{0,40}([0-9]+(?:\.[0-9]+)?)%/i
447
- ];
448
- for (const pattern of patterns) {
449
- const match = source.match(pattern);
450
- if (match?.[1]) return Number(match[1]);
451
- }
452
- return null;
453
- }
454
-
455
- // src/core/application/runtime/track-schedule.ts
456
- var import_node_fs10 = __toESM(require("node:fs"));
457
- var import_node_path17 = __toESM(require("node:path"));
458
-
459
- // src/core/infrastructure/runtime/coverage.ts
460
- var import_node_fs3 = __toESM(require("node:fs"));
461
- var import_node_path4 = __toESM(require("node:path"));
462
- function parseLcovCoverage(root) {
463
- const candidates = [
464
- import_node_path4.default.join(root, "coverage", "lcov.info"),
465
- import_node_path4.default.join(root, "lcov.info")
466
- ];
467
- for (const file of candidates) {
468
- if (!fileExists(file)) continue;
469
- const text = import_node_fs3.default.readFileSync(file, "utf8");
470
- let found = 0;
471
- let hit = 0;
472
- for (const line of text.split(/\r?\n/)) {
473
- if (line.startsWith("LF:")) found += Number(line.slice(3)) || 0;
474
- if (line.startsWith("LH:")) hit += Number(line.slice(3)) || 0;
475
- }
476
- if (found > 0) return Math.round(hit / found * 1e4) / 100;
477
- }
478
- return null;
479
- }
480
- function coverageThreshold(root) {
481
- const topology = loadTopology(root);
482
- const config = topology.config || {};
483
- for (const key of ["coverage_threshold", "minimum_coverage", "min_coverage"]) {
484
- const value = Number(config[key]);
485
- if (Number.isFinite(value) && value >= 0) return value;
486
- }
487
- const workflowPath = import_node_path4.default.join(root, "cadre", "workflow.json");
488
- const workflow = readJson(workflowPath, null);
489
- if (workflow) {
490
- const text = JSON.stringify(workflow);
491
- const match = text.match(/(?:coverage|test coverage)[^%]{0,120}?([0-9]+(?:\.[0-9]+)?)\s*%/i);
492
- if (match?.[1]) return Number(match[1]);
493
- }
494
- return 80;
495
- }
496
- function runCoverage(root, args = {}, workingRoot = root) {
497
- const command = configuredCoverageCommand(root, args, workingRoot);
498
- if (!command) {
499
- return {
500
- ok: false,
501
- available: false,
502
- command: null,
503
- coverage: null,
504
- reason: "No coverage/test command configured or detected",
505
- hints: [
506
- "Set cadre/config.json coverage_command",
507
- "Add package.json scripts.coverage or scripts.test:coverage",
508
- "Pass { command } explicitly to cadre_complete_task"
509
- ]
510
- };
511
- }
512
- const timeoutMs = Number(args.timeoutMs || 10 * 60 * 1e3);
513
- const result = runCommand(command, [], {
514
- cwd: workingRoot,
515
- shell: true,
516
- timeoutMs,
517
- maxBuffer: 30 * 1024 * 1024
518
- });
519
- const combined = `${result.stdout}
520
- ${result.stderr}`;
521
- const parsed = parseCoveragePercent(combined);
522
- const lcov = parsed == null ? parseLcovCoverage(workingRoot) : null;
523
- const coverage = parsed == null ? lcov : parsed;
524
- return {
525
- ok: result.ok,
526
- available: true,
527
- command,
528
- cwd: workingRoot,
529
- status: result.status,
530
- signal: result.signal,
531
- coverage,
532
- coverage_source: parsed == null && lcov != null ? "lcov" : parsed != null ? "output" : null,
533
- timed_out: result.signal === "SIGTERM" || result.signal === "SIGKILL",
534
- stdout_tail: result.stdout.slice(-4e3),
535
- stderr_tail: result.stderr.slice(-4e3),
536
- result
537
- };
538
- }
539
- function parseIsoTime(value) {
540
- if (typeof value !== "string" || value.trim() === "") return null;
541
- const time = Date.parse(value);
542
- return Number.isFinite(time) ? time : null;
543
- }
544
- function staleInfo(value, now = Date.now()) {
545
- const time = parseIsoTime(value);
546
- if (!time) return { stale: false, age_minutes: null };
547
- const ageMs = Math.max(0, now - time);
548
- return {
549
- stale: ageMs > STALE_LEASE_MS,
550
- age_minutes: Math.floor(ageMs / 6e4)
551
- };
552
- }
553
-
554
- // src/core/application/runtime/repo-resolution.ts
555
- var import_node_path16 = __toESM(require("node:path"));
556
-
557
- // src/lsp/language-registry.ts
558
- var import_node_fs4 = __toESM(require("node:fs"));
559
- var import_node_path6 = __toESM(require("node:path"));
560
- var import_node_child_process2 = require("node:child_process");
561
-
562
- // src/lsp/ignore-policy.ts
563
- var import_node_path5 = __toESM(require("node:path"));
564
- var DEFAULT_IGNORES = /* @__PURE__ */ new Set([
565
- ".git",
566
- ".hg",
567
- ".svn",
568
- ".worktrees",
569
- ".agents",
570
- ".claude",
571
- ".cache",
572
- ".codex",
573
- ".copilot",
574
- ".dart_tool",
575
- ".gemini",
576
- ".gradle",
577
- ".mypy_cache",
578
- ".pytest_cache",
579
- ".ruff_cache",
580
- ".serverless",
581
- "node_modules",
582
- "vendor",
583
- "dist",
584
- "build",
585
- "coverage",
586
- "out",
587
- "target",
588
- ".next",
589
- ".nuxt",
590
- ".parcel-cache",
591
- ".svelte-kit",
592
- ".turbo",
593
- ".vite",
594
- ".venv",
595
- "venv",
596
- "__pycache__",
597
- "__generated__",
598
- "generated",
599
- "gen",
600
- "tmp",
601
- "temp",
602
- "logs",
603
- "Pods",
604
- "DerivedData",
605
- ".idea",
606
- ".vscode"
607
- ]);
608
- var DEFAULT_IGNORE_PATHS = [
609
- "plugins/cadre",
610
- "plugins/cadre-claude",
611
- "plugins/cadre-copilot",
612
- "plugins/cadre-antigravity"
613
- ];
614
- function normalizeRel(file) {
615
- return file.split(import_node_path5.default.sep).join("/");
616
- }
617
- function shouldIgnore(root, fullPath, name) {
618
- if (DEFAULT_IGNORES.has(name)) return true;
619
- const rel = normalizeRel(import_node_path5.default.relative(root, fullPath));
620
- return DEFAULT_IGNORE_PATHS.some(
621
- (ignored) => rel === ignored || rel.startsWith(`${ignored}/`)
622
- );
623
- }
624
-
625
- // src/lsp/language-registry.ts
626
- var EXTENSION_LANGUAGE_IDS = {
627
- ".js": "javascript",
628
- ".jsx": "javascript",
629
- ".ts": "typescript",
630
- ".tsx": "typescript",
631
- ".py": "python",
632
- ".go": "go",
633
- ".rs": "rust",
634
- ".java": "java",
635
- ".kt": "kotlin",
636
- ".kts": "kotlin",
637
- ".swift": "swift",
638
- ".rb": "ruby",
639
- ".php": "php",
640
- ".dart": "dart",
641
- ".html": "html",
642
- ".htm": "html",
643
- ".css": "css",
644
- ".scss": "css",
645
- ".sass": "css",
646
- ".less": "css",
647
- ".json": "json",
648
- ".jsonc": "json",
649
- ".yaml": "yaml",
650
- ".yml": "yaml",
651
- ".md": "markdown",
652
- ".mdx": "markdown",
653
- ".toml": "toml",
654
- ".lua": "lua",
655
- ".sh": "shell",
656
- ".bash": "shell",
657
- ".zsh": "shell",
658
- ".ksh": "shell",
659
- ".tf": "terraform",
660
- ".tfvars": "terraform",
661
- ".hcl": "terraform",
662
- ".ex": "elixir",
663
- ".exs": "elixir",
664
- ".scala": "scala",
665
- ".sc": "scala",
666
- ".clj": "clojure",
667
- ".cljs": "clojure",
668
- ".cljc": "clojure",
669
- ".hs": "haskell",
670
- ".lhs": "haskell",
671
- ".ml": "ocaml",
672
- ".mli": "ocaml",
673
- ".zig": "zig",
674
- ".nix": "nix",
675
- ".elm": "elm",
676
- ".vue": "vue",
677
- ".svelte": "svelte",
678
- ".xml": "xml",
679
- ".xsd": "xml",
680
- ".xsl": "xml",
681
- ".xslt": "xml",
682
- ".graphql": "graphql",
683
- ".gql": "graphql",
684
- ".prisma": "prisma",
685
- ".proto": "protobuf",
686
- ".c": "c-cpp",
687
- ".h": "c-cpp",
688
- ".cc": "c-cpp",
689
- ".cpp": "c-cpp",
690
- ".cxx": "c-cpp",
691
- ".hpp": "c-cpp",
692
- ".m": "c-cpp",
693
- ".mm": "c-cpp",
694
- ".cs": "csharp"
695
- };
696
- var FILE_LANGUAGE_IDS = {
697
- Dockerfile: "dockerfile",
698
- Containerfile: "dockerfile"
699
- };
700
- function fileLanguageId(file) {
701
- return FILE_LANGUAGE_IDS[import_node_path6.default.basename(file)] || EXTENSION_LANGUAGE_IDS[import_node_path6.default.extname(file).toLowerCase()] || null;
702
- }
703
- function languageForFile(file) {
704
- return fileLanguageId(file);
705
- }
706
- function normalizeWorkspaceFile(root, rel) {
707
- const normalized = rel.replace(/\r/g, "").trim();
708
- if (!normalized) return null;
709
- const full = import_node_path6.default.join(root, normalized);
710
- if (shouldIgnore(root, full, import_node_path6.default.basename(normalized))) return null;
711
- return normalized;
712
- }
713
- function gitWorkspaceFiles(root) {
714
- const result = (0, import_node_child_process2.spawnSync)("git", ["ls-files", "-co", "--exclude-standard", "-z"], {
715
- cwd: root,
716
- encoding: "buffer",
717
- maxBuffer: 30 * 1024 * 1024
718
- });
719
- if (result.status !== 0 || !result.stdout || result.stdout.length === 0) return [];
720
- return result.stdout.toString("utf8").split("\0").map((item) => normalizeWorkspaceFile(root, item)).filter((item) => Boolean(item)).sort();
721
- }
722
- function walkWorkspaceFiles(root) {
723
- const files = [];
724
- const visit = (dir) => {
725
- let entries;
726
- try {
727
- entries = import_node_fs4.default.readdirSync(dir, { withFileTypes: true });
728
- } catch {
729
- return;
730
- }
731
- for (const entry of entries) {
732
- const full = import_node_path6.default.join(dir, entry.name);
733
- if (shouldIgnore(root, full, entry.name)) continue;
734
- if (entry.isDirectory()) {
735
- visit(full);
736
- continue;
737
- }
738
- if (entry.isFile()) files.push(import_node_path6.default.relative(root, full).split(import_node_path6.default.sep).join("/"));
739
- }
740
- };
741
- visit(root);
742
- return files.sort();
743
- }
744
- function listWorkspaceFiles(root) {
745
- const gitFiles = gitWorkspaceFiles(root);
746
- return gitFiles.length > 0 ? gitFiles : walkWorkspaceFiles(root);
747
- }
748
-
749
- // src/core/application/runtime/branch-set.ts
750
- var import_node_fs5 = __toESM(require("node:fs"));
751
- var import_node_path7 = __toESM(require("node:path"));
752
- var MONOREPO_REPO_KEY = "root";
753
- function repoSegment(repo) {
754
- return safeName(repo === "." ? MONOREPO_REPO_KEY : repo);
755
- }
756
- function gitBranch(cwd) {
757
- const result = runCommand("git", ["branch", "--show-current"], { cwd });
758
- return result.ok ? result.stdout.trim() || null : null;
759
- }
760
- function gitRoot(cwd) {
761
- const result = runCommand("git", ["rev-parse", "--show-toplevel"], { cwd });
762
- return result.ok ? import_node_path7.default.resolve(result.stdout.trim() || cwd) : null;
763
- }
764
- function branchExists(cwd, branch) {
765
- return runCommand("git", ["rev-parse", "--verify", "--quiet", branch], { cwd }).ok;
766
- }
767
- function taskRepos(root, track) {
768
- const topology = loadTopology(root);
769
- if (!topology.polyrepo) return /* @__PURE__ */ new Set([MONOREPO_REPO_KEY]);
770
- const repos = /* @__PURE__ */ new Set();
771
- const defaultRepo = asOptionalString(topology.defaultRepo);
772
- for (const task of parsePlanFile(track.plan_path).tasks || []) {
773
- const repo = asOptionalString(task.repo) || defaultRepo;
774
- if (repo) repos.add(repo);
775
- }
776
- const metadataRepos = isRecord(track.metadata.repos) ? track.metadata.repos : null;
777
- if (metadataRepos) {
778
- for (const [repo, rawInfo] of Object.entries(metadataRepos)) {
779
- const info = asJsonObject(rawInfo);
780
- if (info.affected === true || info.git_branch || info.worktree_path) repos.add(repo);
781
- }
782
- }
783
- return repos;
784
- }
785
- function branchSetForTrack(root, track, args = {}) {
786
- const topology = loadTopology(root);
787
- const requestedRepo = asOptionalString(args.repo);
788
- const affected = taskRepos(root, track);
789
- if (topology.polyrepo) {
790
- const metadataRepos = isRecord(track.metadata.repos) ? track.metadata.repos : {};
791
- const topoRepos = Array.isArray(topology.repos.repos) ? topology.repos.repos.map(asJsonObject) : [];
792
- const byName = /* @__PURE__ */ new Map();
793
- for (const rawRepo of topoRepos) {
794
- const name = asOptionalString(rawRepo.name);
795
- if (name) byName.set(name, rawRepo);
796
- }
797
- for (const [repo, rawInfo] of Object.entries(metadataRepos)) {
798
- if (!byName.has(repo)) byName.set(repo, { name: repo, ...asJsonObject(rawInfo) });
799
- }
800
- const repoRows = Array.from(byName.values());
801
- return repoRows.filter((rawRepo) => {
802
- const repo = asOptionalString(rawRepo.name);
803
- return Boolean(repo && (!requestedRepo || requestedRepo === repo) && affected.has(repo));
804
- }).map((rawRepo) => {
805
- const repo = asString(rawRepo.name);
806
- const info = {
807
- submodule_path: asOptionalString(rawRepo.submodule_path) || "",
808
- base_branch: asOptionalString(rawRepo.default_branch) || asOptionalString(rawRepo.base_branch) || "main",
809
- ...isRecord(metadataRepos[repo]) ? asJsonObject(metadataRepos[repo]) : {}
810
- };
811
- return branchSetEntry(root, track, repo, info, args, true);
812
- });
813
- }
814
- if (requestedRepo && requestedRepo !== "." && requestedRepo !== MONOREPO_REPO_KEY) return [];
815
- return [branchSetEntry(root, track, MONOREPO_REPO_KEY, {}, args, false)];
816
- }
817
- function branchSetEntry(root, track, repo, info, args, polyrepo) {
818
- const segment = repoSegment(repo);
819
- const sourceRel = polyrepo ? asOptionalString(info.submodule_path) || "" : ".";
820
- const sourceRoot = polyrepo && sourceRel ? import_node_path7.default.resolve(root, sourceRel) : root;
821
- const baseBranch = asOptionalString(args.base) || asOptionalString(info.base_branch) || "main";
822
- const trackBranch = asOptionalString(args.head) || asOptionalString(args.branch) || asOptionalString(info.git_branch) || asOptionalString(track.metadata.git_branch) || `track/${track.track_id}`;
823
- const legacyPath = repo === MONOREPO_REPO_KEY ? asOptionalString(track.metadata.worktree_path) : asOptionalString(info.worktree_path);
824
- const relIntegration = legacyPath || import_node_path7.default.join(".worktrees", "cadre", "tracks", safeName(track.track_id), "integrate", segment);
825
- const integrationWorktree = import_node_path7.default.resolve(root, relIntegration);
826
- const workerRoot = import_node_path7.default.resolve(root, ".worktrees", "cadre", "tracks", safeName(track.track_id), "workers", segment);
827
- const exists = fileExists(integrationWorktree);
828
- const currentBranch = exists ? gitBranch(integrationWorktree) : null;
829
- const expectedRoot = gitRoot(sourceRoot);
830
- const actualRoot = exists ? gitRoot(integrationWorktree) : null;
831
- const wrongRepo = Boolean(exists && expectedRoot && actualRoot && expectedRoot !== actualRoot);
832
- const wrongBranch = Boolean(exists && currentBranch && currentBranch !== trackBranch);
833
- const health = !exists ? "missing" : wrongRepo ? "wrong_repo" : wrongBranch ? "wrong_branch" : "ready";
834
- return {
835
- repo,
836
- repo_segment: segment,
837
- source_root: sourceRoot,
838
- source_path: sourceRel,
839
- base_branch: baseBranch,
840
- track_branch: trackBranch,
841
- integration_worktree: integrationWorktree,
842
- integration_worktree_path: import_node_path7.default.relative(root, integrationWorktree) || ".",
843
- worker_root: workerRoot,
844
- worker_root_path: import_node_path7.default.relative(root, workerRoot) || ".",
845
- affected: true,
846
- exists,
847
- current_branch: currentBranch,
848
- health,
849
- branch_exists: branchExists(sourceRoot, trackBranch),
850
- commands: integrationCommands(sourceRoot, integrationWorktree, trackBranch, baseBranch, exists)
851
- };
852
- }
853
- function integrationCommands(sourceRoot, integrationWorktree, branch, base, exists) {
854
- if (exists) return [];
855
- return [{
856
- command: "git",
857
- args: ["worktree", "add", integrationWorktree, branch],
858
- fallback_args: ["worktree", "add", "-b", branch, integrationWorktree, base],
859
- cwd: sourceRoot
860
- }];
861
- }
862
- function ensureIntegrationWorktree(entry) {
863
- if (entry.exists) {
864
- if (entry.health !== "ready") return { ok: false, stage: "integration_worktree_health", entry, error: `Integration worktree for ${entry.repo} is ${entry.health}` };
865
- return { ok: true, entry, created: false };
866
- }
867
- import_node_fs5.default.mkdirSync(import_node_path7.default.dirname(entry.integration_worktree), { recursive: true });
868
- const args = entry.branch_exists ? ["worktree", "add", entry.integration_worktree, entry.track_branch] : ["worktree", "add", "-b", entry.track_branch, entry.integration_worktree, entry.base_branch];
869
- const result = runCommand("git", args, { cwd: entry.source_root });
870
- return {
871
- ok: result.ok,
872
- entry: { ...entry, exists: result.ok, current_branch: result.ok ? entry.track_branch : entry.current_branch, health: result.ok ? "ready" : entry.health },
873
- created: result.ok,
874
- command: { command: "git", args, cwd: entry.source_root },
875
- result
876
- };
877
- }
878
- function branchSetEntryForRepo(root, track, repo, args = {}) {
879
- return branchSetForTrack(root, track, { ...args, repo: repo === MONOREPO_REPO_KEY ? void 0 : repo }).find((entry) => entry.repo === repo || repo === "." && entry.repo === MONOREPO_REPO_KEY) || null;
880
- }
881
- function taskRepo(root, task, args = {}) {
882
- const topology = loadTopology(root);
883
- if (!topology.polyrepo) return MONOREPO_REPO_KEY;
884
- return asString(args.repo || task?.repo || topology.defaultRepo);
885
- }
886
-
887
- // src/core/application/runtime/track-context.ts
888
- var import_node_path8 = __toESM(require("node:path"));
889
- function findTrack(root, trackId) {
890
- return listTracks(root).find((item) => item.track_id === trackId) || null;
891
- }
892
- function trackContext(root, trackId) {
893
- const track = findTrack(root, trackId);
894
- if (!track) return { ok: false, error: `Track not found: ${trackId}` };
895
- const topology = loadTopology(root);
896
- const plan = parsePlanFile(track.plan_path);
897
- const hold = holdInfo(track);
898
- const branchSet = branchSetForTrack(root, track);
899
- const worktrees = [];
900
- if (track.metadata.worktree_path) {
901
- const abs = import_node_path8.default.resolve(root, track.metadata.worktree_path);
902
- worktrees.push({
903
- repo: ".",
904
- path: track.metadata.worktree_path,
905
- exists: fileExists(abs),
906
- git_branch: track.metadata.git_branch || `track/${track.track_id}`
907
- });
908
- }
909
- const reposMetadata = isRecord(track.metadata.repos) ? track.metadata.repos : null;
910
- if (reposMetadata) {
911
- for (const [repo, rawInfo] of Object.entries(reposMetadata)) {
912
- const info = asJsonObject(rawInfo);
913
- const submodulePath = info.submodule_path || "";
914
- const worktreePath = info.worktree_path || "";
915
- worktrees.push({
916
- repo,
917
- submodule_path: submodulePath,
918
- path: worktreePath,
919
- exists: worktreePath ? fileExists(import_node_path8.default.resolve(root, worktreePath)) : false,
920
- git_branch: info.git_branch || `track/${track.track_id}`,
921
- base_branch: info.base_branch || "main"
922
- });
923
- }
924
- }
925
- return {
926
- ok: true,
927
- root,
928
- topology: {
929
- polyrepo: topology.polyrepo,
930
- default_repo: topology.defaultRepo,
931
- sync_mode: topology.config.sync_mode || "local"
932
- },
933
- track: {
934
- track_id: track.track_id,
935
- status: track.metadata.status || "new",
936
- name: track.metadata.name || track.metadata.description || track.track_id,
937
- priority: track.metadata.priority || "medium",
938
- owner: track.metadata.owner || null,
939
- reviewer: track.metadata.reviewer || null,
940
- git_branch: track.metadata.git_branch || `track/${track.track_id}`,
941
- metadata_path: import_node_path8.default.relative(root, track.metadata_path || import_node_path8.default.join(track.dir, "metadata.json")),
942
- plan_path: import_node_path8.default.relative(root, track.plan_path),
943
- spec_path: import_node_path8.default.relative(root, track.spec_path),
944
- tags: asStringArray(track.metadata.tags),
945
- review: track.metadata.review || null,
946
- last_coverage: track.metadata.last_coverage ?? null
947
- },
948
- hold,
949
- task_counts: taskCounts(plan),
950
- plan,
951
- branch_set: branchSet,
952
- worktrees
953
- };
954
- }
955
-
956
- // src/core/application/runtime/quality-gates.ts
957
- var import_node_fs9 = __toESM(require("node:fs"));
958
- var import_node_path15 = __toESM(require("node:path"));
959
-
960
- // src/runtime-paths.ts
961
- var import_node_path9 = __toESM(require("node:path"));
962
- function unique(values) {
963
- return Array.from(new Set(values));
964
- }
965
- function mcpServerPathCandidates(root) {
966
- const candidates = [];
967
- let dir = __dirname;
968
- for (let depth = 0; depth < 8; depth += 1) {
969
- candidates.push(import_node_path9.default.join(dir, "cadre-server.js"));
970
- candidates.push(import_node_path9.default.join(dir, "mcp", "cadre-server.js"));
971
- candidates.push(import_node_path9.default.join(dir, "scripts", "mcp", "cadre-server.js"));
972
- const parent = import_node_path9.default.dirname(dir);
973
- if (parent === dir) break;
974
- dir = parent;
975
- }
976
- if (root) candidates.push(import_node_path9.default.join(root, "cadre", "scripts", "mcp", "cadre-server.js"));
977
- return unique(candidates);
978
- }
979
-
980
- // src/core/application/runtime/project-maintenance.ts
981
- function lspReview(root, args = {}) {
982
- const candidates = mcpServerPathCandidates(root);
983
- const helper = candidates.find(fileExists);
984
- if (!helper) return { available: false, reason: "No Cadre MCP runtime found for LSP review", checked: candidates };
985
- const commandArgs = [helper, "--cadre-lsp-review", "--base", args.base || "main", "--head", args.head || "HEAD", "--json"];
986
- if (args.config) commandArgs.push("--config", args.config);
987
- const result = runCommand("node", commandArgs, { cwd: root });
988
- if (!result.ok) {
989
- return { available: false, reason: "LSP review helper failed", helper, result };
990
- }
991
- try {
992
- return { helper, ...asJsonObject(JSON.parse(result.stdout || "{}")) };
993
- } catch {
994
- return { available: false, reason: "LSP review helper returned invalid JSON", helper, result };
995
- }
996
- }
997
-
998
- // src/core/application/runtime/repo-map.ts
999
- var import_node_fs6 = __toESM(require("node:fs"));
1000
- var import_node_path11 = __toESM(require("node:path"));
1001
-
1002
- // src/core/application/runtime/workspace-cache.ts
1003
- var import_node_child_process3 = require("node:child_process");
1004
- var import_node_path10 = __toESM(require("node:path"));
1005
- var CACHE = /* @__PURE__ */ new Map();
1006
- var DEFAULT_TTL_MS = 3e4;
1007
- function gitHead(root) {
1008
- const result = (0, import_node_child_process3.spawnSync)("git", ["rev-parse", "HEAD"], {
1009
- cwd: root,
1010
- encoding: "utf8",
1011
- maxBuffer: 1024 * 1024
1012
- });
1013
- return result.status === 0 ? result.stdout.trim() || "unknown" : "nogit";
1014
- }
1015
- function workspaceCacheKey(root, scope, discriminator = "") {
1016
- return JSON.stringify({
1017
- root: import_node_path10.default.resolve(root),
1018
- head: gitHead(root),
1019
- scope,
1020
- discriminator
1021
- });
1022
- }
1023
- function cachedWorkspaceValue(root, scope, discriminator, producer, ttlMs = DEFAULT_TTL_MS) {
1024
- const key = workspaceCacheKey(root, scope, discriminator);
1025
- const now = Date.now();
1026
- const existing = CACHE.get(key);
1027
- if (existing && now - existing.createdAt <= ttlMs) return existing.value;
1028
- const value = producer();
1029
- CACHE.set(key, { value, createdAt: now });
1030
- if (CACHE.size > 200) {
1031
- const oldest = Array.from(CACHE.entries()).sort((a, b) => a[1].createdAt - b[1].createdAt).slice(0, 40);
1032
- for (const [oldKey] of oldest) CACHE.delete(oldKey);
1033
- }
1034
- return value;
1035
- }
1036
-
1037
- // src/core/application/runtime/repo-map.ts
1038
- function isIgnoredRepoMapFile(file) {
1039
- const normalized = String(file || "").replace(/\\/g, "/");
1040
- if (!normalized) return true;
1041
- if (normalized.startsWith(".agents/")) return true;
1042
- if (normalized.startsWith(".claude/")) return true;
1043
- if (normalized.startsWith(".claude-plugin/")) return true;
1044
- if (normalized.startsWith(".copilot/")) return true;
1045
- if (normalized.startsWith(".gemini/")) return true;
1046
- if (normalized.startsWith("plugins/cadre/")) return true;
1047
- if (normalized.startsWith("plugins/cadre-claude/")) return true;
1048
- if (normalized.startsWith("plugins/cadre-copilot/")) return true;
1049
- if (normalized.startsWith("plugins/cadre-antigravity/")) return true;
1050
- return normalized.split("/").some((part) => [".git", "node_modules", "dist", "build", "coverage"].includes(part));
1051
- }
1052
- function selectedRepoNames(args = {}) {
1053
- const values = [
1054
- asOptionalString(args.repo),
1055
- ...asStringArray(args.repos)
1056
- ].filter((value) => Boolean(value));
1057
- return values.length > 0 ? new Set(values) : null;
1058
- }
1059
- function intelRepoRoots(root, args = {}) {
1060
- const selected = selectedRepoNames(args);
1061
- const topology = loadTopology(root);
1062
- const control = {
1063
- repo: ".",
1064
- root,
1065
- path: ".",
1066
- source: "control-root"
1067
- };
1068
- if (!topology.polyrepo) return selected && !selected.has(".") ? [] : [control];
1069
- const entries = [control];
1070
- for (const raw of Array.isArray(topology.repos.repos) ? topology.repos.repos : []) {
1071
- const repo = asJsonObject(raw);
1072
- if (repo.enabled === false) continue;
1073
- const name = asOptionalString(repo.name);
1074
- const rel = asOptionalString(repo.submodule_path);
1075
- if (!name || !rel) continue;
1076
- entries.push({
1077
- repo: name,
1078
- root: import_node_path11.default.resolve(root, rel),
1079
- path: rel,
1080
- source: "repos.json"
1081
- });
1082
- }
1083
- return selected ? entries.filter((entry) => selected.has(entry.repo)) : entries;
1084
- }
1085
- function combineLanguageCounts(entries) {
1086
- const counts = {};
1087
- for (const entry of entries) {
1088
- const languages = asJsonObject(entry.by_language);
1089
- for (const [language, count] of Object.entries(languages)) {
1090
- counts[language] = (counts[language] || 0) + Number(count || 0);
1091
- }
1092
- }
1093
- return Object.fromEntries(Object.entries(counts).sort());
1094
- }
1095
- var GENERIC_SYMBOL_PATTERNS = [
1096
- /\b(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\b/g,
1097
- /\b(?:export\s+)?(?:class|interface|type|enum|struct|record|trait)\s+([A-Za-z_$][\w$]*)\b/g,
1098
- /\bexport\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*[:=]/g
1099
- ];
1100
- var LANGUAGE_SYMBOL_PATTERNS = {
1101
- python: [/^\s*(?:async\s+)?def\s+([A-Za-z_][\w]*)\b/gm, /^\s*class\s+([A-Za-z_][\w]*)\b/gm],
1102
- go: [/^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_][\w]*)\b/gm, /^\s*type\s+([A-Za-z_][\w]*)\s+/gm],
1103
- rust: [/^\s*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_][\w]*)\b/gm, /^\s*(?:pub\s+)?(?:struct|enum|trait|type)\s+([A-Za-z_][\w]*)\b/gm],
1104
- java: [/^\s*(?:public|private|protected|static|final|abstract|sealed|non-sealed|\s)*(?:class|interface|enum|record)\s+([A-Za-z_][\w]*)\b/gm, /^\s*(?:public|private|protected|static|final|abstract|synchronized|native|\s)*[\w<>\[\].?,\s]+\s+([A-Za-z_][\w]*)\s*\(/gm],
1105
- kotlin: [/^\s*(?:public|private|protected|internal|open|final|abstract|data|sealed|\s)*(?:class|interface|object|enum|typealias)\s+([A-Za-z_][\w]*)\b/gm, /^\s*(?:public|private|protected|internal|suspend|inline|tailrec|operator|infix|fun|\s)*fun\s+([A-Za-z_][\w]*)\b/gm],
1106
- swift: [/^\s*(?:public|private|internal|open|fileprivate|static|final|mutating|nonmutating|\s)*(?:func|class|struct|enum|protocol)\s+([A-Za-z_][\w]*)\b/gm],
1107
- csharp: [/^\s*(?:public|private|protected|internal|static|partial|sealed|abstract|virtual|override|\s)*(?:class|interface|record|struct|enum)\s+([A-Za-z_][\w]*)\b/gm, /^\s*(?:public|private|protected|internal|static|async|\s)*[\w<>\[\].?,\s]+\s+([A-Za-z_][\w]*)\s*\(/gm],
1108
- ruby: [/^\s*(?:class|module|def)\s+([A-Za-z_][\w!?=]*)\b/gm],
1109
- elixir: [/^\s*(?:defmodule|defp?|defmacro)\s+([A-Za-z_][\w!?]*)\b/gm],
1110
- lua: [/^\s*(?:local\s+)?function\s+([A-Za-z_][\w.]*)\b/gm],
1111
- terraform: [/^\s*(?:resource|module|variable|output|data)\s+"?([A-Za-z0-9_.-]+)"?/gim],
1112
- sql: [/^\s*(?:CREATE\s+(?:OR\s+REPLACE\s+)?)?(?:TABLE|VIEW|FUNCTION|PROCEDURE|TYPE)\s+([A-Za-z_][\w."]*)\b/gim],
1113
- shell: [/^\s*function\s+([A-Za-z_][\w-]*)\b/gm, /^\s*(?:local\s+)?([A-Za-z_][\w-]*)\s*\(\)\s*\{/gm]
1114
- };
1115
- function symbolPatternsForLanguage(language) {
1116
- return [...GENERIC_SYMBOL_PATTERNS, ...LANGUAGE_SYMBOL_PATTERNS[language] || []].map(
1117
- (pattern) => new RegExp(pattern.source, pattern.flags)
1118
- );
1119
- }
1120
- function extractRepoSymbols(root, file, limitPerFile = 40) {
1121
- const abs = import_node_path11.default.join(root, file);
1122
- if (!fileExists(abs)) return [];
1123
- let stat;
1124
- try {
1125
- stat = import_node_fs6.default.statSync(abs);
1126
- } catch {
1127
- return [];
1128
- }
1129
- if (stat.size > 1024 * 1024) return [];
1130
- const language = languageForFile(file);
1131
- if (!language) return [];
1132
- const text = import_node_fs6.default.readFileSync(abs, "utf8");
1133
- const patterns = symbolPatternsForLanguage(language);
1134
- const symbols = [];
1135
- for (const pattern of patterns) {
1136
- let match;
1137
- while ((match = pattern.exec(text)) && symbols.length < limitPerFile) {
1138
- const prefix = text.slice(0, match.index);
1139
- const line = prefix.split(/\r?\n/).length;
1140
- const name = match[1];
1141
- if (name) symbols.push({ name, file, line, language });
1142
- }
1143
- }
1144
- return symbols;
1145
- }
1146
- function repoMap(root, args = {}) {
1147
- const limit = Number(args.limit || 200);
1148
- const symbol = args.symbol ? String(args.symbol) : null;
1149
- const repos = intelRepoRoots(root, args);
1150
- if (symbol) {
1151
- const repoResults = repos.map((entry) => {
1152
- const result = runCommand("git", ["grep", "-n", "-w", "--", symbol], { cwd: entry.root, maxBuffer: 10 * 1024 * 1024 });
1153
- const matches2 = result.stdout.split(/\r?\n/).filter(Boolean).filter((line) => !isIgnoredRepoMapFile(line.split(":")[0] || "")).slice(0, limit).map((line) => {
1154
- const [file, lineNo, ...rest] = line.split(":");
1155
- return { repo: entry.repo, file: file || "", line: Number(lineNo), snippet: rest.join(":").trim().slice(0, 180) };
1156
- });
1157
- return { repo: entry.repo, root: entry.root, path: entry.path, ok: result.ok || matches2.length > 0, matches: matches2, truncated: matches2.length >= limit };
1158
- });
1159
- const matches = repoResults.flatMap((entry) => asArray(entry.matches)).slice(0, limit);
1160
- return { ok: repoResults.some((entry) => entry.ok) || matches.length > 0, root, symbol, matches, repos: repoResults, truncated: matches.length >= limit };
1161
- }
1162
- return cachedWorkspaceValue(root, "repo-map", JSON.stringify({ limit, repos: repos.map((entry) => entry.repo) }), () => {
1163
- const repoResults = repos.map((entry) => {
1164
- const files2 = listWorkspaceFiles(entry.root).filter((file) => !isIgnoredRepoMapFile(file));
1165
- const byLanguage = {};
1166
- const symbols2 = [];
1167
- for (const file of files2) {
1168
- const language = languageForFile(file);
1169
- if (language) byLanguage[language] = (byLanguage[language] || 0) + 1;
1170
- if (symbols2.length < limit) symbols2.push(...extractRepoSymbols(entry.root, file, 12).map((symbolEntry) => ({
1171
- ...symbolEntry,
1172
- repo: entry.repo
1173
- })));
1174
- if (symbols2.length > limit) symbols2.length = limit;
1175
- }
1176
- return {
1177
- ok: true,
1178
- repo: entry.repo,
1179
- root: entry.root,
1180
- path: entry.path,
1181
- files: files2.length,
1182
- by_language: Object.fromEntries(Object.entries(byLanguage).sort()),
1183
- symbols: symbols2,
1184
- truncated: symbols2.length >= limit
1185
- };
1186
- });
1187
- const files = repoResults.reduce((sum, entry) => sum + Number(entry.files || 0), 0);
1188
- const symbols = repoResults.flatMap((entry) => asArray(entry.symbols)).slice(0, limit);
1189
- return {
1190
- ok: true,
1191
- root,
1192
- files,
1193
- by_language: combineLanguageCounts(repoResults),
1194
- symbols,
1195
- repos: repoResults,
1196
- truncated: symbols.length >= limit
1197
- };
1198
- });
1199
- }
1200
-
1201
- // src/core/application/runtime/track-mutations.ts
1202
- var import_node_fs8 = __toESM(require("node:fs"));
1203
- var import_node_path14 = __toESM(require("node:path"));
1204
-
1205
- // src/core/domain/track-status.ts
1206
- var STATUS_MARKERS = {
1207
- new: "[ ]",
1208
- in_progress: "[~]",
1209
- completed: "[x]",
1210
- blocked: "[!]",
1211
- skipped: "[-]"
1212
- };
1213
- var VALID_STATUSES = new Set(Object.keys(STATUS_MARKERS));
1214
-
1215
- // src/core/application/runtime/native-state.ts
1216
- var import_node_fs7 = __toESM(require("node:fs"));
1217
- var import_node_path12 = __toESM(require("node:path"));
1218
- function nativeStatePaths(root) {
1219
- return {
1220
- events: import_node_path12.default.join(root, "cadre", "events.jsonl"),
1221
- formulas: import_node_path12.default.join(root, "cadre", "formulas"),
1222
- operations: import_node_path12.default.join(root, "cadre", "operations"),
1223
- messages: import_node_path12.default.join(root, "cadre", "messages"),
1224
- inbox: import_node_path12.default.join(root, "cadre", "messages", "inbox.jsonl"),
1225
- outbox: import_node_path12.default.join(root, "cadre", "messages", "outbox.jsonl"),
1226
- wisps: import_node_path12.default.join(root, "cadre", "local", "wisps")
1227
- };
1228
- }
1229
- function compactStamp(value) {
1230
- return value.replace(/[^0-9A-Za-z]+/g, "").slice(0, 16);
1231
- }
1232
- function nativeId(prefix, payload) {
1233
- const recordedAt = asOptionalString(payload.recorded_at) || utcNow();
1234
- return `${prefix}_${compactStamp(recordedAt)}_${textHash(JSON.stringify(payload)).slice(0, 12)}`;
1235
- }
1236
- function ensureCadreLocalIgnored(root) {
1237
- const cadreDir = import_node_path12.default.join(root, "cadre");
1238
- const ignorePath = import_node_path12.default.join(cadreDir, ".gitignore");
1239
- import_node_fs7.default.mkdirSync(cadreDir, { recursive: true });
1240
- const current = fileExists(ignorePath) ? import_node_fs7.default.readFileSync(ignorePath, "utf8") : "";
1241
- const lines = current.split(/\r?\n/).filter(Boolean);
1242
- if (!lines.includes("/local/")) {
1243
- lines.push("/local/");
1244
- import_node_fs7.default.writeFileSync(ignorePath, `${lines.join("\n")}
1245
- `);
1246
- return import_node_path12.default.relative(root, ignorePath);
1247
- }
1248
- return null;
1249
- }
1250
- function ensureNativeState(root) {
1251
- const paths = nativeStatePaths(root);
1252
- for (const dir of [
1253
- asOptionalString(paths.formulas),
1254
- asOptionalString(paths.operations),
1255
- asOptionalString(paths.messages),
1256
- asOptionalString(paths.wisps)
1257
- ].filter((value) => Boolean(value))) {
1258
- import_node_fs7.default.mkdirSync(dir, { recursive: true });
1259
- }
1260
- const ignore_path = ensureCadreLocalIgnored(root);
1261
- return {
1262
- ok: true,
1263
- paths: {
1264
- events: import_node_path12.default.relative(root, String(paths.events)),
1265
- formulas: import_node_path12.default.relative(root, String(paths.formulas)),
1266
- operations: import_node_path12.default.relative(root, String(paths.operations)),
1267
- messages: import_node_path12.default.relative(root, String(paths.messages)),
1268
- wisps: import_node_path12.default.relative(root, String(paths.wisps))
1269
- },
1270
- ignore_path
1271
- };
1272
- }
1273
- function appendCadreEvent(root, event) {
1274
- ensureNativeState(root);
1275
- const recorded_at = asOptionalString(event.recorded_at) || utcNow();
1276
- const kind = asOptionalString(event.kind || event.type) || "event";
1277
- const actor = asOptionalString(event.actor) || gitIdentity(root) || null;
1278
- const entry = {
1279
- ...event,
1280
- version: 1,
1281
- schema: "cadre.event.v1",
1282
- id: asOptionalString(event.id) || nativeId("evt", { ...event, recorded_at, kind }),
1283
- kind,
1284
- recorded_at,
1285
- actor
1286
- };
1287
- const file = import_node_path12.default.join(root, "cadre", "events.jsonl");
1288
- appendJsonl(file, entry);
1289
- return { ok: true, path: import_node_path12.default.relative(root, file), event: entry };
1290
- }
1291
-
1292
- // src/core/application/runtime/commit-trace.ts
1293
- var import_node_path13 = __toESM(require("node:path"));
1294
- var DEFAULT_NOTES_REF = "refs/notes/cadre";
1295
- function configured(root) {
1296
- return fileExists(import_node_path13.default.join(root, "cadre", "config.json"));
1297
- }
1298
- function traceability(root) {
1299
- return asJsonObject(loadTopology(root).config.traceability);
1300
- }
1301
- function traceEnabled(root, kind, args, force = false) {
1302
- const mode = asOptionalString(args.commitMode || args.commit_mode)?.toLowerCase();
1303
- if (["off", "none", "manual", "false"].includes(mode || "")) return false;
1304
- if (force) return true;
1305
- if (!configured(root)) return false;
1306
- const trace = traceability(root);
1307
- if (Object.keys(trace).length === 0) return false;
1308
- if (trace.enabled === false) return false;
1309
- if (kind === "product") return trace.auto_product_commits !== false;
1310
- if (kind === "control") return trace.auto_control_commits !== false;
1311
- return trace.auto_automation_commits !== false;
1312
- }
1313
- function notesRef(root, args = {}) {
1314
- return asOptionalString(args.notesRef || args.notes_ref) || asOptionalString(traceability(root).notes_ref) || DEFAULT_NOTES_REF;
1315
- }
1316
- function notesEnabled(root) {
1317
- const trace = traceability(root);
1318
- return trace.git_notes !== false && trace.notes !== false;
1319
- }
1320
- function statusEntries(cwd) {
1321
- const result = runCommand("git", ["status", "--porcelain", "--untracked-files=all"], { cwd });
1322
- if (!result.ok) return {};
1323
- const entries = {};
1324
- for (const line of result.stdout.split(/\r?\n/)) {
1325
- if (!line.trim()) continue;
1326
- const status = line.slice(0, 2);
1327
- const rawPath = line.slice(3).trim();
1328
- const file = rawPath.includes(" -> ") ? rawPath.split(" -> ").pop() || "" : rawPath;
1329
- const normalized = file.replace(/^"|"$/g, "");
1330
- if (normalized) entries[normalized] = status;
1331
- }
1332
- return entries;
1333
- }
1334
- function beginTrace(cwd) {
1335
- const gitRoot2 = runCommand("git", ["rev-parse", "--show-toplevel"], { cwd });
1336
- if (!gitRoot2.ok) {
1337
- return {
1338
- ok: true,
1339
- cwd,
1340
- entries: {},
1341
- dirty_files: [],
1342
- skipped: true,
1343
- reason: "not a git repository"
1344
- };
1345
- }
1346
- const root = gitRoot2.stdout.trim() || cwd;
1347
- const entries = statusEntries(root);
1348
- return {
1349
- ok: true,
1350
- cwd: root,
1351
- git_root: root,
1352
- entries,
1353
- dirty_files: Object.keys(entries).sort()
1354
- };
1355
- }
1356
- function isControlPlaneFile2(file) {
1357
- const normalized = file.replace(/\\/g, "/").replace(/^\.\//, "");
1358
- if (normalized.startsWith("cadre/local/")) return false;
1359
- if (normalized.startsWith("cadre/.locks/")) return false;
1360
- if (normalized.includes(".tmp")) return false;
1361
- return normalized.startsWith("cadre/") || normalized === ".gitattributes" || normalized === ".gitmodules" || normalized === ".gitlab-ci.yml" || normalized === "cadre-merge-train.gitlab-ci.yml" || normalized.startsWith(".github/workflows/cadre-");
1362
- }
1363
- function changedAfter(before, after) {
1364
- const beforeEntries = asJsonObject(before?.entries);
1365
- return Object.entries(after).filter(([file, status]) => beforeEntries[file] !== status).map(([file]) => file).sort();
1366
- }
1367
- function uniqueFiles(files) {
1368
- return Array.from(new Set(files.map((file) => file.replace(/\\/g, "/").replace(/^\.\//, "")).filter(Boolean))).sort();
1369
- }
1370
- function conventionalSubject(type, scope, subject) {
1371
- const cleanType = type.replace(/[^a-z0-9-]/gi, "").toLowerCase() || "cadre";
1372
- const cleanScope = scope.replace(/[^a-z0-9_.-]/gi, "-").toLowerCase() || "trace";
1373
- return `${cleanType}(${cleanScope}): ${subject.trim() || "record trace"}`;
1374
- }
1375
- function messageBody(body, footers) {
1376
- const footerText = Object.entries(footers).filter((entry) => Boolean(entry[1])).map(([key, value]) => `${key}: ${value}`).join("\n");
1377
- return [body?.trim() || "", footerText].filter(Boolean).join("\n\n");
1378
- }
1379
- function commandOk(result) {
1380
- return result.ok === true;
1381
- }
1382
- function commitSha(cwd) {
1383
- const result = runCommand("git", ["rev-parse", "HEAD"], { cwd });
1384
- return result.ok ? result.stdout.trim() || null : null;
1385
- }
1386
- function writeNote(cwd, ref, sha, note) {
1387
- return runCommand("git", ["notes", "--ref", ref, "add", "-f", "-m", `${JSON.stringify(note, null, 2)}
1388
- `, sha], { cwd });
1389
- }
1390
- function commitTrace(root, args, options) {
1391
- if (!traceEnabled(root, options.kind, args, options.forceEnabled === true)) {
1392
- return { ok: true, skipped: true, reason: "traceability disabled or unconfigured" };
1393
- }
1394
- const cwd = options.cwd || root;
1395
- const snapshot = options.before || beginTrace(cwd);
1396
- if (snapshot.skipped) return { ok: true, skipped: true, reason: snapshot.reason || "git unavailable" };
1397
- const gitRoot2 = asOptionalString(snapshot.git_root) || cwd;
1398
- const after = statusEntries(gitRoot2);
1399
- const requestedFiles = options.files ? uniqueFiles(options.files) : uniqueFiles([
1400
- ...changedAfter(snapshot, after).filter((file) => options.kind === "product" ? !isControlPlaneFile2(file) : isControlPlaneFile2(file)),
1401
- ...options.includeDirtyFiles || []
1402
- ]);
1403
- const files = requestedFiles.filter((file) => after[file]);
1404
- if (files.length === 0) return { ok: true, skipped: true, reason: "no changed files to commit" };
1405
- const beforeEntries = asJsonObject(snapshot.entries);
1406
- const preexisting = files.filter((file) => beforeEntries[file]);
1407
- const allowDirty = options.allowDirty === true || args.allowDirty === true || args.allow_dirty === true;
1408
- if (preexisting.length > 0 && !allowDirty) {
1409
- return {
1410
- ok: false,
1411
- stage: "preexisting_dirty_files",
1412
- reason: "Refusing to commit files that were dirty before this packet",
1413
- files,
1414
- preexisting_dirty_files: preexisting
1415
- };
1416
- }
1417
- const add = runCommand("git", ["add", "-A", "--", ...files], { cwd: gitRoot2 });
1418
- if (!add.ok) return { ok: false, stage: "git_add", files, add };
1419
- const staged = runCommand("git", ["diff", "--cached", "--quiet"], { cwd: gitRoot2 });
1420
- if (staged.status === 0) return { ok: true, skipped: true, reason: "no staged changes", files };
1421
- const traceId = `trace_${textHash(JSON.stringify({ root, files, now: utcNow(), workflow: options.workflow })).slice(0, 16)}`;
1422
- const type = asOptionalString(args.commitType || args.commit_type) || options.type || (options.kind === "product" ? "feat" : "cadre");
1423
- const scope = asOptionalString(args.commitScope || args.commit_scope) || options.scope || options.workflow;
1424
- const subject = asOptionalString(args.commitSubject || args.commit_subject) || options.subject;
1425
- const fullSubject = conventionalSubject(type, scope, subject);
1426
- const body = asOptionalString(args.commitBody || args.commit_body) || options.body;
1427
- const commitBody = messageBody(body, {
1428
- "Cadre-Trace-Id": traceId,
1429
- "Cadre-Workflow": options.workflow,
1430
- "Cadre-Track": options.trackId || null,
1431
- "Cadre-Repo": options.repo || null
1432
- });
1433
- const commit = runCommand("git", [
1434
- "-c",
1435
- "commit.gpgsign=false",
1436
- "-c",
1437
- "user.name=Cadre",
1438
- "-c",
1439
- "user.email=cadre@local.invalid",
1440
- "commit",
1441
- "-m",
1442
- fullSubject,
1443
- "-m",
1444
- commitBody
1445
- ], { cwd: gitRoot2 });
1446
- if (!commit.ok) return { ok: false, stage: "git_commit", files, commit };
1447
- const sha = commitSha(gitRoot2);
1448
- const notePayload = {
1449
- version: 1,
1450
- schema: "cadre.commit_trace.v1",
1451
- trace_id: traceId,
1452
- kind: options.kind,
1453
- workflow: options.workflow,
1454
- action: options.action || null,
1455
- track_id: options.trackId || null,
1456
- repo: options.repo || null,
1457
- files,
1458
- commit_sha: sha,
1459
- recorded_at: utcNow(),
1460
- ...asJsonObject(options.note)
1461
- };
1462
- if (options.kind === "product") notePayload.product_commit_sha = sha;
1463
- if (options.kind === "control") notePayload.control_commit_sha = sha;
1464
- const ref = notesRef(root, args);
1465
- const note = sha && notesEnabled(root) ? writeNote(gitRoot2, ref, sha, notePayload) : null;
1466
- return {
1467
- ok: !note || commandOk(note),
1468
- trace_id: traceId,
1469
- kind: options.kind,
1470
- workflow: options.workflow,
1471
- commit_sha: sha,
1472
- subject: fullSubject,
1473
- files,
1474
- notes_ref: ref,
1475
- note
1476
- };
1477
- }
1478
-
1479
- // src/core/application/runtime/track-mutations.ts
1480
- function recordTaskResultUnlocked(root, args = {}) {
1481
- const track = findTrack(root, args.trackId);
1482
- if (!track) return { ok: false, error: `Track not found: ${args.trackId}` };
1483
- const plan = parsePlanFile(track.plan_path);
1484
- const phaseIndex = Number(args.phaseIndex);
1485
- const taskIndex = Number(args.taskIndex);
1486
- const phase = (plan.phases || []).find((item) => item.phase_index === phaseIndex);
1487
- const task = phase && (phase.tasks || []).find((item) => item.task_index === taskIndex);
1488
- if (!task) return { ok: false, error: `Task not found: phase ${phaseIndex} task ${taskIndex}` };
1489
- const planJsonPath = trackPlanJsonPath(track);
1490
- const commitSha2 = args.commitSha ? String(args.commitSha).trim() : "";
1491
- const recordedAt = utcNow();
1492
- const lastTaskResult = {
1493
- phase_index: phaseIndex,
1494
- task_index: taskIndex,
1495
- task_key: task.task_key,
1496
- status: args.status || "completed",
1497
- commit_sha: commitSha2 || null,
1498
- repo: args.repo || task.repo || null,
1499
- working_root: args.workingRoot || null,
1500
- recorded_at: recordedAt
1501
- };
1502
- const metadata = patchJsonFile(track.metadata_path, (current) => {
1503
- if (typeof args.coverage === "number") current.last_coverage = args.coverage;
1504
- if (args.lastTestRun && typeof args.lastTestRun === "object") current.last_test_run = args.lastTestRun;
1505
- if (isRecord(args.manualVerificationEvidence)) current.last_manual_verification_result = asJsonObject(args.manualVerificationEvidence);
1506
- current.last_task_result = lastTaskResult;
1507
- return current;
1508
- });
1509
- if (!metadata.ok) {
1510
- return { ok: false, track_id: track.track_id, stage: "metadata_patch", metadata };
1511
- }
1512
- if (fileExists(planJsonPath)) {
1513
- const planPatch = patchJsonFile(planJsonPath, (current) => {
1514
- const phases = asArray(current.phases).map((rawPhase) => {
1515
- const currentPhase = asJsonObject(rawPhase);
1516
- if (Number(currentPhase.phase_index || currentPhase.index) !== phaseIndex) return currentPhase;
1517
- return {
1518
- ...currentPhase,
1519
- tasks: asArray(currentPhase.tasks).map((rawTask) => {
1520
- const currentTask = asJsonObject(rawTask);
1521
- if (Number(currentTask.task_index || currentTask.index) !== taskIndex) return currentTask;
1522
- const commitShas = Array.from(/* @__PURE__ */ new Set([
1523
- ...asStringArray(currentTask.commit_shas),
1524
- ...commitSha2 ? [commitSha2.slice(0, 12)] : []
1525
- ]));
1526
- return {
1527
- ...currentTask,
1528
- status: args.status || "completed",
1529
- commit_shas: commitShas,
1530
- completion_evidence: {
1531
- ...asJsonObject(currentTask.completion_evidence),
1532
- commit_sha: commitSha2 || null,
1533
- repo: args.repo || task.repo || null,
1534
- working_root: args.workingRoot || null,
1535
- coverage: typeof args.coverage === "number" ? args.coverage : null,
1536
- recorded_at: recordedAt,
1537
- ...isRecord(args.manualVerificationEvidence) ? { manual_verification: asJsonObject(args.manualVerificationEvidence) } : {}
1538
- }
1539
- };
1540
- })
1541
- };
1542
- });
1543
- return { ...current, phases, updated_at: recordedAt };
1544
- });
1545
- if (!planPatch.ok) {
1546
- return { ok: false, track_id: track.track_id, stage: "plan_json_patch", metadata, plan_json: planPatch };
1547
- }
1548
- const nextPlan = asJsonObject(planPatch.value);
1549
- import_node_fs8.default.writeFileSync(
1550
- track.plan_path,
1551
- withGeneratedMarker(import_node_path14.default.relative(root, planJsonPath), "cadre.plan.v1", renderPlanMarkdown(nextPlan, import_node_path14.default.relative(root, planJsonPath)))
1552
- );
1553
- return {
1554
- ok: true,
1555
- track_id: track.track_id,
1556
- task_key: task.task_key,
1557
- line: task.line,
1558
- status: args.status || "completed",
1559
- commit_sha: commitSha2 || null,
1560
- event: appendCadreEvent(root, {
1561
- kind: "task_result_recorded",
1562
- workflow: "record_task_result",
1563
- track_id: track.track_id,
1564
- phase_index: phaseIndex,
1565
- task_index: taskIndex,
1566
- task_key: task.task_key,
1567
- status: args.status || "completed",
1568
- commit_sha: commitSha2 || null,
1569
- repo: args.repo || task.repo || null
1570
- }),
1571
- metadata,
1572
- plan_json: planPatch
1573
- };
1574
- }
1575
- return {
1576
- ok: false,
1577
- track_id: track.track_id,
1578
- stage: "missing_plan_json",
1579
- error: `Missing canonical plan JSON: ${planJsonPath}`,
1580
- metadata
1581
- };
1582
- }
1583
- function recordTaskResult(root, args = {}) {
1584
- const track = findTrack(root, args.trackId);
1585
- if (!track) return { ok: false, error: `Track not found: ${args.trackId}` };
1586
- if (args.lock === false) return recordTaskResultUnlocked(root, args);
1587
- return withTrackLock(root, track.track_id, () => recordTaskResultUnlocked(root, { ...args, lock: false }));
1588
- }
1589
-
1590
- // src/core/application/runtime/quality-gates.ts
1591
- function testCoverage(root, args = {}) {
1592
- let track = null;
1593
- let task = null;
1594
- let workingRoot = {
1595
- repo: args.repo || ".",
1596
- path: args.workingRoot ? import_node_path15.default.resolve(root, args.workingRoot) : root,
1597
- source: args.workingRoot ? "argument.workingRoot" : "project-root"
1598
- };
1599
- if (args.trackId) {
1600
- track = findTrack(root, args.trackId);
1601
- if (!track) {
1602
- return { ok: false, available: false, error: `Track not found: ${args.trackId}` };
1603
- }
1604
- if (args.phaseIndex != null && args.taskIndex != null) {
1605
- const plan = parsePlanFile(track.plan_path);
1606
- const phase = (plan.phases || []).find((item) => item.phase_index === Number(args.phaseIndex));
1607
- task = phase?.tasks.find((item) => item.task_index === Number(args.taskIndex)) || null;
1608
- }
1609
- workingRoot = resolveTaskWorkingRoot(root, track, task, args);
1610
- if (isWorkingRootError(workingRoot)) {
1611
- return {
1612
- ok: false,
1613
- available: false,
1614
- stage: "polyrepo_repo_resolution",
1615
- working_root: workingRoot,
1616
- reason: workingRoot.error
1617
- };
1618
- }
1619
- }
1620
- const coverageRun = runCoverage(root, args, workingRoot.path);
1621
- if (!coverageRun.available) return coverageRun;
1622
- const { command, coverage } = coverageRun;
1623
- let task_result = null;
1624
- let metadata = null;
1625
- if (track) {
1626
- const writeCoverage = () => {
1627
- metadata = patchJsonFile(track.metadata_path, (current) => {
1628
- current.last_test_run = {
1629
- command,
1630
- cwd: coverageRun.cwd || workingRoot.path,
1631
- ok: coverageRun.ok,
1632
- status: coverageRun.status,
1633
- signal: coverageRun.signal,
1634
- coverage,
1635
- measured_at: utcNow()
1636
- };
1637
- if (typeof coverage === "number") current.last_coverage = coverage;
1638
- return current;
1639
- }, { lock: false });
1640
- return metadata;
1641
- };
1642
- const metadataWrite = withTrackLock(root, track.track_id, writeCoverage);
1643
- if (!metadataWrite.ok) return { ok: false, available: true, command, coverage, working_root: workingRoot, stage: "metadata_lock", metadata: metadataWrite };
1644
- const metadataResult = metadata ?? metadataWrite;
1645
- if (!metadataResult.ok) {
1646
- return { ok: false, available: true, command, coverage, working_root: workingRoot, stage: "metadata_patch", metadata: metadataResult };
1647
- }
1648
- if (args.phaseIndex != null && args.taskIndex != null) {
1649
- task_result = recordTaskResult(root, {
1650
- trackId: args.trackId,
1651
- phaseIndex: args.phaseIndex,
1652
- taskIndex: args.taskIndex,
1653
- status: args.status || (coverageRun.ok ? "completed" : "blocked"),
1654
- commitSha: args.commitSha,
1655
- coverage,
1656
- repo: workingRoot.repo,
1657
- workingRoot: import_node_path15.default.relative(root, workingRoot.path) || "."
1658
- });
1659
- }
1660
- }
1661
- return {
1662
- ok: coverageRun.ok,
1663
- available: true,
1664
- command,
1665
- cwd: coverageRun.cwd,
1666
- status: coverageRun.status,
1667
- signal: coverageRun.signal,
1668
- coverage,
1669
- coverage_source: coverageRun.coverage_source,
1670
- timed_out: coverageRun.signal === "SIGTERM" || coverageRun.signal === "SIGKILL",
1671
- stdout_tail: coverageRun.stdout_tail,
1672
- stderr_tail: coverageRun.stderr_tail,
1673
- working_root: workingRoot,
1674
- metadata,
1675
- task_result
1676
- };
1677
- }
1678
- function configuredMachineGateCommand(root, args = {}, workingRoot = root) {
1679
- const explicit = args.machineCommand || args.machine_command || args.command;
1680
- if (explicit) return String(explicit);
1681
- const config = loadTopology(root).config || {};
1682
- for (const key of [
1683
- "review_machine_gate_command",
1684
- "machine_gate_command",
1685
- "review_check_command",
1686
- "typecheck_command",
1687
- "build_command",
1688
- "check_command"
1689
- ]) {
1690
- if (typeof config[key] === "string" && config[key].trim()) return config[key].trim();
1691
- }
1692
- const pkg = loadPackageJson(workingRoot);
1693
- const scripts = pkg ? asJsonObject(pkg.scripts) : {};
1694
- if (Object.keys(scripts).length > 0) {
1695
- for (const name of ["typecheck", "check", "build", "lint"]) {
1696
- if (scripts[name]) {
1697
- if (fileExists(import_node_path15.default.join(workingRoot, "pnpm-lock.yaml"))) return `pnpm ${name}`;
1698
- if (fileExists(import_node_path15.default.join(workingRoot, "yarn.lock"))) return `yarn ${name}`;
1699
- return `npm run ${name}`;
1700
- }
1701
- }
1702
- }
1703
- return null;
1704
- }
1705
- function runMachineGate(root, args = {}, workingRoot = root) {
1706
- const command = configuredMachineGateCommand(root, args, workingRoot);
1707
- if (!command) {
1708
- return {
1709
- ok: true,
1710
- available: false,
1711
- reason: "No review machine-gate command configured or discovered",
1712
- hints: [
1713
- "Pass { machineCommand } explicitly",
1714
- "Set cadre/config.json review_machine_gate_command",
1715
- "Add a package script named typecheck, check, build, or lint"
1716
- ]
1717
- };
1718
- }
1719
- const timeoutMs = Number(args.timeoutMs || 10 * 60 * 1e3);
1720
- const result = runCommand(command, [], {
1721
- cwd: workingRoot,
1722
- shell: true,
1723
- timeoutMs,
1724
- maxBuffer: 30 * 1024 * 1024
1725
- });
1726
- return {
1727
- ok: result.ok,
1728
- available: true,
1729
- command,
1730
- cwd: workingRoot,
1731
- status: result.status,
1732
- signal: result.signal,
1733
- timed_out: result.signal === "SIGTERM" || result.signal === "SIGKILL",
1734
- stdout_tail: result.stdout.slice(-4e3),
1735
- stderr_tail: result.stderr.slice(-4e3)
1736
- };
1737
- }
1738
- function reviewMachineGate(root, args = {}) {
1739
- const trackId = args.trackId || args.track_id || null;
1740
- const track = trackId ? findTrack(root, trackId) : null;
1741
- if (trackId && !track) return { ok: false, error: `Track not found: ${trackId}` };
1742
- if (track) {
1743
- const repoError = repoEntriesError(root, track, args);
1744
- if (repoError) return repoError;
1745
- }
1746
- const entries = track ? repoEntriesForTrack(root, track, args) : [{
1747
- repo: args.repo || ".",
1748
- root: args.workingRoot ? import_node_path15.default.resolve(root, args.workingRoot) : root,
1749
- path: args.workingRoot || ".",
1750
- source: args.workingRoot ? "argument.workingRoot" : "project-root"
1751
- }];
1752
- const results = entries.map((entry) => {
1753
- const gate = runMachineGate(root, args, entry.root);
1754
- return {
1755
- repo: entry.repo,
1756
- path: entry.path,
1757
- source: entry.source,
1758
- ...gate
1759
- };
1760
- });
1761
- const blocking = results.filter((result) => result.available === true && !result.ok);
1762
- return {
1763
- ok: blocking.length === 0,
1764
- available: results.some((result) => result.available === true),
1765
- track_id: trackId,
1766
- results,
1767
- blocking_count: blocking.length
1768
- };
1769
- }
1770
- function diffSurface(root, base, head) {
1771
- const range = `${base}...${head}`;
1772
- const stat = runCommand("git", ["diff", "--stat", range], { cwd: root, maxBuffer: 10 * 1024 * 1024 });
1773
- const names = runCommand("git", ["diff", "--name-only", range], { cwd: root, maxBuffer: 10 * 1024 * 1024 });
1774
- return {
1775
- ok: stat.ok || names.ok,
1776
- base,
1777
- head,
1778
- stat: stat.stdout.trim(),
1779
- files: names.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean),
1780
- errors: [stat.stderr, names.stderr].filter(Boolean).join("\n").trim()
1781
- };
1782
- }
1783
- function scanReviewTodos(root, files, limit = 100) {
1784
- const findings = [];
1785
- const patterns = [
1786
- /\bTODO\b/i,
1787
- /\bFIXME\b/i,
1788
- /\bstub\b/i,
1789
- /throw new Error\(["']not implemented/i
1790
- ];
1791
- for (const file of files || []) {
1792
- if (isIgnoredRepoMapFile(file)) continue;
1793
- const abs = import_node_path15.default.join(root, file);
1794
- if (!fileExists(abs)) continue;
1795
- let stat;
1796
- try {
1797
- stat = import_node_fs9.default.statSync(abs);
1798
- } catch {
1799
- continue;
1800
- }
1801
- if (stat.size > 1024 * 1024) continue;
1802
- const lines = import_node_fs9.default.readFileSync(abs, "utf8").split(/\r?\n/);
1803
- for (let index = 0; index < lines.length && findings.length < limit; index += 1) {
1804
- const line = lines[index] || "";
1805
- if (patterns.some((pattern) => pattern.test(line))) {
1806
- findings.push({ file, line: index + 1, snippet: line.trim().slice(0, 180) });
1807
- }
1808
- }
1809
- }
1810
- return findings;
1811
- }
1812
- function reviewAssist(root, args = {}) {
1813
- const trackId = args.trackId || args.track_id;
1814
- if (!trackId) return { ok: false, error: "trackId is required" };
1815
- const context = trackContext(root, trackId);
1816
- if (!context.ok) return context;
1817
- const track = findTrack(root, trackId);
1818
- if (!track) return { ok: false, error: `Track not found: ${trackId}` };
1819
- const repoError = repoEntriesError(root, track, args);
1820
- if (repoError) return repoError;
1821
- const plan = parsePlanFile(track.plan_path);
1822
- const base = args.base || "main";
1823
- const head = args.head || track.metadata.git_branch || "HEAD";
1824
- const repoEntries = repoEntriesForTrack(root, track, args);
1825
- const repoDiffs = repoEntries.map((entry) => ({
1826
- repo: entry.repo,
1827
- path: entry.path,
1828
- cwd: entry.root,
1829
- source: entry.source,
1830
- ...diffSurface(entry.root, entry.base || base, entry.head || head)
1831
- }));
1832
- const diff = repoDiffs.find((entry) => entry.repo === "root" || entry.repo === ".") || diffSurface(root, base, head);
1833
- const incompleteTasks = [];
1834
- for (const phase of plan.phases) {
1835
- for (const task of phase.tasks) {
1836
- if (task.marker !== "x" && task.marker !== "-") {
1837
- incompleteTasks.push({
1838
- phase: phase.phase_index,
1839
- task: task.task_index,
1840
- task_key: task.task_key,
1841
- title: task.title,
1842
- marker: task.marker,
1843
- repo: task.repo || null
1844
- });
1845
- }
1846
- }
1847
- }
1848
- const todoLimit = Number(args.todoLimit || 100);
1849
- const repoTodos = repoDiffs.map((entry) => ({
1850
- repo: entry.repo,
1851
- path: entry.path,
1852
- cwd: entry.cwd,
1853
- todos: scanReviewTodos(entry.cwd || root, entry.files, todoLimit)
1854
- }));
1855
- const todos = repoTodos.flatMap((entry) => entry.todos.map((todo) => ({ ...todo, repo: entry.repo }))).slice(0, todoLimit);
1856
- const lsp = args.includeLsp === false ? null : args.lspResult || args.lsp_result || lspReview(root, { base, head, config: args.config });
1857
- const machineGate = args.includeMachine === false ? null : reviewMachineGate(root, args);
1858
- const lspObject = asJsonObject(lsp);
1859
- const machineGateObject = asJsonObject(machineGate);
1860
- const blocking = [];
1861
- if (incompleteTasks.length > 0) blocking.push(`${incompleteTasks.length} plan task(s) are not completed or skipped`);
1862
- if (todos.length > 0) blocking.push(`${todos.length} TODO/FIXME/stub marker(s) found in changed files`);
1863
- if (track.metadata.last_coverage == null) blocking.push("No measured coverage recorded on the track");
1864
- if (lsp && lspObject.available !== false && Array.isArray(lspObject.findings)) {
1865
- const lspBlocking = asArray(lspObject.findings).filter((finding) => finding.severity === "blocking" || finding.blocking === true);
1866
- if (lspBlocking.length > 0) blocking.push(`${lspBlocking.length} blocking LSP/code-intelligence finding(s)`);
1867
- }
1868
- const machineBlockingCount = asNumber(machineGateObject.blocking_count);
1869
- if (machineGate && machineBlockingCount > 0) {
1870
- blocking.push(`${machineBlockingCount} machine gate check(s) failed`);
1871
- }
1872
- const result = {
1873
- ok: true,
1874
- root,
1875
- track_id: trackId,
1876
- base,
1877
- head,
1878
- diff,
1879
- repo_diffs: repoDiffs,
1880
- branch_set: context.branch_set || [],
1881
- task_counts: context.task_counts,
1882
- incomplete_tasks: incompleteTasks,
1883
- coverage: track.metadata.last_coverage ?? null,
1884
- todos,
1885
- repo_todos: repoTodos,
1886
- lsp,
1887
- machine_gate: machineGate,
1888
- suggested_verdict: blocking.length === 0 ? "approved" : "changes_requested",
1889
- blocking_reasons: blocking
1890
- };
1891
- const mode = (asOptionalString(args.responseMode || args.response_mode || (args.detail === true ? "detail" : null)) || "compact").toLowerCase();
1892
- if (["detail", "detailed", "full", "verbose"].includes(mode)) return result;
1893
- const lspSummary = asJsonObject(result.lsp);
1894
- const gateSummary = asJsonObject(result.machine_gate);
1895
- const diffSummary = asJsonObject(diff);
1896
- const diffFiles = Array.isArray(diffSummary.files) ? diffSummary.files : [];
1897
- return {
1898
- ok: true,
1899
- root,
1900
- track_id: trackId,
1901
- base,
1902
- head,
1903
- task_counts: context.task_counts,
1904
- diff: {
1905
- repo: diffSummary.repo || ".",
1906
- file_count: diffFiles.length,
1907
- stat: asOptionalString(diffSummary.stat) || ""
1908
- },
1909
- repo_diffs: repoDiffs.slice(0, 20).map((entry) => ({
1910
- repo: entry.repo,
1911
- path: entry.path,
1912
- files: Array.isArray(entry.files) ? entry.files.slice(0, 50) : [],
1913
- file_count: Array.isArray(entry.files) ? entry.files.length : 0,
1914
- stat: entry.stat
1915
- })),
1916
- repo_diffs_count: repoDiffs.length,
1917
- incomplete_tasks: incompleteTasks.slice(0, 20),
1918
- incomplete_tasks_count: incompleteTasks.length,
1919
- coverage: track.metadata.last_coverage ?? null,
1920
- todos: todos.slice(0, 20),
1921
- todos_count: todos.length,
1922
- lsp: lsp ? {
1923
- available: lspSummary.available !== false,
1924
- degraded: lspSummary.degraded === true || lspSummary.fallback === "text_scan",
1925
- findings_count: Array.isArray(lspSummary.findings) ? lspSummary.findings.length : 0,
1926
- server_count: Array.isArray(lspSummary.servers) ? lspSummary.servers.length : 0,
1927
- polyrepo: lspSummary.polyrepo === true
1928
- } : null,
1929
- machine_gate: machineGate ? {
1930
- ok: gateSummary.ok !== false,
1931
- available: gateSummary.available !== false,
1932
- blocking_count: Number(gateSummary.blocking_count || 0),
1933
- result_count: Array.isArray(gateSummary.results) ? gateSummary.results.length : 0
1934
- } : null,
1935
- suggested_verdict: result.suggested_verdict,
1936
- blocking_reasons: blocking,
1937
- detail_available: true
1938
- };
1939
- }
1940
-
1941
- // src/core/application/runtime/review-records.ts
1942
- function syncControlPlane(root, args = {}) {
1943
- const topology = loadTopology(root);
1944
- if (topology.config.sync_mode !== "shared") {
1945
- return { ok: true, skipped: true, reason: "sync_mode is not shared", commands: [] };
1946
- }
1947
- const mode = args.mode || "pre";
1948
- const remote = asOptionalString(topology.config.control_remote) || "origin";
1949
- const branch = asOptionalString(topology.config.control_branch) || "main";
1950
- const commands = [];
1951
- commands.push(runCommand("git", ["config", "merge.ours.driver", "true"], { cwd: root }));
1952
- const safety = controlPlaneSyncSafety(root, mode, remote, branch);
1953
- if (!safety.ok) {
1954
- return { ok: false, mode, remote, branch, safety, commands };
1955
- }
1956
- if (mode === "pre") {
1957
- commands.push(runCommand("git", ["pull", "--rebase", remote, branch], { cwd: root }));
1958
- } else if (mode === "post") {
1959
- commands.push(runCommand("git", ["push", remote, branch], { cwd: root }));
1960
- } else {
1961
- return { ok: false, error: `Invalid sync mode: ${mode}`, commands };
1962
- }
1963
- return { ok: commands.every((cmd) => cmd.ok), mode, remote, branch, safety, commands };
1964
- }
1965
-
1966
- // src/core/application/runtime/workflow-response.ts
1967
- function resultOk(value) {
1968
- return !value || value.ok !== false;
1969
- }
1970
- function withSharedControlPlaneSync(root, args = {}, operation, fn) {
1971
- const topology = loadTopology(root);
1972
- if (args.execute !== true || topology.config.sync_mode !== "shared" || args.skipSync === true) {
1973
- return fn();
1974
- }
1975
- const syncPre = syncControlPlane(root, { mode: "pre" });
1976
- if (syncPre.ok === false) {
1977
- return {
1978
- ok: false,
1979
- phase_state: "blocked",
1980
- stage: "sync_pre",
1981
- operation,
1982
- sync_pre: syncPre
1983
- };
1984
- }
1985
- const result = fn();
1986
- if (result.ok === false) {
1987
- return {
1988
- ...result,
1989
- sync_pre: syncPre,
1990
- sync_post: null
1991
- };
1992
- }
1993
- const syncPost = syncControlPlane(root, { mode: "post" });
1994
- return {
1995
- ...result,
1996
- ok: resultOk(result) && syncPost.ok !== false,
1997
- phase_state: syncPost.ok === false ? "recovery_required" : result.phase_state,
1998
- sync_pre: syncPre,
1999
- sync_post: syncPost
2000
- };
2001
- }
2002
-
2003
- // src/core/application/runtime/workspace-intel.ts
2004
- function lspImpact(root, args = {}) {
2005
- const limit = Number(args.limit || 50);
2006
- const symbols = Array.isArray(args.symbols) ? args.symbols : args.symbol ? [args.symbol] : [];
2007
- const files = Array.isArray(args.files) ? args.files : [];
2008
- const symbolResults = {};
2009
- for (const symbol of symbols.filter(Boolean)) {
2010
- symbolResults[symbol] = repoMap(root, { symbol, limit });
2011
- }
2012
- const repoEntries = intelRepoRoots(root, args);
2013
- const repoFileSymbols = repoEntries.map((entry) => {
2014
- const fileSymbols2 = {};
2015
- for (const file of files) {
2016
- if (isIgnoredRepoMapFile(file)) continue;
2017
- fileSymbols2[file] = extractRepoSymbols(entry.root, file, limit).map((symbolEntry) => ({
2018
- ...symbolEntry,
2019
- repo: entry.repo
2020
- }));
2021
- }
2022
- return { repo: entry.repo, root: entry.root, path: entry.path, files: fileSymbols2 };
2023
- });
2024
- const fileSymbols = {};
2025
- for (const entry of repoFileSymbols) {
2026
- for (const [file, symbolsForFile] of Object.entries(asJsonObject(entry.files))) {
2027
- const key = entry.repo === "." ? file : `${entry.repo}:${file}`;
2028
- fileSymbols[key] = asArray(symbolsForFile);
2029
- }
2030
- }
2031
- const review = args.lspResult || args.lsp_result ? args.lspResult || args.lsp_result : args.base || args.head ? lspReview(root, { base: args.base || "main", head: args.head || "HEAD", config: args.config }) : null;
2032
- return {
2033
- ok: true,
2034
- root,
2035
- symbols: symbolResults,
2036
- files: fileSymbols,
2037
- repos: repoFileSymbols,
2038
- review
2039
- };
2040
- }
2041
-
2042
- // src/core/application/runtime/planning.ts
2043
- function worktreePlan(root, args = {}) {
2044
- const track = findTrack(root, args.trackId || args.track_id);
2045
- if (!track) return { ok: false, error: `Track not found: ${args.trackId || args.track_id}` };
2046
- const repoError = repoEntriesError(root, track, args);
2047
- if (repoError) return repoError;
2048
- const topology = loadTopology(root);
2049
- const branchSet = branchSetForTrack(root, track, args);
2050
- const execute = args.execute === true;
2051
- const setup_results = execute ? branchSet.map((entry) => ensureIntegrationWorktree(entry)) : [];
2052
- const plans = branchSet.map((entry, index) => {
2053
- const result = setup_results[index];
2054
- const resultEntry = isRecord(result?.entry) ? asJsonObject(result.entry) : entry;
2055
- return {
2056
- repo: entry.repo,
2057
- source_root: entry.source_root,
2058
- source_path: entry.source_path,
2059
- worktree_path: entry.integration_worktree_path,
2060
- integration_worktree: entry.integration_worktree,
2061
- worker_root: entry.worker_root,
2062
- branch: entry.track_branch,
2063
- base: entry.base_branch,
2064
- exists: result ? result.ok === true : entry.exists,
2065
- current_branch: result ? asOptionalString(resultEntry.current_branch) : entry.current_branch,
2066
- health: result ? asOptionalString(resultEntry.health) || entry.health : entry.health,
2067
- branch_exists: entry.branch_exists,
2068
- commands: entry.commands,
2069
- setup_result: result || null
2070
- };
2071
- });
2072
- return {
2073
- ok: setup_results.every((result) => result.ok !== false) && branchSet.every((entry) => entry.health === "ready" || entry.health === "missing"),
2074
- root,
2075
- track_id: track.track_id,
2076
- execute,
2077
- dry_run: !execute,
2078
- topology: topology.polyrepo ? "polyrepo" : "monorepo",
2079
- branch_set: branchSet,
2080
- plans,
2081
- setup_results
2082
- };
2083
- }
2084
-
2085
- // src/core/application/runtime/tech-stack.ts
2086
- function humanReviewConfirmed(args = {}) {
2087
- const rawArgs = args;
2088
- return rawArgs.approvalComplete === true || rawArgs.approval_complete === true;
2089
- }
2090
-
2091
- // src/core/application/runtime/repo-resolution.ts
2092
- function topologyRepoEntries(topology) {
2093
- const entries = {};
2094
- for (const raw of Array.isArray(topology.repos.repos) ? topology.repos.repos : []) {
2095
- const repo = asJsonObject(raw);
2096
- const name = asOptionalString(repo.name);
2097
- if (!name) continue;
2098
- entries[name] = {
2099
- submodule_path: asOptionalString(repo.submodule_path) || "",
2100
- base_branch: asOptionalString(repo.default_branch) || asOptionalString(repo.base_branch) || "main"
2101
- };
2102
- }
2103
- return entries;
2104
- }
2105
- function trackRepoEntries(root, track) {
2106
- const topology = loadTopology(root);
2107
- const entries = topologyRepoEntries(topology);
2108
- const reposMetadata = isRecord(track.metadata.repos) ? track.metadata.repos : null;
2109
- if (reposMetadata) {
2110
- for (const [repo, rawInfo] of Object.entries(reposMetadata)) {
2111
- entries[repo] = { ...entries[repo], ...asJsonObject(rawInfo) };
2112
- }
2113
- }
2114
- return entries;
2115
- }
2116
- function availableRepoNames(root, track) {
2117
- return Object.keys(trackRepoEntries(root, track)).sort();
2118
- }
2119
- function unresolvedWorkingRoot(root, track, repo, task = null) {
2120
- return {
2121
- ok: false,
2122
- repo,
2123
- path: "",
2124
- source: "polyrepo-unresolved-repo",
2125
- error: `Unknown polyrepo task repo "${repo}" for track ${track.track_id}`,
2126
- unresolved_repo: repo,
2127
- available_repos: availableRepoNames(root, track),
2128
- track_id: track.track_id,
2129
- task_key: task?.task_key
2130
- };
2131
- }
2132
- function isWorkingRootError(value) {
2133
- return value.ok === false;
2134
- }
2135
- function unresolvedPlanRepos(root, track, args = {}) {
2136
- const topology = loadTopology(root);
2137
- if (!topology.polyrepo) return [];
2138
- const entries = trackRepoEntries(root, track);
2139
- const known = new Set(Object.keys(entries));
2140
- const plan = parsePlanFile(track.plan_path);
2141
- const errors = [];
2142
- const seen = /* @__PURE__ */ new Set();
2143
- for (const task of plan.tasks || []) {
2144
- const repo = asOptionalString(args.repo) || task.repo || topology.defaultRepo;
2145
- if (repo && known.has(repo)) continue;
2146
- const key = `${repo || ""}:${task.task_key}`;
2147
- if (seen.has(key)) continue;
2148
- seen.add(key);
2149
- errors.push({
2150
- track_id: track.track_id,
2151
- task_key: task.task_key,
2152
- line: task.line,
2153
- repo: repo || null,
2154
- message: repo ? `Unknown polyrepo task repo "${repo}"` : "Task has no repo annotation and repos.json has no default_repo",
2155
- available_repos: Array.from(known).sort()
2156
- });
2157
- }
2158
- return errors;
2159
- }
2160
- function repoEntriesError(root, track, args = {}) {
2161
- const topology = loadTopology(root);
2162
- if (!topology.polyrepo) return null;
2163
- const entries = trackRepoEntries(root, track);
2164
- const requested = asOptionalString(args.repo);
2165
- const missing = requested ? entries[requested] ? [] : [{ repo: requested, message: `Unknown polyrepo repo "${requested}"` }] : unresolvedPlanRepos(root, track, args);
2166
- if (missing.length === 0) return null;
2167
- return {
2168
- ok: false,
2169
- stage: "polyrepo_repo_resolution",
2170
- track_id: track.track_id,
2171
- errors: missing,
2172
- available_repos: Object.keys(entries).sort()
2173
- };
2174
- }
2175
- function resolveTaskWorkingRoot(root, track, task = null, args = {}) {
2176
- const explicitWorkingRoot = asOptionalString(args.workingRoot || args.workerRoot || args.worker_root || args.worktree);
2177
- if (explicitWorkingRoot) {
2178
- const candidate = import_node_path16.default.isAbsolute(explicitWorkingRoot) ? explicitWorkingRoot : import_node_path16.default.resolve(root, explicitWorkingRoot);
2179
- return { repo: taskRepo(root, task, args), path: candidate, source: "argument.workingRoot" };
2180
- }
2181
- const repo = taskRepo(root, task, args);
2182
- const branchEntry = branchSetEntryForRepo(root, track, repo, args);
2183
- if (branchEntry && branchEntry.exists && branchEntry.health === "ready") {
2184
- return {
2185
- repo: branchEntry.repo,
2186
- path: branchEntry.integration_worktree,
2187
- source: "branch-set.integration_worktree",
2188
- branch_set: branchEntry
2189
- };
2190
- }
2191
- const topology = loadTopology(root);
2192
- if (topology.polyrepo) {
2193
- const info = typeof repo === "string" ? trackRepoEntries(root, track)[repo] || {} : {};
2194
- if (Object.keys(info).length > 0) {
2195
- const rel = info.worktree_path || info.submodule_path || "";
2196
- return {
2197
- ok: true,
2198
- repo,
2199
- path: rel ? import_node_path16.default.resolve(root, rel) : root,
2200
- source: branchEntry ? "branch-set.integration_missing_fallback" : info.worktree_path ? "metadata.repos.worktree_path" : "metadata.repos.submodule_path",
2201
- ...branchEntry ? { branch_set: branchEntry } : {}
2202
- };
2203
- }
2204
- return unresolvedWorkingRoot(root, track, String(repo || ""), task);
2205
- }
2206
- if (track.metadata.worktree_path && !branchEntry) {
2207
- const candidate = import_node_path16.default.resolve(root, track.metadata.worktree_path);
2208
- if (fileExists(candidate)) {
2209
- return { repo: ".", path: candidate, source: "metadata.worktree_path" };
2210
- }
2211
- }
2212
- return {
2213
- ok: true,
2214
- repo: MONOREPO_REPO_KEY,
2215
- path: root,
2216
- source: branchEntry ? "branch-set.integration_missing_fallback" : "project-root",
2217
- ...branchEntry ? { branch_set: branchEntry } : {}
2218
- };
2219
- }
2220
- function repoEntriesForTrack(root, track, args = {}) {
2221
- return branchSetForTrack(root, track, args).map((entry) => ({
2222
- repo: entry.repo,
2223
- root: entry.exists && entry.health === "ready" ? entry.integration_worktree : entry.source_root,
2224
- path: entry.exists && entry.health === "ready" ? entry.integration_worktree_path : entry.source_path,
2225
- base: entry.base_branch,
2226
- head: entry.track_branch,
2227
- source: entry.exists && entry.health === "ready" ? "branch-set.integration_worktree" : "branch-set.source_root",
2228
- branch_set: entry
2229
- }));
2230
- }
2231
-
2232
- // src/core/application/runtime/track-schedule.ts
2233
- function workStateForTrack(track) {
2234
- const statePath = import_node_path17.default.join(track.dir, "implement_state.json");
2235
- return readJson(statePath, null);
2236
- }
2237
- function holdInfo(track, now = Date.now()) {
2238
- const state = workStateForTrack(track);
2239
- const lease = track.metadata.lease || null;
2240
- const stateOwner = state?.owner || null;
2241
- const owner = stateOwner || track.metadata.owner || null;
2242
- const leaseOwner = lease?.owner || null;
2243
- const leaseTime = lease && (asOptionalString(lease.heartbeat_at) || lease.acquired_at);
2244
- const stateTime = state && (state.last_updated || state.last_handoff);
2245
- const leaseStale = staleInfo(leaseTime, now);
2246
- const stateStale = staleInfo(stateTime, now);
2247
- return {
2248
- owner,
2249
- metadata_owner: track.metadata.owner || null,
2250
- state_owner: stateOwner,
2251
- lease_owner: leaseOwner,
2252
- lease_heartbeat_at: leaseTime || null,
2253
- lease_stale: lease ? leaseStale.stale : false,
2254
- lease_age_minutes: leaseStale.age_minutes,
2255
- state_last_updated: stateTime || null,
2256
- state_stale: state ? stateStale.stale : false,
2257
- state_age_minutes: stateStale.age_minutes
2258
- };
2259
- }
2260
- function taskCounts(plan) {
2261
- const counts = { total: 0, pending: 0, in_progress: 0, completed: 0, blocked: 0, skipped: 0, percent: 0 };
2262
- for (const phase of plan.phases || []) {
2263
- for (const task of phase.tasks || []) {
2264
- counts.total += 1;
2265
- if (task.marker === "x") counts.completed += 1;
2266
- else if (task.marker === "~") counts.in_progress += 1;
2267
- else if (task.marker === "!") counts.blocked += 1;
2268
- else if (task.marker === "-") counts.skipped += 1;
2269
- else counts.pending += 1;
2270
- }
2271
- }
2272
- counts.percent = counts.total === 0 ? 0 : Math.round(counts.completed / counts.total * 100);
2273
- return counts;
2274
- }
2275
- function listTrackDirs(root) {
2276
- const tracksDir = import_node_path17.default.join(root, "cadre", "tracks");
2277
- if (!fileExists(tracksDir)) return [];
2278
- return import_node_fs10.default.readdirSync(tracksDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => import_node_path17.default.join(tracksDir, entry.name)).sort();
2279
- }
2280
- function listTracks(root) {
2281
- const tracks = [];
2282
- for (const dir of listTrackDirs(root)) {
2283
- const metadataPath = import_node_path17.default.join(dir, "metadata.json");
2284
- const metadata = readJson(metadataPath, null);
2285
- if (!metadata) continue;
2286
- const trackId = metadata.track_id || import_node_path17.default.basename(dir);
2287
- tracks.push({
2288
- track_id: trackId,
2289
- dir,
2290
- metadata_path: metadataPath,
2291
- plan_path: import_node_path17.default.join(dir, "plan.md"),
2292
- spec_path: import_node_path17.default.join(dir, "spec.md"),
2293
- plan_json_path: import_node_path17.default.join(dir, "plan.json"),
2294
- spec_json_path: import_node_path17.default.join(dir, "spec.json"),
2295
- learnings_jsonl_path: import_node_path17.default.join(dir, "learnings.jsonl"),
2296
- handoff_json_path: import_node_path17.default.join(dir, "handoff.json"),
2297
- metadata
2298
- });
2299
- }
2300
- return tracks;
2301
- }
2302
- function parsePlanJson(raw) {
2303
- return planJsonToParsedPlan(asJsonObject(raw));
2304
- }
2305
- function parsePlanFile(file) {
2306
- const planJsonPath = planJsonPathForPlanPath(file);
2307
- if (fileExists(planJsonPath)) {
2308
- const raw = readJson(planJsonPath, null);
2309
- if (raw) return parsePlanJson(raw);
2310
- }
2311
- return {
2312
- ok: false,
2313
- phases: [],
2314
- tasks: [],
2315
- warnings: [],
2316
- errors: [`Missing canonical plan JSON: ${planJsonPath}`]
2317
- };
2318
- }
2319
-
2320
- // src/core/application/runtime/status.ts
2321
- function asArray(value) {
2322
- if (Array.isArray(value)) return value.filter(isRecord);
2323
- if (isRecord(value) && Array.isArray(value.items)) return value.items.filter(isRecord).map(asJsonObject);
2324
- if (isRecord(value) && Array.isArray(value.issues)) return value.issues.filter(isRecord).map(asJsonObject);
2325
- if (isRecord(value) && Array.isArray(value.data)) return value.data.filter(isRecord).map(asJsonObject);
2326
- return [];
2327
- }
2328
-
2329
- // src/core/application/runtime/markdown-docs.ts
2330
- function normalizedText(text) {
2331
- return text.replace(/\r\n/g, "\n").replace(/\n*$/, "\n");
2332
- }
2333
- function generatedMarker(source, schema, body) {
2334
- return `<!-- cadre:generated from="${source}" schema="${schema}" hash="${textHash(body).slice(0, 16)}" -->`;
2335
- }
2336
- function withGeneratedMarker(source, schema, body) {
2337
- const normalized = normalizedText(body);
2338
- return `${generatedMarker(source, schema, normalized)}
2339
- ${normalized}`;
2340
- }
2341
- function appendCanonicalJsonReference(parts, source, heading = "Canonical Source") {
2342
- const target = source ? `\`${source}\`` : "the canonical JSON file referenced by the generated marker";
2343
- parts.push(`## ${heading}`, "", `Canonical data lives in ${target}. This Markdown is a generated human-readable projection.`, "");
2344
- }
2345
- function markerForPlanStatus(status) {
2346
- const normalized = String(status || "pending");
2347
- if (normalized === "completed") return "x";
2348
- if (normalized === "in_progress") return "~";
2349
- if (normalized === "blocked") return "!";
2350
- if (normalized === "skipped") return "-";
2351
- return " ";
2352
- }
2353
-
2354
- // src/core/application/runtime/plan-docs.ts
2355
- var MANUAL_VERIFICATION_TASK_TYPE = "user_manual_verification";
2356
- function trackPlanJsonPath(track) {
2357
- return track.plan_json_path || import_node_path18.default.join(track.dir, "plan.json");
2358
- }
2359
- function planJsonPathForPlanPath(file) {
2360
- if (file.endsWith(".json")) return file;
2361
- return import_node_path18.default.join(import_node_path18.default.dirname(file), "plan.json");
2362
- }
2363
- function manualVerificationScope(value) {
2364
- const task = asJsonObject(value);
2365
- const manual = asJsonObject(task.manual_verification);
2366
- const annotations = asJsonObject(task.annotations);
2367
- return asOptionalString(manual.scope) || asOptionalString(annotations["manual-verification-scope"]) || asOptionalString(annotations["manual-verification"]) || null;
2368
- }
2369
- function isManualVerificationTaskObject(value, scope) {
2370
- const task = asJsonObject(value);
2371
- const annotations = asJsonObject(task.annotations);
2372
- const type = asOptionalString(task.task_type) || asOptionalString(annotations["task-type"]);
2373
- const taskScope = manualVerificationScope(task);
2374
- const key = asOptionalString(task.task_key || task.key) || "";
2375
- const title = asOptionalString(task.title) || "";
2376
- const matchesManual = type === MANUAL_VERIFICATION_TASK_TYPE || title.toLowerCase().includes("user manual verification") || key.endsWith("_manual_verification") || key === "track_manual_verification";
2377
- if (!matchesManual) return false;
2378
- if (!scope) return true;
2379
- if (taskScope) return taskScope === scope;
2380
- return scope === "track" ? key === "track_manual_verification" : key !== "track_manual_verification";
2381
- }
2382
- function planJsonToParsedPlan(raw) {
2383
- const phases = asArray(raw.phases).map((rawPhase, phaseOffset) => {
2384
- const phase = asJsonObject(rawPhase);
2385
- const phaseIndex = Number(phase.phase_index || phase.index || phaseOffset + 1);
2386
- const phaseDepends = asStringArray(phase.depends_on);
2387
- const hasExplicitPhaseDepends = Object.prototype.hasOwnProperty.call(phase, "depends_on");
2388
- const annotations = {
2389
- ...asJsonObject(phase.annotations),
2390
- ...asOptionalString(phase.execution_mode) ? { execution: asOptionalString(phase.execution_mode) } : {},
2391
- ...hasExplicitPhaseDepends ? { depends: phaseDepends.join(",") } : {}
2392
- };
2393
- const tasks = asArray(phase.tasks).map((rawTask, taskOffset) => {
2394
- const task = asJsonObject(rawTask);
2395
- const taskIndex = Number(task.task_index || task.index || taskOffset + 1);
2396
- const taskKey = asOptionalString(task.task_key) || `phase${phaseIndex}_task${taskIndex}`;
2397
- const files = asStringArray(task.files);
2398
- const depends = asStringArray(task.depends_on || task.depends);
2399
- const labels = asStringArray(task.labels);
2400
- const taskAnnotations = {
2401
- ...asJsonObject(task.annotations),
2402
- ...files.length > 0 ? { files: files.join(", ") } : {},
2403
- ...depends.length > 0 ? { depends: depends.join(",") } : {},
2404
- ...labels.length > 0 ? { labels: labels.join(",") } : {},
2405
- ...asOptionalString(task.repo) ? { repo: asOptionalString(task.repo) } : {}
2406
- };
2407
- return {
2408
- task_index: taskIndex,
2409
- task_key: taskKey,
2410
- title: asOptionalString(task.title) || `Task ${taskIndex}`,
2411
- marker: markerForPlanStatus(task.status),
2412
- annotations: taskAnnotations,
2413
- files,
2414
- depends,
2415
- labels,
2416
- repo: asOptionalString(task.repo) || null,
2417
- line: Number(task.line || phaseIndex * 100 + taskIndex),
2418
- phase_index: phaseIndex,
2419
- commit_shas: asStringArray(task.commit_shas),
2420
- repo_shas: asJsonObject(task.repo_shas),
2421
- task_type: asOptionalString(task.task_type || taskAnnotations["task-type"]) || null,
2422
- manual_verification: isRecord(task.manual_verification) ? asJsonObject(task.manual_verification) : asOptionalString(taskAnnotations["manual-verification-scope"]) ? { scope: asOptionalString(taskAnnotations["manual-verification-scope"]) } : null,
2423
- completion_evidence: isRecord(task.completion_evidence) ? asJsonObject(task.completion_evidence) : null
2424
- };
2425
- });
2426
- return {
2427
- phase_index: phaseIndex,
2428
- title: asOptionalString(phase.title) || `Phase ${phaseIndex}`,
2429
- annotations,
2430
- tasks,
2431
- line: Number(phase.line || phaseIndex * 100)
2432
- };
2433
- });
2434
- return { ok: true, phases, tasks: phases.flatMap((phase) => phase.tasks), warnings: [], errors: [] };
2435
- }
2436
- function renderPlanMarkdown(raw, canonicalSource) {
2437
- const trackId = asOptionalString(raw.track_id) || "track";
2438
- const parts = [`# Plan: ${trackId}`, ""];
2439
- const parsed = planJsonToParsedPlan(raw);
2440
- for (const phase of parsed.phases) {
2441
- parts.push(`## Phase ${phase.phase_index}: ${phase.title.replace(/^Phase\s+\d+:\s*/i, "")}`);
2442
- if (phase.annotations.execution) parts.push(`<!-- execution: ${phase.annotations.execution} -->`);
2443
- if (Object.prototype.hasOwnProperty.call(phase.annotations, "depends")) {
2444
- parts.push(`<!-- depends: ${phase.annotations.depends || ""} -->`);
2445
- }
2446
- parts.push("");
2447
- for (const task of phase.tasks) {
2448
- const commit = task.commit_shas && task.commit_shas.length > 0 ? ` (${task.commit_shas[task.commit_shas.length - 1]})` : "";
2449
- parts.push(`- [${task.marker}] Task ${task.task_index}: ${task.title.replace(/^Task\s+\d+:\s*/i, "")}${commit}`);
2450
- if (task.repo) parts.push(` <!-- repo: ${task.repo} -->`);
2451
- if (task.files.length > 0) parts.push(` <!-- files: ${task.files.join(", ")} -->`);
2452
- if (task.depends.length > 0) parts.push(` <!-- depends: ${task.depends.join(", ")} -->`);
2453
- if (task.labels && task.labels.length > 0) parts.push(` <!-- labels: ${task.labels.join(", ")} -->`);
2454
- if (task.commit_shas && task.commit_shas.length > 0) parts.push(` <!-- commits: ${task.commit_shas.join(", ")} -->`);
2455
- if (task.task_type) parts.push(` <!-- task-type: ${task.task_type} -->`);
2456
- if (task.manual_verification) {
2457
- const manual = asJsonObject(task.manual_verification);
2458
- const scope = asOptionalString(manual.scope);
2459
- if (scope) parts.push(` <!-- manual-verification-scope: ${scope} -->`);
2460
- const checks = asArray(manual.suggested_checks);
2461
- if (checks.length > 0) parts.push(` <!-- manual-verification-checks: ${checks.length} suggested -->`);
2462
- }
2463
- parts.push("");
2464
- }
2465
- }
2466
- appendCanonicalJsonReference(parts, canonicalSource);
2467
- return normalizedText(parts.join("\n"));
2468
- }
2469
-
2470
- // src/dap/config.ts
2471
- var import_node_fs11 = __toESM(require("node:fs"));
2472
- var import_node_path19 = __toESM(require("node:path"));
2473
- function configPath(root, config) {
2474
- const rel = config || "cadre/dap.json";
2475
- return import_node_path19.default.isAbsolute(rel) ? rel : import_node_path19.default.join(root, rel);
2476
- }
2477
- function readConfig(file) {
2478
- try {
2479
- return asJsonObject(JSON.parse(import_node_fs11.default.readFileSync(file, "utf8")));
2480
- } catch {
2481
- return {};
2482
- }
2483
- }
2484
- function substitute(value, tokens) {
2485
- if (typeof value === "string") {
2486
- return Object.entries(tokens).reduce((text, [token, replacement]) => text.split(token).join(replacement), value);
2487
- }
2488
- if (Array.isArray(value)) return value.map((entry) => substitute(entry, tokens));
2489
- if (!isRecord(value)) return value;
2490
- return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, substitute(entry, tokens)]));
2491
- }
2492
- function normalizeBreakpoints(root, raw) {
2493
- if (!Array.isArray(raw)) return [];
2494
- return raw.map(asJsonObject).flatMap((entry) => {
2495
- const file = asOptionalString(entry.file) || asOptionalString(entry.path);
2496
- const line = asNumber(entry.line);
2497
- if (!file || line < 1) return [];
2498
- const abs = import_node_path19.default.isAbsolute(file) ? file : import_node_path19.default.join(root, file);
2499
- return [{
2500
- ...entry,
2501
- file: import_node_path19.default.relative(root, abs).split(import_node_path19.default.sep).join("/"),
2502
- line
2503
- }];
2504
- });
2505
- }
2506
- function normalizeDapSession(root, args = {}) {
2507
- const file = configPath(root, args.config);
2508
- const loaded = readConfig(file);
2509
- const inlineConfiguration = asJsonObject(args.configuration);
2510
- const configurationId = asOptionalString(args.configurationId || args.configuration_id || args.id);
2511
- const configurations = Array.isArray(loaded.configurations) ? loaded.configurations.map(asJsonObject) : [];
2512
- const configuration = Object.keys(inlineConfiguration).length > 0 ? inlineConfiguration : configurations.find((entry) => asOptionalString(entry.id) === configurationId) || configurations[0] || {};
2513
- if (Object.keys(configuration).length === 0) return { ok: false, error: "DAP configuration is required" };
2514
- const adapters = Array.isArray(loaded.adapters) ? loaded.adapters.map(asJsonObject) : [];
2515
- const adapterId = asOptionalString(configuration.adapterId) || asOptionalString(configuration.adapter_id);
2516
- const inlineAdapter = asJsonObject(configuration.adapter);
2517
- const adapter = Object.keys(inlineAdapter).length > 0 ? inlineAdapter : adapters.find((entry) => asOptionalString(entry.id) === adapterId) || {};
2518
- const command = asOptionalString(adapter.command);
2519
- if (!command) return { ok: false, error: "DAP adapter command is required" };
2520
- const request = asOptionalString(configuration.request);
2521
- if (request !== "launch" && request !== "attach") return { ok: false, error: "DAP configuration request must be launch or attach" };
2522
- const tokens = {
2523
- "${workspaceFolder}": root,
2524
- "${root}": root,
2525
- "${cwd}": root,
2526
- "${testCommand}": asOptionalString(args.testCommand || args.test_command) || ""
2527
- };
2528
- return {
2529
- adapter: substitute(adapter, tokens),
2530
- configuration: substitute(configuration, tokens),
2531
- request,
2532
- arguments: substitute(configuration.arguments || configuration.args || {}, tokens),
2533
- breakpoints: normalizeBreakpoints(root, args.breakpoints || configuration.breakpoints),
2534
- timeoutMs: Math.max(1e3, Math.min(10 * 60 * 1e3, asNumber(args.timeoutMs, 12e4)))
2535
- };
2536
- }
2537
- function redactDapValue(value) {
2538
- if (Array.isArray(value)) return value.map(redactDapValue);
2539
- if (!isRecord(value)) return value;
2540
- return Object.fromEntries(Object.entries(value).map(([key, entry]) => {
2541
- const sensitive = /token|password|secret|credential|apikey|api_key|authorization/i.test(key);
2542
- return [key, sensitive ? "<redacted>" : redactDapValue(entry)];
2543
- }));
2544
- }
2545
-
2546
- // src/dap/snapshot.ts
2547
- var import_node_path20 = __toESM(require("node:path"));
2548
-
2549
- // src/dap/client.ts
2550
- var import_node_child_process4 = require("node:child_process");
2551
-
2552
- // src/dap/protocol.ts
2553
- function encodeDapMessage(message) {
2554
- const body = JSON.stringify(message);
2555
- return Buffer.from(`Content-Length: ${Buffer.byteLength(body, "utf8")}\r
2556
- \r
2557
- ${body}`, "utf8");
2558
- }
2559
- var DapMessageBuffer = class {
2560
- buffer = Buffer.alloc(0);
2561
- push(chunk) {
2562
- this.buffer = Buffer.concat([this.buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8")]);
2563
- const messages = [];
2564
- while (true) {
2565
- const headerEnd = this.buffer.indexOf("\r\n\r\n");
2566
- if (headerEnd === -1) return messages;
2567
- const header = this.buffer.slice(0, headerEnd).toString("utf8");
2568
- const lengthMatch = header.match(/Content-Length:\s*(\d+)/i);
2569
- if (!lengthMatch) {
2570
- this.buffer = this.buffer.slice(headerEnd + 4);
2571
- continue;
2572
- }
2573
- const length = Number(lengthMatch[1]);
2574
- const bodyStart = headerEnd + 4;
2575
- const bodyEnd = bodyStart + length;
2576
- if (this.buffer.length < bodyEnd) return messages;
2577
- const rawBody = this.buffer.slice(bodyStart, bodyEnd).toString("utf8");
2578
- this.buffer = this.buffer.slice(bodyEnd);
2579
- try {
2580
- messages.push(asJsonObject(JSON.parse(rawBody)));
2581
- } catch {
2582
- }
2583
- }
2584
- }
2585
- };
2586
-
2587
- // src/dap/client.ts
2588
- var DapClient = class {
2589
- constructor(options) {
2590
- this.options = options;
2591
- }
2592
- proc = null;
2593
- nextSeq = 1;
2594
- pending = /* @__PURE__ */ new Map();
2595
- waiters = [];
2596
- reader = new DapMessageBuffer();
2597
- stderr = "";
2598
- events = [];
2599
- outputs = [];
2600
- start() {
2601
- return new Promise((resolve, reject) => {
2602
- let settled = false;
2603
- const fail = (error) => {
2604
- if (!settled) {
2605
- settled = true;
2606
- reject(error);
2607
- }
2608
- };
2609
- this.proc = (0, import_node_child_process4.spawn)(this.options.command, this.options.args || [], {
2610
- cwd: this.options.cwd,
2611
- stdio: ["pipe", "pipe", "pipe"]
2612
- });
2613
- this.proc.once("spawn", () => {
2614
- if (!settled) {
2615
- settled = true;
2616
- resolve();
2617
- }
2618
- });
2619
- this.proc.once("error", (error) => fail(new Error(`Unable to start DAP adapter ${this.options.command}: ${errorMessage(error)}`)));
2620
- this.proc.stdout.on("data", (chunk) => this.read(chunk));
2621
- this.proc.stderr.on("data", (chunk) => {
2622
- this.stderr = `${this.stderr}${chunk.toString("utf8")}`.slice(-(this.options.outputLimit || 8e3));
2623
- });
2624
- this.proc.on("exit", (code, signal) => this.rejectAll(signal ? `DAP adapter exited with signal ${signal}` : `DAP adapter exited with code ${code}`));
2625
- });
2626
- }
2627
- read(chunk) {
2628
- for (const message of this.reader.push(chunk)) this.handleMessage(message);
2629
- }
2630
- handleMessage(message) {
2631
- if (message.type === "response") {
2632
- const requestSeq = Number(message.request_seq);
2633
- const pending = this.pending.get(requestSeq);
2634
- if (!pending) return;
2635
- this.pending.delete(requestSeq);
2636
- clearTimeout(pending.timer);
2637
- if (message.success === false) {
2638
- pending.reject(new Error(asOptionalString(message.message) || `${message.command || "request"} failed`));
2639
- } else {
2640
- pending.resolve(asJsonObject(message.body));
2641
- }
2642
- return;
2643
- }
2644
- if (message.type === "event") {
2645
- this.events.push(message);
2646
- if (message.event === "output") this.outputs.push(message);
2647
- this.resolveWaiters(message);
2648
- }
2649
- }
2650
- resolveWaiters(message) {
2651
- const eventName = asOptionalString(message.event);
2652
- if (!eventName) return;
2653
- const ready = this.waiters.filter((waiter) => waiter.events.includes(eventName));
2654
- this.waiters = this.waiters.filter((waiter) => !waiter.events.includes(eventName));
2655
- for (const waiter of ready) {
2656
- clearTimeout(waiter.timer);
2657
- waiter.resolve(message);
2658
- }
2659
- }
2660
- rejectAll(message) {
2661
- for (const pending of this.pending.values()) {
2662
- clearTimeout(pending.timer);
2663
- pending.reject(new Error(message));
2664
- }
2665
- this.pending.clear();
2666
- for (const waiter of this.waiters) {
2667
- clearTimeout(waiter.timer);
2668
- waiter.resolve(null);
2669
- }
2670
- this.waiters = [];
2671
- }
2672
- request(command, args = {}, timeoutMs = this.options.requestTimeoutMs || 1e4) {
2673
- if (!this.proc) return Promise.reject(new Error("DAP adapter is not running"));
2674
- const seq = this.nextSeq++;
2675
- const message = { seq, type: "request", command, arguments: args };
2676
- return new Promise((resolve, reject) => {
2677
- const timer = setTimeout(() => {
2678
- this.pending.delete(seq);
2679
- reject(new Error(`${command} timed out after ${timeoutMs}ms`));
2680
- }, timeoutMs);
2681
- this.pending.set(seq, { resolve, reject, timer });
2682
- this.proc?.stdin.write(encodeDapMessage(message));
2683
- });
2684
- }
2685
- waitForAny(events, timeoutMs) {
2686
- const existing = this.events.find((message) => events.includes(asOptionalString(message.event) || ""));
2687
- if (existing) return Promise.resolve(existing);
2688
- return new Promise((resolve) => {
2689
- const timer = setTimeout(() => {
2690
- this.waiters = this.waiters.filter((waiter) => waiter.resolve !== resolve);
2691
- resolve(null);
2692
- }, timeoutMs);
2693
- this.waiters.push({ events, resolve, timer });
2694
- });
2695
- }
2696
- stderrTail() {
2697
- return this.stderr;
2698
- }
2699
- async shutdown() {
2700
- try {
2701
- await this.request("disconnect", { terminateDebuggee: true, restart: false }, 2e3);
2702
- } catch {
2703
- }
2704
- if (this.proc && !this.proc.killed) this.proc.kill("SIGTERM");
2705
- }
2706
- };
2707
-
2708
- // src/dap/snapshot.ts
2709
- function delay(ms) {
2710
- return new Promise((resolve) => setTimeout(resolve, ms));
2711
- }
2712
- function redactText(value) {
2713
- return value.replace(/(token|password|secret|api[_-]?key|authorization)(\s*[=:]\s*)\S+/gi, "$1$2<redacted>").slice(-8e3);
2714
- }
2715
- function outputEvents(client) {
2716
- return client.outputs.slice(-50).map((event) => {
2717
- const body = asJsonObject(event.body);
2718
- return {
2719
- category: asOptionalString(body.category) || "console",
2720
- output: redactText(asOptionalString(body.output) || "")
2721
- };
2722
- });
2723
- }
2724
- async function requestOptional(client, command, args, timeoutMs = 3e3) {
2725
- try {
2726
- return await client.request(command, args, timeoutMs);
2727
- } catch {
2728
- return null;
2729
- }
2730
- }
2731
- async function collectVariables(client, variablesReference, limit) {
2732
- if (variablesReference <= 0) return [];
2733
- const result = await requestOptional(client, "variables", { variablesReference, start: 0, count: limit });
2734
- const variables = Array.isArray(result?.variables) ? result.variables.map(asJsonObject) : [];
2735
- return variables.slice(0, limit).map((variable) => ({
2736
- name: asOptionalString(variable.name) || "",
2737
- type: asOptionalString(variable.type) || null,
2738
- value: redactText(asOptionalString(variable.value) || ""),
2739
- variablesReference: asNumber(variable.variablesReference)
2740
- }));
2741
- }
2742
- async function collectScopes(client, frameId, variableLimit) {
2743
- const scopesResult = await requestOptional(client, "scopes", { frameId });
2744
- const scopes = Array.isArray(scopesResult?.scopes) ? scopesResult.scopes.map(asJsonObject) : [];
2745
- const collected = [];
2746
- for (const scope of scopes.slice(0, 6)) {
2747
- const variablesReference = asNumber(scope.variablesReference);
2748
- collected.push({
2749
- name: asOptionalString(scope.name) || "scope",
2750
- expensive: scope.expensive === true,
2751
- variables: await collectVariables(client, variablesReference, variableLimit)
2752
- });
2753
- }
2754
- return collected;
2755
- }
2756
- async function collectStoppedSnapshot(client, event, args) {
2757
- const body = asJsonObject(event.body);
2758
- const frameLimit = Math.max(1, Math.min(50, asNumber(args.limit, 20)));
2759
- const variableLimit = Math.max(1, Math.min(100, asNumber(args.variableLimit || args.variable_limit, 25)));
2760
- const threadsResult = await requestOptional(client, "threads", {});
2761
- const threadIds = asNumber(body.threadId) > 0 ? [asNumber(body.threadId)] : Array.isArray(threadsResult?.threads) ? threadsResult.threads.map(asJsonObject).map((thread) => asNumber(thread.id)).filter(Boolean) : [];
2762
- const threads = [];
2763
- for (const threadId of threadIds.slice(0, 8)) {
2764
- const stack = await requestOptional(client, "stackTrace", { threadId, startFrame: 0, levels: frameLimit });
2765
- const frames = Array.isArray(stack?.stackFrames) ? stack.stackFrames.map(asJsonObject) : [];
2766
- const summarizedFrames = [];
2767
- for (const frame of frames.slice(0, frameLimit)) {
2768
- const source = asJsonObject(frame.source);
2769
- const frameId = asNumber(frame.id);
2770
- summarizedFrames.push({
2771
- id: frameId,
2772
- name: asOptionalString(frame.name) || "",
2773
- file: asOptionalString(source.path) || asOptionalString(source.name) || null,
2774
- line: asNumber(frame.line),
2775
- column: asNumber(frame.column),
2776
- scopes: summarizedFrames.length === 0 ? await collectScopes(client, frameId, variableLimit) : []
2777
- });
2778
- }
2779
- threads.push({ threadId, frames: summarizedFrames });
2780
- }
2781
- return {
2782
- event: "stopped",
2783
- reason: asOptionalString(body.reason) || null,
2784
- description: asOptionalString(body.description) || null,
2785
- thread_id: asNumber(body.threadId) || null,
2786
- threads
2787
- };
2788
- }
2789
- async function setBreakpoints(client, root, breakpoints) {
2790
- const groups = /* @__PURE__ */ new Map();
2791
- for (const breakpoint of breakpoints) {
2792
- const file = asOptionalString(breakpoint.file);
2793
- if (!file) continue;
2794
- const entries = groups.get(file) || [];
2795
- entries.push(breakpoint);
2796
- groups.set(file, entries);
2797
- }
2798
- const results = [];
2799
- for (const [file, entries] of groups.entries()) {
2800
- const abs = import_node_path20.default.isAbsolute(file) ? file : import_node_path20.default.join(root, file);
2801
- const response = await requestOptional(client, "setBreakpoints", {
2802
- source: { path: abs },
2803
- breakpoints: entries.map((entry) => ({
2804
- line: asNumber(entry.line),
2805
- condition: asOptionalString(entry.condition),
2806
- hitCondition: asOptionalString(entry.hitCondition || entry.hit_condition),
2807
- logMessage: asOptionalString(entry.logMessage || entry.log_message)
2808
- }))
2809
- });
2810
- results.push({
2811
- file,
2812
- breakpoints: Array.isArray(response?.breakpoints) ? response.breakpoints.map(asJsonObject) : []
2813
- });
2814
- }
2815
- return results;
2816
- }
2817
- async function dapSnapshot(root, args = {}) {
2818
- const normalized = normalizeDapSession(root, args);
2819
- if ("ok" in normalized && normalized.ok === false) return normalized;
2820
- const session = normalized;
2821
- const command = asOptionalString(session.adapter.command) || "";
2822
- const adapterArgs = asStringArray(session.adapter.args);
2823
- const client = new DapClient({
2824
- command,
2825
- args: adapterArgs,
2826
- cwd: root,
2827
- requestTimeoutMs: asNumber(session.adapter.requestTimeoutMs, 1e4),
2828
- outputLimit: 8e3
2829
- });
2830
- let launchResponse = null;
2831
- let launchError = null;
2832
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2833
- try {
2834
- await client.start();
2835
- const initialize = await client.request("initialize", {
2836
- adapterID: asOptionalString(session.adapter.id) || command,
2837
- clientID: "cadre",
2838
- clientName: "Cadre",
2839
- pathFormat: "path",
2840
- linesStartAt1: true,
2841
- columnsStartAt1: true,
2842
- supportsVariableType: true,
2843
- supportsVariablePaging: true
2844
- });
2845
- const initialized = client.waitForAny(["initialized"], Math.min(5e3, session.timeoutMs));
2846
- const launch = client.request(session.request, session.arguments, session.timeoutMs).then((body) => {
2847
- launchResponse = body;
2848
- }).catch((error) => {
2849
- launchError = errorMessage(error);
2850
- });
2851
- await initialized;
2852
- const breakpointResults = await setBreakpoints(client, root, session.breakpoints);
2853
- await requestOptional(client, "configurationDone", {}, 3e3);
2854
- await Promise.race([launch, delay(250)]);
2855
- if (launchError) throw new Error(launchError);
2856
- const finalEvent = await client.waitForAny(["stopped", "terminated", "exited"], session.timeoutMs);
2857
- const snapshot = finalEvent?.event === "stopped" ? await collectStoppedSnapshot(client, finalEvent, args) : {
2858
- event: asOptionalString(finalEvent?.event) || "timeout",
2859
- body: finalEvent ? asJsonObject(redactDapValue(asJsonObject(finalEvent.body))) : null
2860
- };
2861
- return {
2862
- ok: finalEvent !== null,
2863
- root,
2864
- started_at: startedAt,
2865
- finished_at: (/* @__PURE__ */ new Date()).toISOString(),
2866
- adapter: {
2867
- id: asOptionalString(session.adapter.id) || command,
2868
- command,
2869
- args: adapterArgs
2870
- },
2871
- request: session.request,
2872
- configuration: redactDapValue(session.configuration),
2873
- initialize,
2874
- launch_response: launchResponse,
2875
- breakpoints: breakpointResults,
2876
- snapshot,
2877
- output: outputEvents(client),
2878
- adapter_stderr_tail: redactText(client.stderrTail()),
2879
- error: finalEvent ? void 0 : `DAP snapshot timed out after ${session.timeoutMs}ms`
2880
- };
2881
- } catch (error) {
2882
- return {
2883
- ok: false,
2884
- root,
2885
- started_at: startedAt,
2886
- finished_at: (/* @__PURE__ */ new Date()).toISOString(),
2887
- adapter: { command, args: adapterArgs },
2888
- configuration: redactDapValue(session.configuration),
2889
- output: outputEvents(client),
2890
- adapter_stderr_tail: redactText(client.stderrTail()),
2891
- error: errorMessage(error)
2892
- };
2893
- } finally {
2894
- await client.shutdown();
2895
- }
2896
- }
2897
-
2898
- // src/core/application/runtime/task-completion.ts
2899
- var import_node_path22 = __toESM(require("node:path"));
2900
-
2901
- // src/core/application/runtime/manual-verification.ts
2902
- var import_node_path21 = __toESM(require("node:path"));
2903
- function completionJournalPath(track) {
2904
- return import_node_path21.default.join(track.dir, "completion_journal.json");
2905
- }
2906
- function readCompletionJournal(track) {
2907
- const value = readJson(completionJournalPath(track), { entries: {} });
2908
- if (!isRecord(value)) return { entries: {} };
2909
- const entries = isRecord(value.entries) ? value.entries : {};
2910
- return {
2911
- ...asJsonObject(value),
2912
- entries: Object.fromEntries(Object.entries(entries).map(([key, entry]) => [key, asJsonObject(entry)]))
2913
- };
2914
- }
2915
- function writeCompletionJournal(track, journal) {
2916
- writeJson(completionJournalPath(track), journal);
2917
- }
2918
- function patchCompletionJournal(track, key, patcher) {
2919
- const journal = readCompletionJournal(track);
2920
- const before = journal.entries[key] || {};
2921
- journal.entries[key] = patcher({ ...before }, journal);
2922
- journal.updated_at = utcNow();
2923
- writeCompletionJournal(track, journal);
2924
- appendJsonl(import_node_path21.default.join(track.dir, "completion_journal.jsonl"), {
2925
- key,
2926
- recorded_at: journal.updated_at,
2927
- entry: journal.entries[key]
2928
- });
2929
- return journal.entries[key];
2930
- }
2931
- function manualVerificationChecksFromInput(value) {
2932
- if (Array.isArray(value)) {
2933
- return value.map((entry, index) => {
2934
- if (typeof entry === "string") return { id: `check-${index + 1}`, heading: entry, status: "reported" };
2935
- return asJsonObject(entry);
2936
- }).filter((entry) => Object.keys(entry).length > 0);
2937
- }
2938
- if (typeof value === "string" && value.trim()) {
2939
- return value.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line, index) => ({ id: `check-${index + 1}`, heading: line, status: "reported" }));
2940
- }
2941
- const object = asJsonObject(value);
2942
- if (Array.isArray(object.checks)) return manualVerificationChecksFromInput(object.checks);
2943
- return Object.keys(object).length > 0 ? [object] : [];
2944
- }
2945
- function manualVerificationResultObject(value) {
2946
- if (typeof value === "string" && value.trim()) return { summary: value.trim() };
2947
- return asJsonObject(value);
2948
- }
2949
- function manualVerificationInputResult(args) {
2950
- return manualVerificationResultObject(args.manualVerificationResult || args.manual_verification_result);
2951
- }
2952
- function manualVerificationInputSummary(args, result) {
2953
- return asOptionalString(args.manualVerificationSummary || args.manual_verification_summary) || asOptionalString(result.summary) || asOptionalString(result.message) || "";
2954
- }
2955
- function manualVerificationInputChecks(args, result) {
2956
- return manualVerificationChecksFromInput(args.manualVerificationChecks || args.manual_verification_checks || result.checks);
2957
- }
2958
- function manualVerificationCommand(args) {
2959
- return asOptionalString(args.manualVerificationCommand || args.manual_verification_command) || null;
2960
- }
2961
- function commandResultEvidence(result) {
2962
- return {
2963
- ok: result.ok,
2964
- status: result.status,
2965
- signal: result.signal || null,
2966
- command: result.command,
2967
- cwd: result.cwd || null,
2968
- stdout_tail: result.stdout.slice(-4e3),
2969
- stderr_tail: result.stderr.slice(-4e3)
2970
- };
2971
- }
2972
- function prepareManualVerificationCompletion(root, track, task, args, workingRoot) {
2973
- const mode = asOptionalString(args.manualVerificationMode || args.manual_verification_mode) || (manualVerificationCommand(args) ? "autorun" : "offline");
2974
- const command = manualVerificationCommand(args);
2975
- const suggestedChecks = asArray(asJsonObject(task.manual_verification).suggested_checks).map(asJsonObject);
2976
- const inputResult = manualVerificationInputResult(args);
2977
- const confirmed = humanReviewConfirmed(args);
2978
- if (mode === "autorun" && !confirmed) {
2979
- if (!command) {
2980
- return {
2981
- ok: false,
2982
- blocked: true,
2983
- stage: "manual_verification",
2984
- reason: "manualVerificationCommand is required for autorun manual verification"
2985
- };
2986
- }
2987
- const result = runCommand(command, [], {
2988
- cwd: workingRoot.path,
2989
- shell: true,
2990
- timeoutMs: Number(args.timeoutMs || 10 * 60 * 1e3),
2991
- maxBuffer: 30 * 1024 * 1024
2992
- });
2993
- const evidence2 = {
2994
- mode,
2995
- approved: false,
2996
- task_key: task.task_key,
2997
- scope: manualVerificationScope(task),
2998
- summary: result.ok ? "Autorun manual verification command completed successfully." : "Autorun manual verification command failed.",
2999
- suggested_checks: suggestedChecks,
3000
- checks: manualVerificationInputChecks(args, inputResult),
3001
- command,
3002
- result: commandResultEvidence(result),
3003
- recorded_at: utcNow()
3004
- };
3005
- return {
3006
- ok: false,
3007
- dry_run: true,
3008
- blocked: true,
3009
- phase_state: "awaiting_staged_approval",
3010
- stage: "manual_verification_approval",
3011
- track_id: track.track_id,
3012
- task_key: task.task_key,
3013
- manual_verification: evidence2,
3014
- reason: "Human approval is required before marking manual verification complete"
3015
- };
3016
- }
3017
- if (!confirmed) {
3018
- return {
3019
- ok: false,
3020
- dry_run: true,
3021
- blocked: true,
3022
- phase_state: "awaiting_staged_approval",
3023
- stage: "manual_verification_approval",
3024
- track_id: track.track_id,
3025
- task_key: task.task_key,
3026
- manual_verification: {
3027
- mode,
3028
- approved: false,
3029
- task_key: task.task_key,
3030
- scope: manualVerificationScope(task),
3031
- suggested_checks: suggestedChecks
3032
- },
3033
- reason: "Human approval is required before marking manual verification complete"
3034
- };
3035
- }
3036
- let commandEvidence = isRecord(inputResult.result) ? asJsonObject(inputResult.result) : null;
3037
- if (mode === "autorun" && command && !commandEvidence) {
3038
- const result = runCommand(command, [], {
3039
- cwd: workingRoot.path,
3040
- shell: true,
3041
- timeoutMs: Number(args.timeoutMs || 10 * 60 * 1e3),
3042
- maxBuffer: 30 * 1024 * 1024
3043
- });
3044
- commandEvidence = commandResultEvidence(result);
3045
- }
3046
- const summary = manualVerificationInputSummary(args, inputResult) || (commandEvidence ? commandEvidence.ok === true ? "Approved autorun manual verification result." : "Approved autorun manual verification result with failures noted." : "");
3047
- if (!summary.trim()) {
3048
- return {
3049
- ok: false,
3050
- blocked: true,
3051
- stage: "manual_verification_summary",
3052
- track_id: track.track_id,
3053
- task_key: task.task_key,
3054
- reason: "manualVerificationSummary or manualVerificationResult.summary is required"
3055
- };
3056
- }
3057
- const evidence = {
3058
- mode,
3059
- approved: true,
3060
- approved_at: utcNow(),
3061
- approved_by: gitIdentity(root) || null,
3062
- task_key: task.task_key,
3063
- scope: manualVerificationScope(task),
3064
- summary: summary.trim(),
3065
- suggested_checks: suggestedChecks,
3066
- checks: manualVerificationInputChecks(args, inputResult),
3067
- ...command ? { command } : {},
3068
- ...commandEvidence ? { result: commandEvidence } : {},
3069
- recorded_at: utcNow()
3070
- };
3071
- return { ok: true, evidence };
3072
- }
3073
-
3074
- // src/core/application/runtime/task-completion.ts
3075
- function completeTask(root, args = {}) {
3076
- return withSharedControlPlaneSync(root, args, "complete_task", () => completeTaskInner(root, { ...args, skipSync: true }));
3077
- }
3078
- function completeTaskInner(root, args = {}) {
3079
- const track = findTrack(root, args.trackId);
3080
- if (!track) return { ok: false, error: `Track not found: ${args.trackId}` };
3081
- const phaseIndex = Number(args.phaseIndex);
3082
- const taskIndex = Number(args.taskIndex);
3083
- const plan = parsePlanFile(track.plan_path);
3084
- const phase = (plan.phases || []).find((item) => item.phase_index === phaseIndex);
3085
- const task = phase && (phase.tasks || []).find((item) => item.task_index === taskIndex);
3086
- if (!task) return { ok: false, error: `Task not found: phase ${phaseIndex} task ${taskIndex}` };
3087
- const workingRoot = resolveTaskWorkingRoot(root, track, task, args);
3088
- if (isWorkingRootError(workingRoot)) {
3089
- return {
3090
- ok: false,
3091
- stage: "polyrepo_repo_resolution",
3092
- blocked: true,
3093
- working_root: workingRoot,
3094
- reason: workingRoot.error
3095
- };
3096
- }
3097
- if (workingRoot.source !== "argument.workingRoot" && workingRoot.source !== "branch-set.integration_worktree" && workingRoot.branch_set) {
3098
- const branchSet = workingRoot.branch_set;
3099
- return {
3100
- ok: false,
3101
- stage: "worktree_setup",
3102
- blocked: true,
3103
- working_root: workingRoot,
3104
- branch_set: branchSet,
3105
- reason: branchSet.exists ? `Integration worktree for ${branchSet.repo} is ${branchSet.health}; complete_task requires the expected track branch or an explicit worker root` : `Integration worktree for ${branchSet.repo} is missing; run worktree_plan with execute before complete_task or pass an explicit worker root`,
3106
- worktree_plan: worktreePlan(root, { trackId: track.track_id, repo: branchSet.repo })
3107
- };
3108
- }
3109
- const manualVerificationTask = isManualVerificationTaskObject(task);
3110
- const manualVerificationCompletion = manualVerificationTask ? prepareManualVerificationCompletion(root, track, task, args, workingRoot) : null;
3111
- if (manualVerificationCompletion && manualVerificationCompletion.ok === false) return manualVerificationCompletion;
3112
- const manualVerificationEvidence = manualVerificationCompletion && isRecord(manualVerificationCompletion.evidence) ? asJsonObject(manualVerificationCompletion.evidence) : null;
3113
- const coverage = manualVerificationTask ? {
3114
- ok: true,
3115
- available: false,
3116
- command: null,
3117
- coverage: null,
3118
- reason: "Manual verification task uses structured human-approved evidence instead of coverage."
3119
- } : runCoverage(root, args, workingRoot.path);
3120
- const threshold = Number(args.coverageThreshold ?? coverageThreshold(root));
3121
- const allowMissingCoverage = args.allowMissingCoverage === true;
3122
- const allowLowCoverage = args.allowLowCoverage === true;
3123
- if (!manualVerificationTask && !coverage.available && !allowMissingCoverage) {
3124
- return {
3125
- ok: false,
3126
- stage: "coverage",
3127
- blocked: true,
3128
- threshold,
3129
- coverage,
3130
- reason: coverage.reason || "Coverage command unavailable"
3131
- };
3132
- }
3133
- if (!manualVerificationTask && coverage.available && !coverage.ok) {
3134
- return {
3135
- ok: false,
3136
- stage: "coverage",
3137
- blocked: true,
3138
- threshold,
3139
- coverage,
3140
- reason: "Coverage/test command failed; task was not marked complete"
3141
- };
3142
- }
3143
- if (!manualVerificationTask && coverage.available && typeof coverage.coverage === "number" && coverage.coverage < threshold && !allowLowCoverage) {
3144
- return {
3145
- ok: false,
3146
- stage: "coverage",
3147
- blocked: true,
3148
- threshold,
3149
- coverage,
3150
- reason: `Coverage ${coverage.coverage}% is below required ${threshold}%; task was not marked complete`
3151
- };
3152
- }
3153
- let resolvedCommitSha = args.commitSha ? String(args.commitSha).trim() : "";
3154
- let productCommit = null;
3155
- if (!resolvedCommitSha && args.allowNoCommit !== true) {
3156
- const productBefore = beginTrace(workingRoot.path);
3157
- productCommit = commitTrace(root, args, {
3158
- kind: "product",
3159
- workflow: "complete_task",
3160
- subject: task.title.replace(/^Task\s+\d+:\s*/i, ""),
3161
- scope: asOptionalString(workingRoot.repo) && workingRoot.repo !== "." ? asOptionalString(workingRoot.repo) || "task" : "task",
3162
- cwd: workingRoot.path,
3163
- before: productBefore,
3164
- files: asStringArray(args.filesChanged || args.files_changed || args.files).length > 0 ? asStringArray(args.filesChanged || args.files_changed || args.files) : task.files,
3165
- allowDirty: true,
3166
- trackId: track.track_id,
3167
- repo: workingRoot.repo,
3168
- note: {
3169
- phase_index: phaseIndex,
3170
- task_index: taskIndex,
3171
- task_key: task.task_key,
3172
- coverage: coverage.coverage ?? null
3173
- }
3174
- });
3175
- if (productCommit.ok === false) return { ...productCommit, stage: "product_commit", working_root: workingRoot };
3176
- resolvedCommitSha = asOptionalString(productCommit.commit_sha) || "";
3177
- }
3178
- const lastTestRun = manualVerificationTask ? null : {
3179
- command: coverage.command,
3180
- cwd: coverage.cwd || workingRoot.path,
3181
- ok: coverage.available ? coverage.ok : null,
3182
- status: coverage.available ? coverage.status : null,
3183
- signal: coverage.available ? coverage.signal : null,
3184
- coverage: coverage.coverage,
3185
- threshold,
3186
- measured_at: utcNow(),
3187
- allow_missing_coverage: allowMissingCoverage,
3188
- allow_low_coverage: allowLowCoverage
3189
- };
3190
- const sha = resolvedCommitSha ? resolvedCommitSha.slice(0, 12) : "unknown";
3191
- const dedupKey = `key: ${track.track_id}:p${phaseIndex}:t${taskIndex}:${sha.slice(0, 7)}`;
3192
- const journalKey = `${phaseIndex}:${taskIndex}:${sha}`;
3193
- const controlBefore = beginTrace(root);
3194
- const recordState = () => {
3195
- const entry = patchCompletionJournal(track, journalKey, (current) => ({
3196
- ...current,
3197
- stage: current.stage || "started",
3198
- track_id: track.track_id,
3199
- phase_index: phaseIndex,
3200
- task_index: taskIndex,
3201
- task_key: task.task_key,
3202
- commit_sha: sha,
3203
- dedup_key: dedupKey,
3204
- started_at: current.started_at || utcNow()
3205
- }));
3206
- const taskResult = recordTaskResultUnlocked(root, {
3207
- trackId: args.trackId,
3208
- phaseIndex,
3209
- taskIndex,
3210
- status: args.status || "completed",
3211
- commitSha: resolvedCommitSha || args.commitSha,
3212
- coverage: coverage.coverage,
3213
- repo: workingRoot.repo,
3214
- workingRoot: import_node_path22.default.relative(root, workingRoot.path) || ".",
3215
- ...lastTestRun ? { lastTestRun } : {},
3216
- ...manualVerificationEvidence ? { manualVerificationEvidence } : {}
3217
- });
3218
- if (!taskResult.ok) {
3219
- patchCompletionJournal(track, journalKey, (current) => ({
3220
- ...current,
3221
- stage: "record_task_result_failed",
3222
- error: taskResult.error || asOptionalString(taskResult.stage) || "record task result failed"
3223
- }));
3224
- return { ok: false, stage: "record_task_result", threshold, working_root: workingRoot, coverage, task_result: taskResult, journal: entry };
3225
- }
3226
- const taskResultJson = asJsonObject(taskResult);
3227
- const recordedEntry = patchCompletionJournal(track, journalKey, (current) => ({
3228
- ...current,
3229
- stage: "state_recorded",
3230
- state_recorded_at: utcNow(),
3231
- task_result: {
3232
- task_key: taskResultJson.task_key,
3233
- commit_sha: taskResultJson.commit_sha,
3234
- line: taskResultJson.line
3235
- }
3236
- }));
3237
- return { ok: true, task_result: taskResult, journal: recordedEntry };
3238
- };
3239
- const stateResult = args.lock === false ? recordState() : withTrackLock(root, track.track_id, recordState);
3240
- if (!stateResult.ok) return { ...stateResult, threshold, working_root: workingRoot, coverage };
3241
- const stateTaskResult = asJsonObject(stateResult.task_result);
3242
- const markComplete = () => patchCompletionJournal(track, journalKey, (current) => ({
3243
- ...current,
3244
- stage: "completed",
3245
- completed_at: current.completed_at || utcNow()
3246
- }));
3247
- const completedJournal = args.lock === false ? markComplete() : withTrackLock(root, track.track_id, markComplete);
3248
- const event = appendCadreEvent(root, {
3249
- kind: "task_completed",
3250
- workflow: "complete_task",
3251
- track_id: track.track_id,
3252
- phase_index: phaseIndex,
3253
- task_index: taskIndex,
3254
- task_key: stateTaskResult.task_key,
3255
- status: args.status || "completed",
3256
- commit_sha: sha,
3257
- coverage: coverage.coverage ?? null,
3258
- summary: args.summary || null,
3259
- journal_key: journalKey
3260
- });
3261
- const controlCommit = commitTrace(root, args, {
3262
- kind: "control",
3263
- workflow: "complete",
3264
- subject: `record ${track.track_id} phase ${phaseIndex} task ${taskIndex}`,
3265
- before: controlBefore,
3266
- files: [
3267
- import_node_path22.default.relative(root, track.metadata_path),
3268
- import_node_path22.default.relative(root, track.plan_path),
3269
- import_node_path22.default.relative(root, trackPlanJsonPath(track)),
3270
- import_node_path22.default.relative(root, completionJournalPath(track)),
3271
- import_node_path22.default.relative(root, `${completionJournalPath(track)}l`),
3272
- import_node_path22.default.relative(root, import_node_path22.default.join(track.dir, "implement_state.json")),
3273
- "cadre/events.jsonl"
3274
- ],
3275
- allowDirty: true,
3276
- trackId: track.track_id,
3277
- repo: ".",
3278
- note: {
3279
- event_id: asOptionalString(asJsonObject(event.event).id) || null,
3280
- phase_index: phaseIndex,
3281
- task_index: taskIndex,
3282
- task_key: stateTaskResult.task_key,
3283
- product_commit_sha: asOptionalString(productCommit?.commit_sha) || resolvedCommitSha || null,
3284
- coverage: coverage.coverage ?? null
3285
- }
3286
- });
3287
- return {
3288
- ok: controlCommit.ok !== false,
3289
- track_id: track.track_id,
3290
- task_key: stateTaskResult.task_key,
3291
- working_root: workingRoot,
3292
- threshold,
3293
- coverage,
3294
- product_commit: productCommit,
3295
- control_commit: controlCommit,
3296
- task_result: stateTaskResult,
3297
- event,
3298
- journal: completedJournal.ok === false ? completedJournal : completedJournal.value || completedJournal
3299
- };
3300
- }
3301
-
3302
- // src/core/domain/project-skill-policy.ts
3303
- var PROJECT_SKILL_MAX_FILE_BYTES = 128 * 1024;
3304
-
3305
- // src/mcp/domain/tool-catalog.ts
3306
- var SERVER_INSTRUCTIONS = [
3307
- "Cadre is a packet-led runtime. Call cadre_workflow first for workflows, cadre_action for a packet named by a workflow response, and cadre_read only for a relevant resource URI.",
3308
- "Pass a root candidate to project-scoped calls. Cadre resolves it internally; setup accepts an uninitialized directory.",
3309
- "Cadre owns control-plane, provider, worker, approval, merge, and generated projection state."
3310
- ].join(" ");
3311
-
3312
- // src/cadre-job-runner.ts
3313
- function readStdin() {
3314
- return new Promise((resolve, reject) => {
3315
- let text = "";
3316
- process.stdin.setEncoding("utf8");
3317
- process.stdin.on("data", (chunk) => {
3318
- text += chunk;
3319
- });
3320
- process.stdin.on("end", () => resolve(text));
3321
- process.stdin.on("error", reject);
3322
- });
3323
- }
3324
- async function runJob(payload) {
3325
- const root = payload.root || process.cwd();
3326
- const args = asJsonObject(payload.args);
3327
- switch (asOptionalString(payload.type)) {
3328
- case "complete_task":
3329
- return completeTask(root, args);
3330
- case "coverage":
3331
- return testCoverage(root, args);
3332
- case "machine_gate":
3333
- return reviewMachineGate(root, args);
3334
- case "review_assist":
3335
- return reviewAssist(root, args);
3336
- case "lsp_review":
3337
- return lspReview(root, args);
3338
- case "lsp_impact":
3339
- return lspImpact(root, args);
3340
- case "dap_snapshot":
3341
- return dapSnapshot(root, args);
3342
- default:
3343
- return { ok: false, error: `Unsupported job type: ${payload.type}` };
3344
- }
3345
- }
3346
- async function runJobRunner() {
3347
- const input = await readStdin();
3348
- const payload = asJsonObject(JSON.parse(input || "{}"));
3349
- const result = await runJob(payload);
3350
- process.stdout.write(`${JSON.stringify(result, null, 2)}
3351
- `);
3352
- }
3353
- if (["cadre-job-runner.js", "cadre-job-runner.ts"].includes(import_node_path23.default.basename(process.argv[1] || ""))) {
3354
- runJobRunner().catch((error) => {
3355
- process.stdout.write(`${JSON.stringify({ ok: false, error: errorMessage(error), stack: error instanceof Error ? error.stack : void 0 }, null, 2)}
3356
- `);
3357
- process.exit(1);
3358
- });
3359
- }
3360
- // Annotate the CommonJS export names for ESM import in node:
3361
- 0 && (module.exports = {
3362
- readStdin,
3363
- runJob,
3364
- runJobRunner
3365
- });