@elvis1513/auto-coding-skill 4.3.7 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +30 -761
  2. package/cli/assets/managed-install.json +42 -1
  3. package/cli/assets/skill/SKILL.md +17 -100
  4. package/cli/assets/skill/data/templates/ENVIRONMENT.md +34 -0
  5. package/cli/assets/skill/data/templates/PROJECT.md +30 -0
  6. package/cli/assets/skill/data/templates/architecture/.gitkeep +1 -0
  7. package/cli/assets/skill/data/templates/bridges/AGENTS.md +52 -157
  8. package/cli/assets/skill/data/templates/deployment/.gitkeep +1 -0
  9. package/cli/assets/skill/data/templates/design/.gitkeep +1 -0
  10. package/cli/assets/skill/data/templates/interfaces/.gitkeep +1 -0
  11. package/cli/assets/skill/data/templates/product/.gitkeep +1 -0
  12. package/cli/src/index.js +154 -2585
  13. package/cli/src/sync-assets.js +38 -95
  14. package/package.json +9 -17
  15. package/cli/assets/agents/browser-debugger.toml +0 -27
  16. package/cli/assets/agents/docs-researcher.toml +0 -18
  17. package/cli/assets/agents/explorer.toml +0 -26
  18. package/cli/assets/agents/fixer.toml +0 -29
  19. package/cli/assets/agents/reviewer.toml +0 -50
  20. package/cli/assets/skill/data/contracts/orchestration-v1.schema.json +0 -567
  21. package/cli/assets/skill/data/policies/feedback-resolutions-v1.json +0 -68
  22. package/cli/assets/skill/data/policies/workflow-migrations-v1.json +0 -657
  23. package/cli/assets/skill/data/templates/ENGINEERING.md +0 -115
  24. package/cli/assets/skill/data/templates/tools/ap.py +0 -16
  25. package/cli/assets/skill/requirements.txt +0 -1
  26. package/cli/assets/skill/scripts/ap.py +0 -17791
  27. package/cli/assets/skill/scripts/core.py +0 -510
  28. package/cli/assets/skill/scripts/http_checks.py +0 -92
  29. package/cli/assets/skill/scripts/install_integrity.py +0 -427
  30. package/cli/assets/skill/scripts/scaffold_templates.py +0 -325
  31. package/cli/tests/ap_concurrency_test.py +0 -3602
  32. package/cli/tests/ap_profiles_test.py +0 -3272
  33. package/cli/tests/core_shell_test.py +0 -345
  34. package/cli/tests/index.test.js +0 -2967
package/cli/src/index.js CHANGED
@@ -1,2625 +1,194 @@
1
1
  #!/usr/bin/env node
2
+ import crypto from "node:crypto";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
4
- import os from "node:os";
5
- import crypto from "node:crypto";
6
- import { execFileSync, spawnSync } from "node:child_process";
7
5
  import { fileURLToPath } from "node:url";
8
6
 
9
- function die(msg){
10
- console.error(`\n[autocoding] ERROR: ${msg}\n`);
11
- process.exit(1);
12
- }
13
-
14
- function takeValue(rest, index, flag){
15
- const value = rest[index + 1];
16
- if (!value || value.startsWith("--")) die(`${flag} requires a value`);
17
- return value;
18
- }
19
-
20
- function parseArgs(argv){
21
- const args = {
22
- cmd: null,
23
- ai: null,
24
- mode: "project",
25
- dest: null,
26
- force: false,
27
- dryRun: false,
28
- json: false,
29
- resetAgentModels: false,
30
- components: "all",
31
- projects: [],
32
- projectsFlagProvided: false,
33
- provided: new Set(),
34
- };
35
- const [,, cmd, ...rest] = argv;
36
- args.cmd = (!cmd || cmd === "-h" || cmd === "--help") ? "help" : cmd;
37
- for (let i = 0; i < rest.length; i++) {
38
- const a = rest[i];
39
- if (a === "--ai") {
40
- args.ai = takeValue(rest, i, a);
41
- args.provided.add("ai");
42
- i += 1;
43
- }
44
- else if (a === "--mode") {
45
- args.mode = takeValue(rest, i, a);
46
- args.provided.add("mode");
47
- i += 1;
48
- }
49
- else if (a === "--dest") {
50
- args.dest = takeValue(rest, i, a);
51
- args.provided.add("dest");
52
- i += 1;
53
- }
54
- else if (a === "--projects") {
55
- args.projects.push(...takeValue(rest, i, a).split(",").map(x => x.trim()).filter(Boolean));
56
- args.projectsFlagProvided = true;
57
- args.provided.add("projects");
58
- i += 1;
59
- }
60
- else if (a === "--dry-run") {
61
- args.dryRun = true;
62
- args.provided.add("dryRun");
63
- }
64
- else if (a === "--json") {
65
- args.json = true;
66
- args.provided.add("json");
67
- }
68
- else if (a === "--reset-agent-models") {
69
- args.resetAgentModels = true;
70
- args.provided.add("resetAgentModels");
71
- }
72
- else if (a === "--components") {
73
- args.components = takeValue(rest, i, a).trim().toLowerCase();
74
- args.provided.add("components");
75
- i += 1;
76
- }
77
- else if (a === "--force") {
78
- args.force = true;
79
- args.provided.add("force");
80
- }
81
- else if (a === "-h" || a === "--help") args.cmd = "help";
82
- else if (!a.startsWith("--")) {
83
- args.projects.push(a);
84
- args.provided.add("projects");
85
- }
86
- else die(`unknown argument: ${a}`);
87
- }
88
- return args;
89
- }
90
-
91
- const ARG_FLAGS = {
92
- ai: "--ai",
93
- mode: "--mode",
94
- dest: "--dest",
95
- force: "--force",
96
- dryRun: "--dry-run",
97
- json: "--json",
98
- resetAgentModels: "--reset-agent-models",
99
- components: "--components",
100
- projects: "--projects/positional project",
101
- };
102
-
103
- const COMMAND_ARGS = {
104
- init: new Set(["ai", "mode", "dest", "force", "resetAgentModels"]),
105
- status: new Set(["projects", "json"]),
106
- sync: new Set(["projects", "dryRun", "json", "resetAgentModels", "components"]),
107
- feedback: new Set(["projects", "json"]),
108
- };
109
-
110
- function validateCommandArgs(args){
111
- const allowed = COMMAND_ARGS[args.cmd];
112
- if (!allowed) return;
113
- const invalid = [...args.provided].filter(name => !allowed.has(name));
114
- if (invalid.length) {
115
- die(`${invalid.map(name => ARG_FLAGS[name] || name).join(", ")} not valid for '${args.cmd}'`);
116
- }
117
- if (args.cmd === "sync" && args.components !== "all") {
118
- die("partial Skill sync was removed in 4.1; use --components all so Skill, AGENTS.md, ENGINEERING.md, agents, and runtime converge together");
119
- }
120
- if (args.cmd === "feedback" && (!args.projectsFlagProvided || args.projects.length === 0)) {
121
- die("'feedback' requires explicit --projects <path[,path...]>");
122
- }
123
- }
124
-
125
- function exists(p){ try { fs.accessSync(p); return true; } catch { return false; } }
126
- function rmrf(p){ fs.rmSync(p, { recursive: true, force: true }); }
127
- function quoted(value){ return JSON.stringify(String(value)); }
128
-
129
- function requireRuntimeDependencies(assetSkill){
130
- const defaultPython = process.platform === "win32" ? "python" : "python3";
131
- const python = String(process.env.AUTOCODING_PYTHON || defaultPython).trim() || defaultPython;
132
- const requirements = path.join(assetSkill, "requirements.txt");
133
- if (!exists(requirements)) die(`missing runtime dependency definition: ${requirements}`);
134
- const check = spawnSync(
135
- python,
136
- ["-c", "import yaml"],
137
- { encoding: "utf8", stdio: "pipe" },
138
- );
139
- if (check.status === 0) return;
140
- const detail = String(check.stderr || check.error?.message || "PyYAML import failed").trim().split(/\r?\n/).slice(-1)[0];
141
- const install = `${quoted(python)} -m pip install --requirement ${quoted(requirements)}`;
142
- die(
143
- `Python runtime dependency check failed${detail ? `: ${detail}` : ""}\n`
144
- + `Run: ${install}\nThen rerun autocoding init.`,
145
- );
146
- }
147
-
148
- function runtimePython(){
149
- const fallback = process.platform === "win32" ? "python" : "python3";
150
- return String(process.env.AUTOCODING_PYTHON || fallback).trim() || fallback;
151
- }
152
-
153
- function readInstallManifest(file){
154
- let manifest;
155
- try {
156
- manifest = JSON.parse(fs.readFileSync(file, "utf8"));
157
- } catch (error) {
158
- die(`invalid managed install manifest ${file}: ${error.message}`);
159
- }
160
- if (manifest?.schema_version !== 1 || !/^\d+\.\d+\.\d+$/.test(String(manifest?.skill_version || ""))) {
161
- die(`invalid managed install manifest schema/version: ${file}`);
162
- }
163
- if (!Array.isArray(manifest.entries) || !Array.isArray(manifest.managed_namespaces)) {
164
- die(`invalid managed install manifest entries/namespaces: ${file}`);
165
- }
166
- return manifest;
167
- }
168
-
169
- function installManifestTarget(root){
170
- return path.join(root, ".agents", "managed-install.json");
171
- }
172
-
173
- function copyInstallManifest(assetManifest, root){
174
- const target = installManifestTarget(root);
175
- fs.mkdirSync(path.dirname(target), { recursive: true });
176
- fs.copyFileSync(assetManifest, target);
177
- return target;
178
- }
179
-
180
- function applyManifestExecutableBits(root, manifest, mode){
181
- if (process.platform === "win32") return;
182
- const scopes = new Set(mode === "project" ? ["shared", "project"] : ["shared"]);
183
- if (safeProjectMutationRequired) {
184
- const mutations = [];
185
- for (const entry of manifest.entries) {
186
- if (!scopes.has(entry.scope) || typeof entry.path !== "string" || typeof entry.executable !== "boolean") continue;
187
- const target = path.join(root, ...entry.path.split("/"));
188
- const { relative } = projectRelativePath(root, target);
189
- mutations.push({
190
- path: relative.split(path.sep).join("/"),
191
- mode: entry.executable ? "755" : "644",
192
- });
193
- }
194
- runSafeProjectChmodBatch(root, mutations);
195
- return;
196
- }
197
- for (const entry of manifest.entries) {
198
- if (!scopes.has(entry.scope) || typeof entry.path !== "string" || typeof entry.executable !== "boolean") continue;
199
- const target = path.join(root, ...entry.path.split("/"));
200
- if (!exists(target) || fs.lstatSync(target).isSymbolicLink()) continue;
201
- const current = fs.statSync(target).mode & 0o777;
202
- const desired = entry.executable ? (current | 0o111) : (current & ~0o111);
203
- if (desired !== current) fs.chmodSync(target, desired);
204
- }
205
- }
206
-
207
- function installIntegrityStatus(root, mode, expectedVersion){
208
- const script = path.join(root, ".agents", "skills", "auto-coding-skill", "scripts", "install_integrity.py");
209
- if (!exists(script)) {
210
- return { ok: false, version: "", checked: 0, errors: ["managed integrity verifier is missing"] };
211
- }
212
- const result = spawnSync(
213
- runtimePython(),
214
- [script, "verify", "--repo", root, "--mode", mode, "--expected-version", expectedVersion, "--json"],
215
- { encoding: "utf8", stdio: "pipe" },
216
- );
217
- try {
218
- const parsed = JSON.parse(result.stdout || "{}");
219
- if (typeof parsed.ok === "boolean" && Array.isArray(parsed.errors)) return parsed;
220
- } catch {
221
- // Fall through to a deterministic diagnostic below.
222
- }
223
- const detail = String(result.stderr || result.stdout || result.error?.message || "integrity verifier failed").trim();
224
- return { ok: false, version: "", checked: 0, errors: [detail || "integrity verifier returned invalid output"] };
225
- }
226
-
227
- function requireInstallIntegrity(root, mode, expectedVersion){
228
- const result = installIntegrityStatus(root, mode, expectedVersion);
229
- if (!result.ok) die(`managed install integrity verification failed:\n- ${result.errors.join("\n- ")}`);
230
- return result;
231
- }
232
-
233
- function runEngineeringConvergence(project, skillRoot, write, installToken = "", transaction = null){
234
- if (transaction) requireInstalledTransactionIntegrity(project, transaction);
235
- const script = path.join(skillRoot, "scripts", "ap.py");
236
- const command = [script, "--repo", project, "project-converge", "--json"];
237
- if (write) command.push("--write");
238
- const result = spawnSync(runtimePython(), command, {
239
- encoding: "utf8",
240
- stdio: "pipe",
241
- env: installToken
242
- ? { ...process.env, AUTOCODING_INSTALL_TRANSACTION_TOKEN: installToken }
243
- : process.env,
244
- });
245
- if (result.status !== 0) {
246
- const detail = String(result.stderr || result.stdout || result.error?.message || "project convergence failed").trim();
247
- die(`unable to converge docs/ENGINEERING.md: ${detail}`);
248
- }
249
- try {
250
- return JSON.parse(result.stdout);
251
- } catch {
252
- die("project convergence returned invalid JSON");
253
- }
254
- }
255
-
256
- function runProjectConfigPrepare(project, skillRoot, write){
257
- const script = path.join(skillRoot, "scripts", "ap.py");
258
- const command = [script, "--repo", project, "project-config-prepare", "--json"];
259
- if (write) command.push("--write");
260
- const result = spawnSync(runtimePython(), command, { encoding: "utf8", stdio: "pipe" });
261
- if (result.status !== 0) {
262
- const detail = String(result.stderr || result.stdout || result.error?.message || "project configuration prepare failed").trim();
263
- die(`unable to prepare project configuration: ${detail}`);
264
- }
265
- try {
266
- const parsed = JSON.parse(result.stdout);
267
- if (
268
- typeof parsed?.finalize_required !== "boolean"
269
- || !/^[0-9a-f]{64}$/.test(String(parsed?.engineering_before_sha256 || ""))
270
- || !/^[0-9a-f]{64}$/.test(String(parsed?.overlay_sha256 || ""))
271
- || !/^[0-9a-f]{64}$/.test(String(parsed?.template_sha256 || ""))
272
- || !Array.isArray(parsed?.actions)
273
- ) throw new Error("unexpected prepare contract");
274
- return parsed;
275
- } catch {
276
- die("project configuration prepare returned invalid JSON");
277
- }
278
- }
279
-
280
- function runProjectConfigFinalize(project, skillRoot, prepared, write, installToken = "", transaction = null){
281
- if (transaction) requireInstalledTransactionIntegrity(project, transaction);
282
- const script = path.join(skillRoot, "scripts", "ap.py");
283
- const command = [
284
- script,
285
- "--repo", project,
286
- "project-config-finalize",
287
- "--engineering-sha256", prepared.engineering_before_sha256,
288
- "--overlay-sha256", prepared.overlay_sha256,
289
- "--template-sha256", prepared.template_sha256,
290
- "--json",
291
- ];
292
- if (write) command.push("--write");
293
- const result = spawnSync(runtimePython(), command, {
294
- encoding: "utf8",
295
- stdio: "pipe",
296
- env: installToken
297
- ? { ...process.env, AUTOCODING_INSTALL_TRANSACTION_TOKEN: installToken }
298
- : process.env,
299
- });
300
- if (result.status !== 0) {
301
- const detail = String(result.stderr || result.stdout || result.error?.message || "project configuration finalize failed").trim();
302
- die(`unable to finalize project configuration: ${detail}`);
303
- }
304
- try {
305
- const parsed = JSON.parse(result.stdout);
306
- if (!Array.isArray(parsed?.actions)) throw new Error("unexpected finalize contract");
307
- return parsed;
308
- } catch {
309
- die("project configuration finalize returned invalid JSON");
310
- }
311
- }
312
-
313
- function readEffectiveConfigStatus(project, skillRoot){
314
- const script = path.join(skillRoot, "scripts", "ap.py");
315
- const result = spawnSync(
316
- runtimePython(),
317
- [script, "--repo", project, "config-effective", "--json"],
318
- { encoding: "utf8", stdio: "pipe" },
319
- );
320
- if (result.status !== 0) {
321
- const detail = String(result.stderr || result.stdout || result.error?.message || "effective config check failed").trim();
322
- return { ok: false, error: detail || "effective config check failed", fields: {}, policy_issues: [] };
323
- }
324
- try {
325
- const parsed = JSON.parse(result.stdout);
326
- if (parsed?.schema !== "auto-coding-skill/effective-config-status/v1" || typeof parsed.fields !== "object") {
327
- throw new Error("unexpected schema");
328
- }
329
- return { ...parsed, ok: true };
330
- } catch {
331
- return { ok: false, error: "effective config check returned invalid JSON", fields: {}, policy_issues: [] };
332
- }
333
- }
334
-
335
- function runManagedScaffoldConvergence(project, skillRoot, group, write){
336
- const script = path.join(skillRoot, "scripts", "ap.py");
337
- const command = [script, "--repo", project, "managed-scaffold-converge", group, "--json"];
338
- if (write) command.push("--write");
339
- const result = spawnSync(runtimePython(), command, { encoding: "utf8", stdio: "pipe" });
340
- if (result.status !== 0) {
341
- const detail = String(result.stderr || result.stdout || result.error?.message || "managed scaffold convergence failed").trim();
342
- die(`unable to converge managed ${group} scaffold: ${detail}`);
343
- }
344
- try {
345
- return JSON.parse(result.stdout);
346
- } catch {
347
- die(`managed ${group} scaffold convergence returned invalid JSON`);
348
- }
349
- }
350
- function shouldSkip(name){
351
- return name === "__pycache__" || name === ".DS_Store" || /\.py[cod]$/i.test(name);
352
- }
353
-
354
- function copyDir(src, dst){
355
- fs.mkdirSync(dst, { recursive: true });
356
- for (const ent of fs.readdirSync(src, { withFileTypes: true })) {
357
- if (shouldSkip(ent.name)) continue;
358
- const s = path.join(src, ent.name);
359
- const d = path.join(dst, ent.name);
360
- if (ent.isDirectory()) copyDir(s, d);
361
- else fs.copyFileSync(s, d);
362
- }
363
- }
364
-
365
- const INSTALL_TRANSACTION_NAME = ".auto-coding-skill-install-transaction";
366
- const INSTALL_TRANSACTION_SCHEMA = 1;
367
- const INSTALL_TRANSACTION_OWNER_SCHEMA = 1;
368
- let trustedProjectFileHelper = "";
369
- let activeInstallTransactionToken = "";
370
- let safeProjectMutationRequired = false;
371
-
372
- function sha256File(file){
373
- return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
374
- }
375
-
376
- function realDirectory(directory, label){
377
- let metadata;
378
- try {
379
- metadata = fs.lstatSync(directory);
380
- } catch (error) {
381
- die(`${label} is unavailable: ${error.code || "read-error"}`);
382
- }
383
- if (!metadata.isDirectory() || metadata.isSymbolicLink()) die(`${label} must be a real directory`);
384
- }
385
-
386
- function regularFile(file, label){
387
- let metadata;
388
- try {
389
- metadata = fs.lstatSync(file);
390
- } catch (error) {
391
- die(`${label} is unavailable: ${error.code || "read-error"}`);
392
- }
393
- if (!metadata.isFile() || metadata.isSymbolicLink()) die(`${label} must be a regular non-symlink file`);
394
- }
395
-
396
- function canonicalProjectRoot(root){
397
- try {
398
- return fs.realpathSync(path.resolve(root));
399
- } catch (error) {
400
- die(`project root is unavailable: ${error.code || "realpath-error"}`);
401
- }
402
- }
403
-
404
- function projectDirectoryChain(root, relative, create = false){
405
- const canonicalRoot = canonicalProjectRoot(root);
406
- const parts = String(relative || "").split(/[\\/]+/).filter(Boolean);
407
- let current = canonicalRoot;
408
- realDirectory(current, "project root");
409
- for (const part of parts) {
410
- if (part === "." || part === "..") die(`unsafe project directory path: ${relative}`);
411
- current = path.join(current, part);
412
- let metadata;
413
- try {
414
- metadata = fs.lstatSync(current);
415
- } catch (error) {
416
- if (error.code !== "ENOENT" || !create) return null;
417
- fs.mkdirSync(current);
418
- metadata = fs.lstatSync(current);
419
- }
420
- if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
421
- die(`project directory chain contains a symlink, junction, or non-directory: ${relative}`);
422
- }
423
- let resolved;
424
- try {
425
- resolved = fs.realpathSync(current);
426
- } catch (error) {
427
- die(`project directory chain could not be verified: ${error.code || "realpath-error"}`);
428
- }
429
- const normalize = value => process.platform === "win32"
430
- ? path.normalize(value).toLowerCase()
431
- : path.normalize(value);
432
- if (normalize(resolved) !== normalize(current)) {
433
- die(`project directory chain contains a symlink or junction: ${relative}`);
434
- }
435
- }
436
- return current;
437
- }
438
-
439
- function lstatIfPresent(candidate){
440
- try {
441
- return fs.lstatSync(candidate);
442
- } catch (error) {
443
- if (error.code === "ENOENT") return null;
444
- die(`install transaction input is unavailable: ${error.code || "lstat-error"}`);
445
- }
446
- }
447
-
448
- function validateInstallTransactionInputs(root, assetSkill, assetManifest){
449
- root = canonicalProjectRoot(root);
450
- projectDirectoryChain(root, ".agents", false);
451
- projectDirectoryChain(root, path.join(".agents", "skills"), false);
452
- projectDirectoryChain(root, "docs", false);
453
- directorySha256(assetSkill);
454
- regularFile(assetManifest, "managed install source manifest");
455
-
456
- const skillDir = path.join(root, ".agents", "skills", "auto-coding-skill");
457
- const skillMetadata = lstatIfPresent(skillDir);
458
- if (skillMetadata) {
459
- if (!skillMetadata.isDirectory() || skillMetadata.isSymbolicLink()) {
460
- die(`installed Skill must be a real directory before convergence: ${root}`);
461
- }
462
- directorySha256(skillDir);
463
- }
464
- const manifest = installManifestTarget(root);
465
- if (lstatIfPresent(manifest)) regularFile(manifest, "installed managed manifest");
466
- const engineering = path.join(root, "docs", "ENGINEERING.md");
467
- if (lstatIfPresent(engineering)) regularFile(engineering, "managed ENGINEERING document");
468
- }
469
-
470
- function projectRelativePath(root, candidate){
471
- const lexicalRoot = path.resolve(root);
472
- const canonicalRoot = canonicalProjectRoot(root);
473
- const absolute = path.resolve(candidate);
474
- const relative = path.relative(lexicalRoot, absolute);
475
- if (!relative || relative === "." || relative.startsWith("..") || path.isAbsolute(relative)) {
476
- die(`unsafe project file target: ${candidate}`);
477
- }
478
- return { canonicalRoot, relative };
479
- }
480
-
481
- function validateProjectFileTarget(root, candidate, label){
482
- const { canonicalRoot, relative } = projectRelativePath(root, candidate);
483
- const parent = path.dirname(relative);
484
- if (parent !== "." && !projectDirectoryChain(canonicalRoot, parent, false)) return;
485
- const target = path.join(canonicalRoot, relative);
486
- const metadata = lstatIfPresent(target);
487
- if (metadata && (!metadata.isFile() || metadata.isSymbolicLink())) {
488
- die(`${label} must be a regular non-symlink file: ${relative}`);
489
- }
490
- }
491
-
492
- const ARCHIVE_TARGET_ATTEMPTS = 64;
493
-
494
- function selectProjectArchiveTarget(root, preferred, payload, options = {}){
495
- const lexicalRoot = path.resolve(root);
496
- const { relative } = projectRelativePath(lexicalRoot, preferred);
497
- const intended = Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload), "utf8");
498
- const legacyPayload = options.legacyDigestPayload === undefined
499
- ? intended
500
- : (Buffer.isBuffer(options.legacyDigestPayload)
501
- ? options.legacyDigestPayload
502
- : Buffer.from(String(options.legacyDigestPayload), "utf8"));
503
- const payloadDigest = crypto.createHash("sha256").update(intended).digest("hex");
504
- const legacyDigest = crypto.createHash("sha256").update(legacyPayload).digest("hex").slice(0, 12);
505
- const normalizedRelative = relative.split(path.sep).join("/");
506
- const pathDigest = crypto.createHash("sha256").update(normalizedRelative).digest("hex").slice(0, 12);
507
- const absolutePreferred = path.join(lexicalRoot, relative);
508
- const parsed = path.parse(absolutePreferred);
509
- const legacyCandidate = path.join(parsed.dir, `${parsed.name}-${legacyDigest}${parsed.ext}`);
510
- const compactStem = `.autocoding-archive-${pathDigest}-${payloadDigest}`;
511
- const candidates = [absolutePreferred];
512
- if (Buffer.byteLength(path.basename(legacyCandidate), "utf8") <= 240) candidates.push(legacyCandidate);
513
- candidates.push(path.join(parsed.dir, `${compactStem}${parsed.ext}`));
514
- for (let attempt = 2; attempt <= ARCHIVE_TARGET_ATTEMPTS; attempt += 1) {
515
- candidates.push(path.join(parsed.dir, `${compactStem}-${attempt}${parsed.ext}`));
516
- }
517
-
518
- const seen = new Set();
519
- for (const candidate of candidates) {
520
- const key = process.platform === "win32" ? path.normalize(candidate).toLowerCase() : path.normalize(candidate);
521
- if (seen.has(key)) continue;
522
- seen.add(key);
523
- validateProjectFileTarget(lexicalRoot, candidate, "project archive target");
524
- const metadata = lstatIfPresent(candidate);
525
- if (!metadata) return { path: candidate, archiveRequired: true };
526
- const existing = fs.readFileSync(candidate);
527
- if (existing.equals(intended)) return { path: candidate, archiveRequired: false };
528
- }
529
- die(
530
- "cannot allocate a collision-free project archive target without overwriting different content: "
531
- + normalizedRelative,
532
- );
533
- }
534
-
535
- function runSafeProjectFileMutation(root, candidate, operation, payload = null, mode = null){
536
- if (!safeProjectMutationRequired) return false;
537
- if (!trustedProjectFileHelper || !activeInstallTransactionToken) {
538
- die("project mutation requires the trusted source helper and active install transaction");
539
- }
540
- const { canonicalRoot, relative } = projectRelativePath(root, candidate);
541
- const command = [
542
- trustedProjectFileHelper,
543
- "--repo", canonicalRoot,
544
- "project-file-safe", operation,
545
- "--path", relative.split(path.sep).join("/"),
546
- "--json",
547
- ];
548
- if (mode !== null) command.push("--mode", mode.toString(8));
549
- const result = spawnSync(runtimePython(), command, {
550
- encoding: "utf8",
551
- stdio: ["pipe", "pipe", "pipe"],
552
- input: payload === null ? undefined : (Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload))),
553
- maxBuffer: 34 * 1024 * 1024,
554
- env: {
555
- ...process.env,
556
- AUTOCODING_INSTALL_TRANSACTION_TOKEN: activeInstallTransactionToken,
557
- },
558
- });
559
- if (result.status !== 0) {
560
- const detail = String(result.stderr || result.stdout || result.error?.message || "safe project mutation failed").trim();
561
- die(`trusted project mutation failed: ${detail}`);
562
- }
563
- return true;
564
- }
565
-
566
- function runSafeProjectChmodBatch(root, mutations){
567
- if (!safeProjectMutationRequired) return false;
568
- if (!trustedProjectFileHelper || !activeInstallTransactionToken) {
569
- die("project chmod batch requires the trusted source helper and active install transaction");
570
- }
571
- const canonicalRoot = canonicalProjectRoot(root);
572
- const result = spawnSync(runtimePython(), [
573
- trustedProjectFileHelper,
574
- "--repo", canonicalRoot,
575
- "project-file-safe", "chmod-batch",
576
- "--json",
577
- ], {
578
- encoding: "utf8",
579
- stdio: ["pipe", "pipe", "pipe"],
580
- input: Buffer.from(JSON.stringify(mutations), "utf8"),
581
- maxBuffer: 2 * 1024 * 1024,
582
- env: {
583
- ...process.env,
584
- AUTOCODING_INSTALL_TRANSACTION_TOKEN: activeInstallTransactionToken,
585
- },
586
- });
587
- if (result.status !== 0) {
588
- const detail = String(result.stderr || result.stdout || result.error?.message || "safe project chmod batch failed").trim();
589
- die(`trusted project chmod batch failed: ${detail}`);
590
- }
591
- return true;
592
- }
593
-
594
- function runInstallIoPhase(root, operation, transaction, state = null){
595
- if (!trustedProjectFileHelper) die("install I/O requires the trusted source helper");
596
- const command = [
597
- trustedProjectFileHelper,
598
- "--repo", canonicalProjectRoot(root),
599
- "install-io", operation,
600
- "--json",
601
- ];
602
- if (operation === "recover") {
603
- if (state?.old_skill_present) command.push("--old-skill-present");
604
- if (state?.old_manifest_present) command.push("--old-manifest-present");
605
- if (state?.old_engineering_present) command.push("--old-engineering-present");
606
- }
607
- const token = transaction?.token || "";
608
- const result = spawnSync(runtimePython(), command, {
609
- encoding: "utf8",
610
- stdio: "pipe",
611
- env: token
612
- ? { ...process.env, AUTOCODING_INSTALL_TRANSACTION_TOKEN: token }
613
- : process.env,
614
- });
615
- if (result.status !== 0) {
616
- const detail = String(result.stderr || result.stdout || result.error?.message || "install I/O phase failed").trim();
617
- die(`trusted install I/O ${operation} failed: ${detail}`);
618
- }
619
- }
620
-
621
- function atomicWriteProjectFile(root, candidate, payload, mode = null){
622
- if (runSafeProjectFileMutation(root, candidate, "write", payload, mode)) return;
623
- const { canonicalRoot, relative } = projectRelativePath(root, candidate);
624
- const parentRelative = path.dirname(relative);
625
- const parent = parentRelative === "."
626
- ? canonicalRoot
627
- : projectDirectoryChain(canonicalRoot, parentRelative, true);
628
- validateProjectFileTarget(canonicalRoot, path.join(canonicalRoot, relative), "managed project target");
629
- const target = path.join(canonicalRoot, relative);
630
- const temporary = path.join(parent, `.autocoding-${process.pid}-${crypto.randomUUID()}.tmp`);
631
- try {
632
- fs.writeFileSync(temporary, payload, mode === null ? undefined : { mode });
633
- if (mode !== null && process.platform !== "win32") fs.chmodSync(temporary, mode);
634
- try {
635
- fs.renameSync(temporary, target);
636
- } catch (error) {
637
- if (
638
- process.platform !== "win32"
639
- || !["EEXIST", "EPERM", "EACCES"].includes(String(error.code || ""))
640
- ) throw error;
641
- validateProjectFileTarget(canonicalRoot, target, "managed project target");
642
- fs.rmSync(target, { force: true });
643
- fs.renameSync(temporary, target);
644
- }
645
- } finally {
646
- try { fs.rmSync(temporary, { force: true }); } catch {}
647
- }
648
- }
649
-
650
- function atomicCreateProjectFile(root, candidate, payload, mode = null){
651
- if (runSafeProjectFileMutation(root, candidate, "create", payload, mode)) return;
652
- const { canonicalRoot, relative } = projectRelativePath(root, candidate);
653
- const parentRelative = path.dirname(relative);
654
- const parent = parentRelative === "."
655
- ? canonicalRoot
656
- : projectDirectoryChain(canonicalRoot, parentRelative, true);
657
- validateProjectFileTarget(canonicalRoot, path.join(canonicalRoot, relative), "create-only project target");
658
- const target = path.join(canonicalRoot, relative);
659
- if (lstatIfPresent(target)) die(`project file appeared before create-only publish: ${relative}`);
660
- const temporary = path.join(parent, `.autocoding-${process.pid}-${crypto.randomUUID()}.tmp`);
661
- let descriptor;
662
- try {
663
- descriptor = fs.openSync(temporary, "wx", mode === null ? 0o644 : mode);
664
- fs.writeFileSync(descriptor, payload);
665
- fs.fsyncSync(descriptor);
666
- fs.closeSync(descriptor);
667
- descriptor = undefined;
668
- const temporaryMetadata = fs.lstatSync(temporary);
669
- if (!temporaryMetadata.isFile() || temporaryMetadata.isSymbolicLink()) {
670
- die(`temporary create-only project file is unsafe: ${relative}`);
671
- }
672
- try {
673
- fs.linkSync(temporary, target);
674
- } catch (error) {
675
- if (error.code === "EEXIST") die(`project file appeared before create-only publish: ${relative}`);
676
- throw error;
677
- }
678
- const published = fs.lstatSync(target);
679
- if (
680
- !published.isFile()
681
- || published.isSymbolicLink()
682
- || published.dev !== temporaryMetadata.dev
683
- || published.ino !== temporaryMetadata.ino
684
- ) die(`project file changed during create-only publish: ${relative}`);
685
- if (mode !== null && process.platform !== "win32") fs.chmodSync(target, mode);
686
- } finally {
687
- if (descriptor !== undefined) {
688
- try { fs.closeSync(descriptor); } catch {}
689
- }
690
- try { fs.unlinkSync(temporary); } catch {}
691
- }
692
- }
693
-
694
- function validateProjectManagedTargets(root, assetAgents){
695
- root = canonicalProjectRoot(root);
696
- for (const directory of [
697
- path.join(".agents", "agents"),
698
- path.join("docs", "tools", "autopipeline"),
699
- path.join("docs", "archive", "workflow"),
700
- ]) projectDirectoryChain(root, directory, false);
701
- validateProjectFileTarget(root, path.join(root, "AGENTS.md"), "root AGENTS.md");
702
- validateProjectFileTarget(
703
- root,
704
- path.join(root, "docs", "tools", "autopipeline", "ap.py"),
705
- "project launcher",
706
- );
707
- for (const relative of listFiles(assetAgents)) {
708
- validateProjectFileTarget(
709
- root,
710
- path.join(root, ".agents", "agents", relative),
711
- "managed agent",
712
- );
713
- }
714
- }
715
-
716
- function copyDirStrict(src, dst){
717
- realDirectory(src, "install transaction source directory");
718
- fs.mkdirSync(dst, { recursive: true });
719
- realDirectory(dst, "install transaction destination directory");
720
- for (const ent of fs.readdirSync(src, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
721
- if (shouldSkip(ent.name)) continue;
722
- if (ent.isSymbolicLink() || (!ent.isDirectory() && !ent.isFile())) {
723
- die(`install transaction refuses a non-regular entry: ${path.join(src, ent.name)}`);
724
- }
725
- const source = path.join(src, ent.name);
726
- const target = path.join(dst, ent.name);
727
- if (ent.isDirectory()) copyDirStrict(source, target);
728
- else fs.copyFileSync(source, target);
729
- }
730
- }
731
-
732
- function directorySha256(root){
733
- realDirectory(root, "install transaction directory");
734
- const digest = crypto.createHash("sha256");
735
- const addRecord = record => {
736
- const payload = Buffer.from(JSON.stringify(record), "utf8");
737
- const length = Buffer.alloc(8);
738
- length.writeBigUInt64BE(BigInt(payload.length));
739
- digest.update(length);
740
- digest.update(payload);
741
- };
742
- const visit = (directory, prefix = "") => {
743
- for (const ent of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
744
- if (shouldSkip(ent.name)) continue;
745
- const relative = prefix ? `${prefix}/${ent.name}` : ent.name;
746
- const candidate = path.join(directory, ent.name);
747
- if (ent.isSymbolicLink() || (!ent.isDirectory() && !ent.isFile())) {
748
- die(`install transaction refuses a non-regular entry: ${candidate}`);
749
- }
750
- if (ent.isDirectory()) {
751
- addRecord({ type: "directory", path: relative });
752
- visit(candidate, relative);
753
- } else {
754
- const payload = fs.readFileSync(candidate);
755
- const mode = fs.statSync(candidate).mode;
756
- addRecord({
757
- type: "file",
758
- path: relative,
759
- size: payload.length,
760
- sha256: crypto.createHash("sha256").update(payload).digest("hex"),
761
- executable: process.platform === "win32" ? false : Boolean(mode & 0o111),
762
- });
763
- }
764
- }
765
- };
766
- visit(root);
767
- return digest.digest("hex");
768
- }
769
-
770
- function atomicCopyFile(source, target){
771
- regularFile(source, "install transaction source file");
772
- fs.mkdirSync(path.dirname(target), { recursive: true });
773
- const temporary = `${target}.autocoding-${process.pid}-${crypto.randomUUID()}.tmp`;
774
- try {
775
- fs.copyFileSync(source, temporary);
776
- if (process.platform !== "win32") fs.chmodSync(temporary, fs.statSync(source).mode & 0o777);
777
- fs.renameSync(temporary, target);
778
- } catch (error) {
779
- try { fs.rmSync(temporary, { force: true }); } catch {}
780
- if (
781
- process.platform === "win32"
782
- && ["EEXIST", "EPERM", "EACCES"].includes(String(error.code || ""))
783
- && exists(target)
784
- ) {
785
- fs.rmSync(target, { force: true });
786
- fs.copyFileSync(source, target);
787
- return;
788
- }
789
- throw error;
790
- }
791
- }
792
-
793
- function installTransactionPaths(root){
794
- root = canonicalProjectRoot(root);
795
- const agentsRoot = path.join(root, ".agents");
796
- const directory = path.join(agentsRoot, INSTALL_TRANSACTION_NAME);
797
- return {
798
- root,
799
- agentsRoot,
800
- directory,
801
- owner: path.join(directory, "owner.json"),
802
- state: path.join(directory, "state.json"),
803
- newSkill: path.join(directory, "new-skill"),
804
- newManifest: path.join(directory, "new-manifest.json"),
805
- oldSkill: path.join(directory, "old-skill"),
806
- oldManifest: path.join(directory, "old-manifest.json"),
807
- oldEngineering: path.join(directory, "old-ENGINEERING.md"),
808
- };
809
- }
810
-
811
- function writeInstallTransactionOwner(transaction){
812
- const tokenSha256 = crypto.createHash("sha256").update(transaction.token).digest("hex");
813
- const owner = {
814
- schema: INSTALL_TRANSACTION_OWNER_SCHEMA,
815
- pid: process.pid,
816
- started_at: new Date().toISOString(),
817
- token_sha256: tokenSha256,
818
- };
819
- const descriptor = fs.openSync(transaction.owner, "wx", 0o600);
820
- try {
821
- fs.writeFileSync(descriptor, `${JSON.stringify(owner)}\n`, "utf8");
822
- fs.fsyncSync(descriptor);
823
- } finally {
824
- fs.closeSync(descriptor);
825
- }
826
- transaction.ownerPid = owner.pid;
827
- transaction.ownerTokenSha256 = owner.token_sha256;
828
- return owner;
829
- }
830
-
831
- function publishInstallTransactionOwner(transaction){
832
- const claimDirectory = path.join(
833
- transaction.agentsRoot,
834
- `${INSTALL_TRANSACTION_NAME}.claim-${process.pid}-${crypto.randomUUID()}`,
835
- );
836
- fs.mkdirSync(claimDirectory);
837
- const claim = {
838
- ...transaction,
839
- directory: claimDirectory,
840
- owner: path.join(claimDirectory, "owner.json"),
841
- };
842
- try {
843
- const owner = writeInstallTransactionOwner(claim);
844
- fs.renameSync(claimDirectory, transaction.directory);
845
- transaction.ownerPid = owner.pid;
846
- transaction.ownerTokenSha256 = owner.token_sha256;
847
- return owner;
848
- } catch (error) {
849
- rmrf(claimDirectory);
850
- if (lstatIfPresent(transaction.directory)) {
851
- die("another auto-coding-skill installer claimed this project; no install writes were made");
852
- }
853
- throw error;
854
- }
855
- }
856
-
857
- function readInstallTransactionOwner(transaction){
858
- regularFile(transaction.owner, "install transaction owner lease");
859
- let owner;
860
- try {
861
- const payload = fs.readFileSync(transaction.owner);
862
- if (payload.length > 4096) throw new Error("oversized owner lease");
863
- owner = JSON.parse(payload.toString("utf8"));
864
- } catch {
865
- die("install transaction has an invalid owner lease; no recovery writes were made");
866
- }
867
- if (
868
- owner?.schema !== INSTALL_TRANSACTION_OWNER_SCHEMA
869
- || !Number.isSafeInteger(owner.pid)
870
- || owner.pid <= 0
871
- || typeof owner.started_at !== "string"
872
- || !/^[0-9a-f]{64}$/.test(String(owner.token_sha256 || ""))
873
- ) die("install transaction has an unsupported owner lease; no recovery writes were made");
874
- return owner;
875
- }
876
-
877
- function installTransactionOwnerIsAlive(owner){
878
- try {
879
- process.kill(owner.pid, 0);
880
- return true;
881
- } catch (error) {
882
- if (error?.code === "ESRCH") return false;
883
- if (error?.code === "EPERM") return true;
884
- die(`cannot verify install transaction owner liveness: ${error?.code || "process-error"}`);
885
- }
886
- }
887
-
888
- function requireInstallTransactionOwnerStopped(transaction){
889
- const owner = readInstallTransactionOwner(transaction);
890
- if (installTransactionOwnerIsAlive(owner)) {
891
- die(
892
- `auto-coding-skill install transaction is active under owner pid ${owner.pid}; `
893
- + "no recovery writes were made",
894
- );
895
- }
896
- return owner;
897
- }
898
-
899
- function installTransactionPending(root){
900
- const transaction = installTransactionPaths(root);
901
- if (!projectDirectoryChain(transaction.root, ".agents", false)) return false;
902
- const metadata = lstatIfPresent(transaction.directory);
903
- if (!metadata) return false;
904
- if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
905
- die("auto-coding-skill install transaction path must be a real directory");
906
- }
907
- return true;
908
- }
909
-
910
- function readInstallTransactionState(transaction){
911
- const owner = readInstallTransactionOwner(transaction);
912
- regularFile(transaction.state, "install transaction state");
913
- let state;
914
- try {
915
- const payload = fs.readFileSync(transaction.state);
916
- if (payload.length > 64 * 1024) throw new Error("oversized state");
917
- state = JSON.parse(payload.toString("utf8"));
918
- } catch {
919
- die("interrupted install transaction has an invalid state file; no recovery writes were made");
920
- }
921
- const validHash = value => /^[0-9a-f]{64}$/.test(String(value || ""));
922
- if (
923
- state?.schema !== INSTALL_TRANSACTION_SCHEMA
924
- || typeof state.old_skill_present !== "boolean"
925
- || typeof state.old_manifest_present !== "boolean"
926
- || typeof state.old_engineering_present !== "boolean"
927
- || state.owner_pid !== owner.pid
928
- || state.owner_token_sha256 !== owner.token_sha256
929
- || (state.old_skill_present && !validHash(state.old_skill_sha256))
930
- || (state.old_manifest_present && !validHash(state.old_manifest_sha256))
931
- || (state.old_engineering_present && !validHash(state.old_engineering_sha256))
932
- || !validHash(state.staged_skill_sha256)
933
- || !validHash(state.staged_manifest_sha256)
934
- || !validHash(state.internal_token_sha256)
935
- ) die("interrupted install transaction has an unsupported state contract; no recovery writes were made");
936
- return state;
937
- }
938
-
939
- function requireActiveInstallTransactionBinding(transaction, state){
940
- const expectedTokenSha256 = crypto.createHash("sha256").update(transaction.token || "").digest("hex");
941
- if (
942
- transaction.ownerPid !== process.pid
943
- || state.owner_pid !== process.pid
944
- || transaction.ownerTokenSha256 !== expectedTokenSha256
945
- || state.owner_token_sha256 !== expectedTokenSha256
946
- || state.internal_token_sha256 !== expectedTokenSha256
947
- || state.staged_skill_sha256 !== transaction.stagedSkillSha256
948
- || state.staged_manifest_sha256 !== transaction.stagedManifestSha256
949
- ) die("active install transaction binding changed before managed runtime execution");
950
- }
951
-
952
- function requireStagedInstallIntegrity(transaction){
953
- const state = readInstallTransactionState(transaction);
954
- requireActiveInstallTransactionBinding(transaction, state);
955
- realDirectory(transaction.newSkill, "staged install Skill");
956
- regularFile(transaction.newManifest, "staged install manifest");
957
- if (directorySha256(transaction.newSkill) !== state.staged_skill_sha256) {
958
- die("staged Skill failed its transaction identity check before install");
959
- }
960
- if (sha256File(transaction.newManifest) !== state.staged_manifest_sha256) {
961
- die("staged manifest failed its transaction identity check before install");
962
- }
963
- return state;
964
- }
965
-
966
- function requireInstalledTransactionIntegrity(root, transaction){
967
- const state = readInstallTransactionState(transaction);
968
- requireActiveInstallTransactionBinding(transaction, state);
969
- const canonicalRoot = transaction.root || canonicalProjectRoot(root);
970
- const skillDir = path.join(canonicalRoot, ".agents", "skills", "auto-coding-skill");
971
- const manifest = installManifestTarget(canonicalRoot);
972
- realDirectory(skillDir, "installed transaction Skill");
973
- regularFile(manifest, "installed transaction manifest");
974
- if (directorySha256(skillDir) !== state.staged_skill_sha256) {
975
- die("installed Skill changed before the transaction runtime could execute");
976
- }
977
- if (sha256File(manifest) !== state.staged_manifest_sha256) {
978
- die("installed manifest changed before the transaction runtime could execute");
979
- }
980
- return state;
981
- }
982
-
983
- function completeInstallTransaction(root, transaction){
984
- if (!exists(transaction.directory)) return;
985
- runInstallIoPhase(transaction.root || root, "complete", transaction);
986
- if (transaction.token && activeInstallTransactionToken === transaction.token) {
987
- activeInstallTransactionToken = "";
988
- }
989
- }
990
-
991
- function recoverInstallTransaction(root, write = true){
992
- const transaction = installTransactionPaths(root);
993
- if (!projectDirectoryChain(transaction.root, ".agents", false)) return false;
994
- if (!exists(transaction.directory)) return false;
995
- realDirectory(transaction.directory, "auto-coding-skill install transaction");
996
- requireInstallTransactionOwnerStopped(transaction);
997
- if (!exists(transaction.state)) {
998
- // Canonical paths are never changed before state.json is durable.
999
- if (!write) return true;
1000
- completeInstallTransaction(root, transaction);
1001
- return true;
1002
- }
1003
- const state = readInstallTransactionState(transaction);
1004
-
1005
- // Validate every backup before touching any canonical path. The backups are
1006
- // copied, never moved, so recovery itself can be safely retried.
1007
- if (state.old_skill_present) {
1008
- realDirectory(transaction.oldSkill, "install transaction old Skill backup");
1009
- if (directorySha256(transaction.oldSkill) !== state.old_skill_sha256) {
1010
- die("interrupted install transaction old Skill backup failed its identity check");
1011
- }
1012
- }
1013
- if (state.old_manifest_present) {
1014
- regularFile(transaction.oldManifest, "install transaction old manifest backup");
1015
- if (sha256File(transaction.oldManifest) !== state.old_manifest_sha256) {
1016
- die("interrupted install transaction old manifest backup failed its identity check");
1017
- }
1018
- }
1019
- if (state.old_engineering_present) {
1020
- regularFile(transaction.oldEngineering, "install transaction old ENGINEERING backup");
1021
- if (sha256File(transaction.oldEngineering) !== state.old_engineering_sha256) {
1022
- die("interrupted install transaction old ENGINEERING backup failed its identity check");
1023
- }
1024
- }
1025
-
1026
- if (!write) return true;
1027
-
1028
- runInstallIoPhase(transaction.root, "recover", transaction, state);
1029
- const skillDir = path.join(transaction.root, ".agents", "skills", "auto-coding-skill");
1030
- if (state.old_skill_present && directorySha256(skillDir) !== state.old_skill_sha256) {
1031
- die("restored Skill backup failed verification");
1032
- }
1033
- const manifest = installManifestTarget(transaction.root);
1034
- if (state.old_manifest_present && sha256File(manifest) !== state.old_manifest_sha256) {
1035
- die("restored manifest backup failed verification");
1036
- }
1037
- const engineering = path.join(transaction.root, "docs", "ENGINEERING.md");
1038
- if (state.old_engineering_present && sha256File(engineering) !== state.old_engineering_sha256) {
1039
- die("restored ENGINEERING backup failed verification");
1040
- }
1041
- completeInstallTransaction(root, transaction);
1042
- return true;
1043
- }
1044
-
1045
- function beginInstallTransaction(root, assetSkill, assetManifest, prepared){
1046
- recoverInstallTransaction(root, true);
1047
- const transaction = installTransactionPaths(root);
1048
- transaction.token = crypto.randomBytes(32).toString("hex");
1049
- activeInstallTransactionToken = transaction.token;
1050
- projectDirectoryChain(transaction.root, ".agents", true);
1051
- projectDirectoryChain(transaction.root, path.join(".agents", "skills"), false);
1052
- projectDirectoryChain(transaction.root, "docs", false);
1053
- publishInstallTransactionOwner(transaction);
1054
- copyDirStrict(assetSkill, transaction.newSkill);
1055
- const stagedSkillSha256 = directorySha256(transaction.newSkill);
1056
- if (stagedSkillSha256 !== directorySha256(assetSkill)) {
1057
- die("staged Skill copy failed its identity check before install");
1058
- }
1059
- fs.copyFileSync(assetManifest, transaction.newManifest);
1060
- const stagedManifestSha256 = sha256File(transaction.newManifest);
1061
- if (stagedManifestSha256 !== sha256File(assetManifest)) {
1062
- die("staged manifest copy failed its identity check before install");
1063
- }
1064
- transaction.stagedSkillSha256 = stagedSkillSha256;
1065
- transaction.stagedManifestSha256 = stagedManifestSha256;
1066
-
1067
- const skillDir = path.join(transaction.root, ".agents", "skills", "auto-coding-skill");
1068
- const manifest = installManifestTarget(transaction.root);
1069
- const engineering = path.join(transaction.root, "docs", "ENGINEERING.md");
1070
- const state = {
1071
- schema: INSTALL_TRANSACTION_SCHEMA,
1072
- old_skill_present: exists(skillDir),
1073
- old_manifest_present: exists(manifest),
1074
- old_engineering_present: exists(engineering),
1075
- owner_pid: transaction.ownerPid,
1076
- owner_token_sha256: transaction.ownerTokenSha256,
1077
- old_skill_sha256: "",
1078
- old_manifest_sha256: "",
1079
- old_engineering_sha256: "",
1080
- staged_skill_sha256: stagedSkillSha256,
1081
- staged_manifest_sha256: stagedManifestSha256,
1082
- prepared_engineering_sha256: prepared.engineering_before_sha256,
1083
- prepared_overlay_sha256: prepared.overlay_sha256,
1084
- target_template_sha256: prepared.template_sha256,
1085
- internal_token_sha256: crypto.createHash("sha256").update(transaction.token).digest("hex"),
1086
- };
1087
- if (state.old_skill_present) {
1088
- copyDirStrict(skillDir, transaction.oldSkill);
1089
- state.old_skill_sha256 = directorySha256(transaction.oldSkill);
1090
- }
1091
- if (state.old_manifest_present) {
1092
- regularFile(manifest, "installed managed manifest");
1093
- fs.copyFileSync(manifest, transaction.oldManifest);
1094
- state.old_manifest_sha256 = sha256File(transaction.oldManifest);
1095
- }
1096
- if (state.old_engineering_present) {
1097
- regularFile(engineering, "managed ENGINEERING document");
1098
- fs.copyFileSync(engineering, transaction.oldEngineering);
1099
- state.old_engineering_sha256 = sha256File(transaction.oldEngineering);
1100
- if (process.platform !== "win32") fs.chmodSync(transaction.oldEngineering, 0o600);
1101
- }
1102
- const stateDescriptor = fs.openSync(transaction.state, "wx", 0o600);
1103
- try {
1104
- fs.writeFileSync(stateDescriptor, `${JSON.stringify(state)}\n`, "utf8");
1105
- fs.fsyncSync(stateDescriptor);
1106
- } finally {
1107
- fs.closeSync(stateDescriptor);
1108
- }
1109
- return transaction;
1110
- }
1111
-
1112
- function switchInstallTransaction(root, transaction){
1113
- requireStagedInstallIntegrity(transaction);
1114
- runInstallIoPhase(transaction.root || root, "switch", transaction);
1115
- requireInstalledTransactionIntegrity(root, transaction);
1116
- }
1117
-
1118
- function injectInstallFault(phase){
1119
- if (process.env.AUTOCODING_TEST_HOLD_PHASE === phase) {
1120
- const requested = Number(process.env.AUTOCODING_TEST_HOLD_MILLISECONDS || "0");
1121
- if (!Number.isFinite(requested) || requested <= 0 || requested > 15000) {
1122
- throw new Error("AUTOCODING_TEST_HOLD_MILLISECONDS must be between 1 and 15000");
1123
- }
1124
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, requested);
1125
- }
1126
- if (process.env.AUTOCODING_TEST_FAIL_PHASE === phase) {
1127
- throw new Error(`injected auto-coding-skill install fault: ${phase}`);
1128
- }
1129
- }
1130
-
1131
- function listFiles(root, base = root){
1132
- if (!exists(root)) return [];
7
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
8
+ const assetsRoot = path.join(packageRoot, "cli", "assets");
9
+ const assetSkill = path.join(assetsRoot, "skill");
10
+ const assetAgents = path.join(assetSkill, "data", "templates", "bridges", "AGENTS.md");
11
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
12
+ const managedDocs = [
13
+ ["ENVIRONMENT.md", "docs/ENVIRONMENT.md"],
14
+ ];
15
+ const projectDocs = [
16
+ ["PROJECT.md", "docs/PROJECT.md"],
17
+ ["architecture/.gitkeep", "docs/architecture/.gitkeep"],
18
+ ["design/.gitkeep", "docs/design/.gitkeep"],
19
+ ["interfaces/.gitkeep", "docs/interfaces/.gitkeep"],
20
+ ["deployment/.gitkeep", "docs/deployment/.gitkeep"],
21
+ ["product/.gitkeep", "docs/product/.gitkeep"],
22
+ ];
23
+ const bootstrapDocs = [...managedDocs, ...projectDocs];
24
+
25
+ function fail(message) { console.error(`\n[autocoding] ERROR: ${message}\n`); process.exit(1); }
26
+ function exists(file) { try { fs.accessSync(file); return true; } catch { return false; } }
27
+ function sha256(file) { return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); }
28
+ function toJson(value, json) { if (json) console.log(JSON.stringify(value, null, 2)); else console.log(value); }
29
+ function mkdirFor(file) { fs.mkdirSync(path.dirname(file), { recursive: true }); }
30
+ function copyFile(source, target) { mkdirFor(target); fs.copyFileSync(source, target); }
31
+
32
+ function listFiles(root, base = root) {
1133
33
  const out = [];
1134
- for (const ent of fs.readdirSync(root, { withFileTypes: true })) {
1135
- if (shouldSkip(ent.name)) continue;
1136
- const p = path.join(root, ent.name);
1137
- if (ent.isSymbolicLink() || (!ent.isDirectory() && !ent.isFile())) {
1138
- die(`refusing a symlink, junction, or non-regular managed path: ${p}`);
1139
- }
1140
- if (ent.isDirectory()) out.push(...listFiles(p, base));
1141
- else out.push(path.relative(base, p));
34
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
35
+ if (entry.name === ".DS_Store" || entry.name === "__pycache__") continue;
36
+ const file = path.join(root, entry.name);
37
+ if (entry.isDirectory()) out.push(...listFiles(file, base));
38
+ else out.push(path.relative(base, file).split(path.sep).join("/"));
1142
39
  }
1143
40
  return out.sort();
1144
41
  }
1145
42
 
1146
- function compareDirs(src, dst, options = {}){
1147
- const includeExtra = options.includeExtra ?? true;
1148
- const diffs = [];
1149
- const srcFiles = listFiles(src);
1150
- const dstFiles = listFiles(dst);
1151
- const srcSet = new Set(srcFiles);
1152
- const dstSet = new Set(dstFiles);
1153
- for (const rel of srcFiles) {
1154
- if (!dstSet.has(rel)) {
1155
- diffs.push({ path: rel, status: "missing" });
1156
- continue;
1157
- }
1158
- const srcBuf = fs.readFileSync(path.join(src, rel));
1159
- const dstBuf = fs.readFileSync(path.join(dst, rel));
1160
- if (!srcBuf.equals(dstBuf)) diffs.push({ path: rel, status: "stale" });
1161
- }
1162
- if (includeExtra) {
1163
- for (const rel of dstFiles) {
1164
- if (!srcSet.has(rel)) diffs.push({ path: rel, status: "extra" });
1165
- }
1166
- }
1167
- return diffs;
1168
- }
1169
-
1170
- const CORE_DOCS = [];
1171
-
1172
- function isEscapedAt(text, index){
1173
- let slashes = 0;
1174
- for (let i = index - 1; i >= 0 && text[i] === "\\"; i -= 1) slashes += 1;
1175
- return slashes % 2 === 1;
1176
- }
1177
-
1178
- function nextMultilineState(line, initialState){
1179
- let state = initialState;
1180
- let quote = "";
1181
- for (let i = 0; i < line.length;) {
1182
- if (state) {
1183
- const close = line.indexOf(state, i);
1184
- if (close < 0) return state;
1185
- if (state === '"""' && isEscapedAt(line, close)) {
1186
- i = close + state.length;
1187
- continue;
1188
- }
1189
- state = "";
1190
- i = close + 3;
1191
- continue;
1192
- }
1193
- if (quote) {
1194
- if (line[i] === quote && (quote === "'" || !isEscapedAt(line, i))) quote = "";
1195
- i += 1;
1196
- continue;
1197
- }
1198
- if (line[i] === "#") return state;
1199
- if (line.startsWith('"""', i) || line.startsWith("'''", i)) {
1200
- state = line.slice(i, i + 3);
1201
- i += 3;
1202
- continue;
1203
- }
1204
- if (line[i] === '"' || line[i] === "'") quote = line[i];
1205
- i += 1;
1206
- }
1207
- return state;
1208
- }
1209
-
1210
- function parseTomlStringValue(raw){
1211
- const value = raw.trimStart();
1212
- if (!value || (value[0] !== '"' && value[0] !== "'")) {
1213
- return { valid: false, error: "model must be a TOML string" };
1214
- }
1215
- const quote = value[0];
1216
- let decoded = "";
1217
- let end = -1;
1218
- for (let i = 1; i < value.length; i += 1) {
1219
- const ch = value[i];
1220
- if (ch === quote) {
1221
- end = i;
1222
- break;
1223
- }
1224
- if (quote === "'" || ch !== "\\") {
1225
- if (ch.charCodeAt(0) < 0x20) return { valid: false, error: "model contains a control character" };
1226
- decoded += ch;
1227
- continue;
1228
- }
1229
- i += 1;
1230
- if (i >= value.length) return { valid: false, error: "model has an incomplete escape" };
1231
- const escaped = value[i];
1232
- const simpleEscapes = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" };
1233
- if (Object.hasOwn(simpleEscapes, escaped)) {
1234
- decoded += simpleEscapes[escaped];
1235
- continue;
1236
- }
1237
- if (escaped === "u" || escaped === "U") {
1238
- const length = escaped === "u" ? 4 : 8;
1239
- const hex = value.slice(i + 1, i + 1 + length);
1240
- if (hex.length !== length || !/^[0-9A-Fa-f]+$/.test(hex)) {
1241
- return { valid: false, error: `model has an invalid \\${escaped} escape` };
1242
- }
1243
- const codepoint = Number.parseInt(hex, 16);
1244
- if (codepoint > 0x10ffff || (codepoint >= 0xd800 && codepoint <= 0xdfff)) {
1245
- return { valid: false, error: "model has an invalid Unicode codepoint" };
1246
- }
1247
- decoded += String.fromCodePoint(codepoint);
1248
- i += length;
1249
- continue;
1250
- }
1251
- return { valid: false, error: `model has an unsupported escape \\${escaped}` };
1252
- }
1253
- if (end < 0) return { valid: false, error: "model string is not terminated" };
1254
- const trailing = value.slice(end + 1).trimStart();
1255
- if (trailing && !trailing.startsWith("#")) {
1256
- return { valid: false, error: "model must contain only one TOML string value" };
1257
- }
1258
- if (!decoded.trim()) return { valid: false, error: "model must be a non-empty string" };
1259
- return { valid: true, value: decoded };
43
+ function copyTree(source, target) {
44
+ for (const relative of listFiles(source)) copyFile(path.join(source, relative), path.join(target, relative));
1260
45
  }
1261
46
 
1262
- function inspectTopLevelModel(text){
1263
- const lines = text.replace(/\r\n/g, "\n").split("\n");
1264
- const matches = [];
1265
- let multiline = "";
1266
- let inTable = false;
1267
- for (let index = 0; index < lines.length; index += 1) {
1268
- const line = lines[index];
1269
- if (!multiline) {
1270
- const trimmed = line.trimStart();
1271
- if (trimmed.startsWith("[") && !trimmed.startsWith("[#")) inTable = true;
1272
- if (!inTable) {
1273
- const match = line.match(/^\s*(?:model|"model"|'model')\s*=\s*(.*)$/);
1274
- if (match) {
1275
- const parsed = parseTomlStringValue(match[1]);
1276
- matches.push({ lineIndex: index, rawLine: line, ...parsed });
1277
- }
1278
- }
1279
- }
1280
- multiline = nextMultilineState(line, multiline);
1281
- }
1282
- if (matches.length > 1) {
1283
- return { valid: false, error: "model is defined more than once", matches };
47
+ function parseArgs(argv) {
48
+ const [,, rawCommand, ...rest] = argv;
49
+ const args = { command: (!rawCommand || rawCommand === "-h" || rawCommand === "--help") ? "help" : rawCommand, dest: null, projects: [], json: false };
50
+ for (let index = 0; index < rest.length; index += 1) {
51
+ const value = rest[index];
52
+ if (value === "--dest") args.dest = rest[++index] || fail("--dest requires a path");
53
+ else if (value === "--projects") args.projects.push(...(rest[++index] || fail("--projects requires paths")).split(",").filter(Boolean));
54
+ else if (value === "--json") args.json = true;
55
+ else if (value === "-h" || value === "--help") args.command = "help";
56
+ else if (value.startsWith("--")) fail(`unknown argument: ${value}`);
57
+ else args.projects.push(value);
1284
58
  }
1285
- if (!matches.length) return { valid: true, present: false, matches };
1286
- const model = matches[0];
1287
- if (!model.valid) return { valid: false, error: model.error, matches };
1288
- return { valid: true, present: true, value: model.value, rawLine: model.rawLine, lineIndex: model.lineIndex, matches };
1289
- }
1290
-
1291
- function normalizeManagedAgent(text, modelInfo = inspectTopLevelModel(text)){
1292
- const lines = text.replace(/\r\n/g, "\n").split("\n");
1293
- if (modelInfo.valid && modelInfo.present) lines.splice(modelInfo.lineIndex, 1);
1294
- return lines.join("\n");
1295
- }
1296
-
1297
- function renderManagedAgent(templateText, existingText, resetModel){
1298
- const existingModel = inspectTopLevelModel(existingText || "");
1299
- const modelLine = !resetModel && existingModel.valid && existingModel.present ? existingModel.rawLine : "";
1300
- let rendered = normalizeManagedAgent(templateText);
1301
- if (!modelLine) return rendered;
1302
- const lines = rendered.split("\n");
1303
- const descriptionIndex = lines.findIndex(line => line.startsWith("description = "));
1304
- lines.splice(descriptionIndex >= 0 ? descriptionIndex + 1 : 0, 0, modelLine);
1305
- return lines.join("\n");
1306
- }
1307
-
1308
- function compareManagedAgents(assetAgents, agentsDir){
1309
- const diffs = [];
1310
- const bindings = [];
1311
- for (const rel of listFiles(assetAgents)) {
1312
- const src = path.join(assetAgents, rel);
1313
- const dst = path.join(agentsDir, rel);
1314
- if (!exists(dst)) {
1315
- diffs.push({ path: rel, status: "missing" });
1316
- bindings.push({ agent: rel, model: "inherit" });
1317
- continue;
1318
- }
1319
- const srcText = fs.readFileSync(src, "utf8");
1320
- const dstText = fs.readFileSync(dst, "utf8");
1321
- const srcModel = inspectTopLevelModel(srcText);
1322
- const dstModel = inspectTopLevelModel(dstText);
1323
- if (!srcModel.valid) throw new Error(`invalid managed agent template ${rel}: ${srcModel.error}`);
1324
- if (!dstModel.valid) {
1325
- diffs.push({ path: rel, status: "invalid-model", detail: dstModel.error });
1326
- } else if (normalizeManagedAgent(srcText, srcModel) !== normalizeManagedAgent(dstText, dstModel)) {
1327
- diffs.push({ path: rel, status: "stale" });
1328
- }
1329
- bindings.push({
1330
- agent: rel,
1331
- model: !dstModel.valid ? "invalid" : (dstModel.present ? dstModel.value : "inherit"),
1332
- });
1333
- }
1334
- return { diffs, bindings };
1335
- }
1336
-
1337
- function syncManagedAgents(assetAgents, agentsDir, options = {}){
1338
- const managedRoot = options.projectRoot || path.dirname(path.dirname(agentsDir));
1339
- projectDirectoryChain(managedRoot, path.relative(path.resolve(managedRoot), path.resolve(agentsDir)), true);
1340
- const bindings = [];
1341
- const managedFiles = new Set(listFiles(assetAgents));
1342
- for (const rel of listFiles(assetAgents)) {
1343
- const src = path.join(assetAgents, rel);
1344
- const dst = path.join(agentsDir, rel);
1345
- const templateText = fs.readFileSync(src, "utf8");
1346
- const existingText = exists(dst) ? fs.readFileSync(dst, "utf8") : "";
1347
- const rendered = renderManagedAgent(templateText, existingText, options.resetModel === true);
1348
- atomicWriteProjectFile(managedRoot, dst, rendered);
1349
- const model = inspectTopLevelModel(rendered);
1350
- bindings.push({ agent: rel, model: model.present ? model.value : "inherit" });
1351
- }
1352
- if (options.removeExtra === true) {
1353
- for (const rel of listFiles(agentsDir)) {
1354
- if (!managedFiles.has(rel)) fs.rmSync(path.join(agentsDir, rel), { force: true });
1355
- }
1356
- }
1357
- return bindings;
1358
- }
1359
-
1360
- function copyMissingDocs(assetSkill, project){
1361
- const srcDocs = path.join(assetSkill, "data", "templates", "docs");
1362
- const dstDocs = path.join(project, "docs");
1363
- const copied = [];
1364
- for (const rel of CORE_DOCS) {
1365
- const src = path.join(srcDocs, rel);
1366
- const dst = path.join(dstDocs, rel);
1367
- if (!exists(dst)) {
1368
- atomicCreateProjectFile(project, dst, fs.readFileSync(src));
1369
- copied.push(path.join("docs", rel));
1370
- }
1371
- }
1372
- return copied;
1373
- }
1374
-
1375
- function renderEngineeringTemplate(templateText, project){
1376
- void project;
1377
- return templateText;
1378
- }
1379
-
1380
- const MANAGED_WORKFLOW_START_TOKEN = "auto-coding-skill:managed-workflow:start";
1381
- const MANAGED_WORKFLOW_END_TOKEN = "auto-coding-skill:managed-workflow:end";
1382
- const MANAGED_WORKFLOW_START_RE = /<!--\s*auto-coding-skill:managed-workflow:start\s+version=([0-9]+\.[0-9]+\.[0-9]+)\s*-->/g;
1383
- const MANAGED_WORKFLOW_END_RE = /<!--\s*auto-coding-skill:managed-workflow:end\s*-->/g;
1384
- const MANAGED_AGENTS_START_TOKEN = "auto-coding-skill:managed-agents:start";
1385
- const MANAGED_AGENTS_END_TOKEN = "auto-coding-skill:managed-agents:end";
1386
- const MANAGED_AGENTS_START_RE = /<!--\s*auto-coding-skill:managed-agents:start\s+version=([0-9]+\.[0-9]+\.[0-9]+)\s*-->/g;
1387
- const MANAGED_AGENTS_END_RE = /<!--\s*auto-coding-skill:managed-agents:end\s*-->/g;
1388
-
1389
- function tokenCount(text, token){
1390
- return text.split(token).length - 1;
1391
- }
1392
-
1393
- function inspectManagedRegion(text, startToken, endToken, startPattern, endPattern, label){
1394
- const rawStarts = tokenCount(text, startToken);
1395
- const rawEnds = tokenCount(text, endToken);
1396
- if (rawStarts === 0 && rawEnds === 0) return { state: "absent" };
1397
-
1398
- const starts = [...text.matchAll(startPattern)];
1399
- const ends = [...text.matchAll(endPattern)];
1400
- if (rawStarts !== starts.length || rawEnds !== ends.length) {
1401
- return { state: "invalid", detail: `managed ${label} marker is malformed` };
1402
- }
1403
- if (starts.length !== 1 || ends.length !== 1) {
1404
- return { state: "invalid", detail: `managed ${label} markers must contain exactly one start/end pair` };
1405
- }
1406
- const start = starts[0].index;
1407
- const end = ends[0].index;
1408
- if (start >= end) {
1409
- return { state: "invalid", detail: "managed workflow markers are out of order or nested" };
1410
- }
1411
- const endExclusive = end + ends[0][0].length;
1412
- return {
1413
- state: "present",
1414
- version: starts[0][1],
1415
- start,
1416
- endExclusive,
1417
- block: text.slice(start, endExclusive),
1418
- };
1419
- }
1420
-
1421
- function inspectManagedWorkflow(text){
1422
- return inspectManagedRegion(
1423
- text,
1424
- MANAGED_WORKFLOW_START_TOKEN,
1425
- MANAGED_WORKFLOW_END_TOKEN,
1426
- MANAGED_WORKFLOW_START_RE,
1427
- MANAGED_WORKFLOW_END_RE,
1428
- "workflow",
1429
- );
1430
- }
1431
-
1432
- function inspectManagedAgentsDocument(text){
1433
- return inspectManagedRegion(
1434
- text,
1435
- MANAGED_AGENTS_START_TOKEN,
1436
- MANAGED_AGENTS_END_TOKEN,
1437
- MANAGED_AGENTS_START_RE,
1438
- MANAGED_AGENTS_END_RE,
1439
- "agents",
1440
- );
59
+ return args;
1441
60
  }
1442
61
 
1443
- function loadWorkflowMigrationPolicy(assetSkill){
1444
- const policyPath = path.join(assetSkill, "data", "policies", "workflow-migrations-v1.json");
1445
- let policy;
1446
- try {
1447
- policy = JSON.parse(fs.readFileSync(policyPath, "utf8"));
1448
- } catch (error) {
1449
- throw new Error(`invalid workflow migration policy ${policyPath}: ${error.message}`);
1450
- }
1451
- if (
1452
- policy?.schema_version !== 1
1453
- || !policy.managed_versions?.agents
1454
- || !policy.managed_versions?.engineering
1455
- || !Array.isArray(policy.known_official_agents_sha256)
1456
- || !Array.isArray(policy.known_official_engineering_body_sha256)
1457
- || !Array.isArray(policy.known_official_fragments)
1458
- || !Array.isArray(policy.conflict_rules)
1459
- ) {
1460
- throw new Error(`invalid workflow migration policy schema: ${policyPath}`);
1461
- }
1462
- return policy;
62
+ function readManifest(project) {
63
+ const file = path.join(project, ".agents", "managed-install.json");
64
+ if (!exists(file)) return null;
65
+ try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
1463
66
  }
1464
67
 
1465
- function escapeRegExp(text){
1466
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
68
+ function legacyManagedPath(relative) {
69
+ return relative.startsWith(".agents/skills/auto-coding-skill/")
70
+ || relative.startsWith(".agents/agents/")
71
+ || relative === "docs/tools/autopipeline/ap.py"
72
+ || relative === "docs/ENGINEERING.md";
1467
73
  }
1468
74
 
1469
- function applyKnownOfficialFragments(text, documentPath, policy){
1470
- let output = text;
1471
- const migrations = [];
1472
- for (const fragment of policy.known_official_fragments) {
1473
- if (!fragment.paths?.includes(documentPath) || !fragment.text) continue;
1474
- let pattern;
1475
- if (fragment.match === "heading-section") {
1476
- const lines = output.match(/.*(?:\r?\n|$)/g).filter(Boolean);
1477
- const offsets = [];
1478
- let cursor = 0;
1479
- for (const line of lines) {
1480
- offsets.push(cursor);
1481
- cursor += line.length;
75
+ function retireExactLegacyFiles(project) {
76
+ const previous = readManifest(project);
77
+ const retired = [];
78
+ if (!Array.isArray(previous?.entries)) return retired;
79
+ for (const entry of previous.entries) {
80
+ if (!legacyManagedPath(entry?.path) || typeof entry.sha256 !== "string") continue;
81
+ const target = path.join(project, ...entry.path.split("/"));
82
+ if (exists(target) && fs.statSync(target).isFile() && sha256(target) === entry.sha256) {
83
+ if (entry.path === "docs/ENGINEERING.md") {
84
+ const version = String(previous.skill_version || "legacy").replace(/[^0-9A-Za-z._-]/g, "_");
85
+ const archive = path.join(project, ".agents", "archive", "auto-coding-skill", version, "docs", "ENGINEERING.md");
86
+ copyFile(target, archive);
1482
87
  }
1483
- const spans = [];
1484
- for (let index = 0; index < lines.length; index += 1) {
1485
- const heading = lines[index].replace(/\r?\n$/, "").match(/^(\s*)(#{1,6})\s+(.+?)\s*#*\s*$/);
1486
- if (!heading || heading[3].trim() !== fragment.text.trim()) continue;
1487
- const level = heading[2].length;
1488
- let end = index + 1;
1489
- while (end < lines.length) {
1490
- const next = lines[end].replace(/\r?\n$/, "").match(/^\s*(#{1,6})\s+/);
1491
- if (next && next[1].length <= level) break;
1492
- end += 1;
1493
- }
1494
- spans.push([offsets[index], end < lines.length ? offsets[end] : output.length]);
1495
- }
1496
- if (spans.length) {
1497
- for (const [start, end] of spans.reverse()) output = output.slice(0, start) + output.slice(end);
1498
- migrations.push(fragment.id);
1499
- }
1500
- continue;
1501
- } else if (fragment.match === "exact-line") {
1502
- pattern = new RegExp(`^[\\t ]*${escapeRegExp(fragment.text.trim())}[\\t ]*(?:\\r?\\n|$)`, "gm");
1503
- } else if (fragment.match === "exact-block") {
1504
- const source = fragment.text.split("\n").map(escapeRegExp).join("\\r?\\n");
1505
- pattern = new RegExp(source, "g");
1506
- } else {
1507
- throw new Error(`unsupported workflow migration match '${fragment.match}' for ${fragment.id}`);
1508
- }
1509
- const replacement = typeof fragment.replacement === "string" ? fragment.replacement : "";
1510
- const updated = output.replace(pattern, matched => {
1511
- if (!replacement) return "";
1512
- if (fragment.match !== "exact-line") return replacement;
1513
- const eol = matched.endsWith("\r\n") ? "\r\n" : (matched.endsWith("\n") ? "\n" : "");
1514
- return `${replacement}${eol}`;
1515
- });
1516
- if (updated !== output) {
1517
- migrations.push(fragment.id);
1518
- output = updated;
1519
- }
1520
- }
1521
- return { output, migrations };
1522
- }
1523
-
1524
- function scanWorkflowConflicts(text, documentPath, policy){
1525
- const conflicts = [];
1526
- const seen = new Set();
1527
- const lines = text.replace(/\r\n/g, "\n").split("\n");
1528
- const candidates = lines.map((line, index) => ({ text: line, line: index + 1 }));
1529
- for (let index = 0; index < lines.length; index += 1) {
1530
- const line = lines[index];
1531
- if (!line.trim()) continue;
1532
- if (/^\s*(?:[-+*]|\d+\.)\s+/.test(line)) {
1533
- let end = index + 1;
1534
- while (end < lines.length && /^\s{2,}\S/.test(lines[end]) && !/^\s*(?:[-+*]|\d+\.)\s+/.test(lines[end])) end += 1;
1535
- if (end > index + 1) candidates.push({ text: lines.slice(index, end).join(" "), line: index + 1 });
1536
- continue;
1537
- }
1538
- if (/^\s*(?:#|\||```|~~~)/.test(line)) continue;
1539
- let end = index + 1;
1540
- while (end < lines.length && lines[end].trim() && !/^\s*(?:#|\||```|~~~|[-+*]|\d+\.)\s*/.test(lines[end])) end += 1;
1541
- if (end > index + 1) candidates.push({ text: lines.slice(index, end).join(" "), line: index + 1 });
1542
- }
1543
- for (const rule of policy.conflict_rules) {
1544
- if (!rule.paths?.includes(documentPath)) continue;
1545
- let pattern;
1546
- try {
1547
- pattern = new RegExp(rule.pattern, String(rule.flags || "").replaceAll("g", ""));
1548
- } catch (error) {
1549
- throw new Error(`invalid workflow conflict rule ${rule.id}: ${error.message}`);
1550
- }
1551
- for (const candidate of candidates) {
1552
- if (!pattern.test(candidate.text)) continue;
1553
- const key = `${rule.id}:${candidate.line}`;
1554
- if (seen.has(key)) continue;
1555
- seen.add(key);
1556
- conflicts.push({
1557
- file: documentPath,
1558
- line: candidate.line,
1559
- ruleId: rule.id,
1560
- message: rule.message,
1561
- excerpt: candidate.text.trim().slice(0, 240),
1562
- });
1563
- }
1564
- }
1565
- return conflicts;
1566
- }
1567
-
1568
- function migrateDocumentText(text, documentPath, policy){
1569
- const migrated = applyKnownOfficialFragments(text, documentPath, policy);
1570
- return {
1571
- output: migrated.output,
1572
- migrations: migrated.migrations,
1573
- conflicts: scanWorkflowConflicts(migrated.output, documentPath, policy),
1574
- };
1575
- }
1576
-
1577
- function replaceManagedBlock(text, region, block){
1578
- let before = text.slice(0, region.start);
1579
- let after = text.slice(region.endExclusive);
1580
- const eol = text.includes("\r\n") ? "\r\n" : "\n";
1581
- if (before && !/(?:\r?\n)$/.test(before)) before += eol;
1582
- if (after && !/^(?:\r?\n)/.test(after)) after = `${eol}${after}`;
1583
- return `${before}${block}${after}`;
1584
- }
1585
-
1586
- function splitEngineeringDocument(text){
1587
- const frontmatter = text.match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/);
1588
- const bodyStart = frontmatter ? frontmatter[0].length : 0;
1589
- return { frontmatter: text.slice(0, bodyStart), body: text.slice(bodyStart) };
1590
- }
1591
-
1592
- function engineeringBodyHash(body){
1593
- return crypto.createHash("sha256").update(body.replace(/\r\n/g, "\n")).digest("hex");
1594
- }
1595
-
1596
- function insertManagedWorkflow(text, block){
1597
- const { frontmatter } = splitEngineeringDocument(text);
1598
- const bodyStart = frontmatter.length;
1599
- const body = text.slice(bodyStart);
1600
- const heading = /^# Engineering Workflow[^\r\n]*(?:\r?\n|$)/m.exec(body);
1601
- const insertion = heading ? bodyStart + heading.index + heading[0].length : bodyStart;
1602
- const before = text.slice(0, insertion);
1603
- const after = text.slice(insertion);
1604
- const eol = text.includes("\r\n") ? "\r\n" : "\n";
1605
- const left = before && !/(?:\r?\n)$/.test(before) ? `${before}${eol}` : before;
1606
- const right = after && !/^(?:\r?\n)/.test(after) ? `${eol}${after}` : after;
1607
- return `${left}${block}${right}`;
1608
- }
1609
-
1610
- function lineCount(text){
1611
- return text ? text.replace(/\r\n/g, "\n").split("\n").length - 1 : 0;
1612
- }
1613
-
1614
- function offsetConflicts(conflicts, offset){
1615
- return conflicts.map(conflict => ({ ...conflict, line: conflict.line + offset }));
1616
- }
1617
-
1618
- function planEngineeringSync(project, assetSkill, policy = loadWorkflowMigrationPolicy(assetSkill)){
1619
- const root = path.resolve(project);
1620
- const engineering = path.join(root, "docs", "ENGINEERING.md");
1621
- const templatePath = path.join(assetSkill, "data", "templates", "ENGINEERING.md");
1622
- const renderedTemplate = renderEngineeringTemplate(fs.readFileSync(templatePath, "utf8"), root);
1623
- const templateRegion = inspectManagedWorkflow(renderedTemplate);
1624
- if (templateRegion.state !== "present") {
1625
- return { state: "invalid", detail: `packaged ENGINEERING template: ${templateRegion.detail || "managed workflow markers are missing"}` };
1626
- }
1627
- if (templateRegion.version !== policy.managed_versions.engineering) {
1628
- return { state: "invalid", detail: `packaged ENGINEERING version ${templateRegion.version} does not match migration policy ${policy.managed_versions.engineering}` };
1629
- }
1630
- if (!exists(engineering)) {
1631
- return { state: "missing", version: templateRegion.version, output: renderedTemplate, engineering, migrations: [], conflicts: [] };
1632
- }
1633
-
1634
- const current = fs.readFileSync(engineering, "utf8");
1635
- const currentRegion = inspectManagedWorkflow(current);
1636
- if (currentRegion.state === "invalid") return { ...currentRegion, engineering };
1637
- if (currentRegion.state === "absent") {
1638
- const currentParts = splitEngineeringDocument(current);
1639
- const templateParts = splitEngineeringDocument(renderedTemplate);
1640
- const legacyHash = engineeringBodyHash(currentParts.body);
1641
- if (policy.known_official_engineering_body_sha256.includes(legacyHash)) {
1642
- return {
1643
- state: "legacy-official",
1644
- version: templateRegion.version,
1645
- previousBodyHash: legacyHash,
1646
- output: `${currentParts.frontmatter}${templateParts.body}`,
1647
- engineering,
1648
- migrations: [`engineering-body-sha256:${legacyHash}`],
1649
- conflicts: [],
1650
- };
1651
- }
1652
- const migrated = migrateDocumentText(currentParts.body, "docs/ENGINEERING.md", policy);
1653
- const conflicts = offsetConflicts(migrated.conflicts, lineCount(currentParts.frontmatter));
1654
- if (conflicts.length) {
1655
- return {
1656
- state: "conflict",
1657
- version: templateRegion.version,
1658
- engineering,
1659
- migrations: migrated.migrations,
1660
- conflicts,
1661
- detail: "unknown workflow directives conflict with the managed fast-gate policy",
1662
- };
1663
- }
1664
- const sectionMigration = migrated.migrations.some(item => item.startsWith("engineering-section-"));
1665
- const archive = sectionMigration ? engineeringArchivePlan(root, current, templateRegion.version) : {};
1666
- return {
1667
- state: "legacy-custom",
1668
- version: templateRegion.version,
1669
- preservedCustom: true,
1670
- output: insertManagedWorkflow(`${currentParts.frontmatter}${migrated.output}`, templateRegion.block),
1671
- engineering,
1672
- migrations: migrated.migrations,
1673
- conflicts: [],
1674
- ...archive,
1675
- };
1676
- }
1677
- const beforeParts = splitEngineeringDocument(current.slice(0, currentRegion.start));
1678
- const migratedBefore = migrateDocumentText(beforeParts.body, "docs/ENGINEERING.md", policy);
1679
- const migratedAfter = migrateDocumentText(current.slice(currentRegion.endExclusive), "docs/ENGINEERING.md", policy);
1680
- const conflicts = [
1681
- ...offsetConflicts(migratedBefore.conflicts, lineCount(beforeParts.frontmatter)),
1682
- ...offsetConflicts(migratedAfter.conflicts, lineCount(current.slice(0, currentRegion.endExclusive))),
1683
- ];
1684
- const migrations = [...migratedBefore.migrations, ...migratedAfter.migrations];
1685
- if (conflicts.length) {
1686
- return {
1687
- state: "conflict",
1688
- version: templateRegion.version,
1689
- previousVersion: currentRegion.version,
1690
- engineering,
1691
- migrations,
1692
- conflicts,
1693
- detail: "unknown workflow directives conflict with the managed fast-gate policy",
1694
- };
1695
- }
1696
- const migratedCurrent = `${beforeParts.frontmatter}${migratedBefore.output}${currentRegion.block}${migratedAfter.output}`;
1697
- const migratedRegion = inspectManagedWorkflow(migratedCurrent);
1698
- const output = replaceManagedBlock(migratedCurrent, migratedRegion, templateRegion.block);
1699
- if (current === output) return { state: "current", version: templateRegion.version, output, engineering, migrations: [], conflicts: [] };
1700
- const sectionMigration = migrations.some(item => item.startsWith("engineering-section-"));
1701
- const archive = sectionMigration ? engineeringArchivePlan(root, current, templateRegion.version) : {};
1702
- return {
1703
- state: "stale",
1704
- version: templateRegion.version,
1705
- previousVersion: currentRegion.version,
1706
- output,
1707
- engineering,
1708
- migrations,
1709
- conflicts: [],
1710
- ...archive,
1711
- };
1712
- }
1713
-
1714
- function engineeringArchivePlan(root, current, version){
1715
- const archiveHeader = [
1716
- `# Archived ENGINEERING.md before auto-coding-skill ${version} docs convergence`,
1717
- "",
1718
- "This file is historical and non-authoritative. Known duplicate workflow sections",
1719
- "were removed from docs/ENGINEERING.md. Move any still-current project facts into",
1720
- "docs/project/ and configuration into docs/project/auto-coding-skill.yaml.",
1721
- "",
1722
- "---",
1723
- "",
1724
- ].join("\n");
1725
- const archiveOutput = `${archiveHeader}${current}`;
1726
- const archiveDir = path.join(root, ".agents", "archive", "auto-coding-skill", version, "workflow");
1727
- const selected = selectProjectArchiveTarget(
1728
- root,
1729
- path.join(archiveDir, "ENGINEERING.md"),
1730
- archiveOutput,
1731
- { legacyDigestPayload: current },
1732
- );
1733
- return {
1734
- archiveDocument: selected.path,
1735
- archiveOutput,
1736
- archiveRequired: selected.archiveRequired,
1737
- };
1738
- }
1739
-
1740
- function planAgentsDocumentSync(project, assetSkill, policy = loadWorkflowMigrationPolicy(assetSkill)){
1741
- const root = path.resolve(project);
1742
- const agentsDocument = path.join(root, "AGENTS.md");
1743
- validateProjectFileTarget(root, agentsDocument, "root AGENTS.md");
1744
- const templatePath = path.join(assetSkill, "data", "templates", "bridges", "AGENTS.md");
1745
- const template = fs.readFileSync(templatePath, "utf8");
1746
- const templateRegion = inspectManagedAgentsDocument(template);
1747
- if (templateRegion.state !== "present" || templateRegion.version !== policy.managed_versions.agents) {
1748
- return { state: "invalid", detail: "packaged AGENTS template markers/version do not match the migration policy", agentsDocument };
1749
- }
1750
- if (!exists(agentsDocument)) {
1751
- return { state: "missing", version: templateRegion.version, output: template, agentsDocument, migrations: [], conflicts: [] };
1752
- }
1753
- const current = fs.readFileSync(agentsDocument, "utf8");
1754
- if (current === template) {
1755
- return { state: "current", version: templateRegion.version, output: template, agentsDocument, migrations: [], conflicts: [] };
1756
- }
1757
- const archiveHeader = [
1758
- `# Archived AGENTS.md before auto-coding-skill ${templateRegion.version}`,
1759
- "",
1760
- "This file is historical and non-authoritative. The root AGENTS.md is fully managed.",
1761
- "Move any still-current project facts into docs/project/",
1762
- "without copying workflow rules back into the root AGENTS.md.",
1763
- "",
1764
- "---",
1765
- "",
1766
- ].join("\n");
1767
- const archiveOutput = `${archiveHeader}${current}`;
1768
- const archiveDir = path.join(
1769
- root,
1770
- ".agents",
1771
- "archive",
1772
- "auto-coding-skill",
1773
- templateRegion.version,
1774
- );
1775
- const selected = selectProjectArchiveTarget(
1776
- root,
1777
- path.join(archiveDir, "AGENTS.md"),
1778
- archiveOutput,
1779
- { legacyDigestPayload: current },
1780
- );
1781
- const currentRegion = inspectManagedAgentsDocument(current);
1782
- return {
1783
- state: currentRegion.state === "present" ? "stale" : "legacy-custom",
1784
- version: templateRegion.version,
1785
- ...(currentRegion.state === "present" ? { previousVersion: currentRegion.version } : {}),
1786
- output: template,
1787
- agentsDocument,
1788
- archiveDocument: selected.path,
1789
- archiveOutput,
1790
- archiveRequired: selected.archiveRequired,
1791
- migrations: ["agents-whole-file-replacement"],
1792
- conflicts: [],
1793
- };
1794
- }
1795
-
1796
- function planControlledDocuments(project, assetSkill){
1797
- const policy = loadWorkflowMigrationPolicy(assetSkill);
1798
- return {
1799
- engineering: planEngineeringSync(project, assetSkill, policy),
1800
- agents: planAgentsDocumentSync(project, assetSkill, policy),
1801
- };
1802
- }
1803
-
1804
- function publicEngineeringPlan(plan){
1805
- const publicConflicts = (plan.conflicts || []).map(conflict => ({
1806
- ...(conflict.file ? { file: conflict.file } : {}),
1807
- ...(Number.isInteger(conflict.line) ? { line: conflict.line } : {}),
1808
- ...(conflict.ruleId ? { ruleId: conflict.ruleId } : {}),
1809
- ...(conflict.message ? { message: conflict.message } : {}),
1810
- }));
1811
- return {
1812
- state: plan.state,
1813
- version: plan.version || "unknown",
1814
- ...(plan.previousVersion ? { previousVersion: plan.previousVersion } : {}),
1815
- ...(plan.previousBodyHash ? { previousBodyHash: plan.previousBodyHash } : {}),
1816
- ...(plan.preservedCustom ? { preservedCustom: true } : {}),
1817
- ...(plan.archiveDocument ? { archive: plan.archiveDocument } : {}),
1818
- ...(plan.migrations?.length ? { migrations: plan.migrations } : {}),
1819
- ...(publicConflicts.length ? { conflicts: publicConflicts } : {}),
1820
- ...(plan.detail ? { detail: plan.detail } : {}),
1821
- };
1822
- }
1823
-
1824
- function registeredTasks(project){
1825
- const root = path.resolve(project);
1826
- let commonDir;
1827
- try {
1828
- const raw = execFileSync("git", ["-C", root, "rev-parse", "--git-common-dir"], {
1829
- encoding: "utf8",
1830
- stdio: ["ignore", "pipe", "ignore"],
1831
- }).trim();
1832
- commonDir = path.resolve(root, raw);
1833
- } catch {
1834
- return [];
1835
- }
1836
- const tasksDir = path.join(commonDir, "auto-coding-skill", "tasks");
1837
- if (!exists(tasksDir)) return [];
1838
- const registered = [];
1839
- for (const entry of fs.readdirSync(tasksDir, { withFileTypes: true })) {
1840
- if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
1841
- const manifestPath = path.join(tasksDir, entry.name);
1842
- let manifest;
1843
- try {
1844
- manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
1845
- } catch {
1846
- registered.push({ project: root, manifest: entry.name, schema: "invalid" });
1847
- continue;
88
+ fs.rmSync(target);
89
+ retired.push(entry.path);
1848
90
  }
1849
- const schema = Number(manifest?.schema ?? 0);
1850
- registered.push({ project: root, manifest: entry.name, schema: Number.isFinite(schema) ? schema : "invalid" });
1851
91
  }
1852
- return registered;
92
+ return retired;
1853
93
  }
1854
94
 
1855
- function assertNoRegisteredTasks(projects){
1856
- const active = projects.flatMap(project => registeredTasks(project));
1857
- if (!active.length) return;
1858
- const locations = active.map(item => `${item.project}:${item.manifest}(schema=${item.schema})`).join(", ");
1859
- die(
1860
- "refusing the entire sync batch because registered auto-coding tasks are still active: "
1861
- + `${locations}\nFinish, integrate, or clean these tasks with the currently installed runtime before upgrading. `
1862
- + "sync will not change the lifecycle semantics of an in-flight task.",
1863
- );
95
+ function isManaged(previous, relative) {
96
+ return Array.isArray(previous?.entries) && previous.entries.some(entry => entry?.path === relative && entry?.ownership === "managed");
1864
97
  }
1865
98
 
1866
- function readPackageVersion(){
1867
- const here = path.dirname(fileURLToPath(import.meta.url));
1868
- const pkgPath = path.resolve(here, "..", "..", "package.json");
1869
- try {
1870
- return JSON.parse(fs.readFileSync(pkgPath, "utf8")).version ?? "unknown";
1871
- } catch {
1872
- return "unknown";
1873
- }
1874
- }
1875
-
1876
- function feedbackLifecycleStatus(root, assetSkill){
1877
- const result = spawnSync(
1878
- runtimePython(),
1879
- [path.join(assetSkill, "scripts", "ap.py"), "feedback-collect", "--project", root, "--json"],
1880
- { encoding: "utf8", stdio: "pipe", maxBuffer: 2 * 1024 * 1024 },
1881
- );
1882
- if (result.error || result.signal || result.status !== 0) {
1883
- return {
1884
- available: false,
1885
- advisory: "run autocoding feedback --projects . --json to inspect Skill feedback metadata",
1886
- };
1887
- }
1888
- try {
1889
- const parsed = JSON.parse(result.stdout);
1890
- return {
1891
- available: true,
1892
- skillVersion: parsed.projects?.[0]?.skill_version || "",
1893
- reportCount: parsed.report_count || 0,
1894
- activeReportCount: parsed.active_report_count || 0,
1895
- closedReportCount: parsed.closed_report_count || 0,
1896
- actionRequiredCount: parsed.action_required_count || 0,
1897
- lifecycleCounts: parsed.lifecycle_counts || {},
1898
- actionRequired: parsed.action_required || [],
1899
- };
1900
- } catch {
1901
- return {
1902
- available: false,
1903
- advisory: "run autocoding feedback --projects . --json to inspect Skill feedback metadata",
1904
- };
1905
- }
99
+ function migrateLegacyEnvironment(project) {
100
+ const previous = readManifest(project);
101
+ const environment = path.join(project, "docs", "ENVIRONMENT.md");
102
+ const projectConfig = path.join(project, "docs", "PROJECT.md");
103
+ if (!exists(environment) || exists(projectConfig) || isManaged(previous, "docs/ENVIRONMENT.md")) return false;
104
+ const legacy = fs.readFileSync(environment, "utf8")
105
+ .replace(/\n?## Migrated access configuration\n\n```yaml\n[\s\S]*?\n```\n?/g, "\n")
106
+ .trim();
107
+ if (!legacy) return false;
108
+ const template = fs.readFileSync(path.join(assetSkill, "data", "templates", "PROJECT.md"), "utf8").trimEnd();
109
+ mkdirFor(projectConfig);
110
+ fs.writeFileSync(projectConfig, `${template}\n\n## Migrated pre-5.0.1 environment context\n\n${legacy}\n`);
111
+ return true;
1906
112
  }
1907
113
 
1908
- function projectStatus(project, assetSkill, assetAgents, assetManifest, releaseManifest){
1909
- const root = path.resolve(project);
1910
- validateInstallTransactionInputs(root, assetSkill, assetManifest);
1911
- validateProjectManagedTargets(root, assetAgents);
1912
- const transactionPending = installTransactionPending(root);
1913
- const skillDir = path.join(root, ".agents", "skills", "auto-coding-skill");
1914
- const agentsDir = path.join(root, ".agents", "agents");
1915
- const toolDir = path.join(root, "docs", "tools", "autopipeline");
1916
- const engineering = path.join(root, "docs", "ENGINEERING.md");
1917
- const engineeringMissing = !exists(engineering);
1918
- const controlledPlans = planControlledDocuments(root, assetSkill);
1919
- const engineeringPlan = controlledPlans.engineering;
1920
- const agentsDocumentPlan = controlledPlans.agents;
1921
- const managedWorkflow = publicEngineeringPlan(engineeringPlan);
1922
- const managedAgentsDocument = publicEngineeringPlan(agentsDocumentPlan);
1923
- const requiredConfigPaths = [
1924
- { label: "workflow.skill_version", path: ["workflow", "skill_version"] },
1925
- { label: "workflow.mode", path: ["workflow", "mode"] },
1926
- { label: "workflow.profile", path: ["workflow", "profile"] },
1927
- { label: "workflow.completion", path: ["workflow", "completion"] },
1928
- { label: "concurrency.isolation", path: ["concurrency", "isolation"] },
1929
- { label: "concurrency.base_ref", path: ["concurrency", "base_ref"] },
1930
- { label: "concurrency.target_branch", path: ["concurrency", "target_branch"] },
1931
- { label: "concurrency.branch_prefix", path: ["concurrency", "branch_prefix"] },
1932
- { label: "concurrency.worktree_root", path: ["concurrency", "worktree_root"] },
1933
- { label: "concurrency.cleanup_merged", path: ["concurrency", "cleanup_merged"] },
1934
- { label: "concurrency.delete_remote_branch", path: ["concurrency", "delete_remote_branch"] },
1935
- { label: "concurrency.disposable_ignored", path: ["concurrency", "disposable_ignored"] },
1936
- { label: "validation.on_unmapped", path: ["validation", "on_unmapped"] },
1937
- { label: "validation.max_command_seconds", path: ["validation", "max_command_seconds"] },
1938
- { label: "validation.max_total_seconds", path: ["validation", "max_total_seconds"] },
1939
- { label: "validation.routes", path: ["validation", "routes"], sequence: true },
1940
- { label: "risk.rules", path: ["risk", "rules"] },
1941
- { label: "docs.framework", path: ["docs", "framework"], filled: true },
1942
- { label: "project.name", path: ["project", "name"], filled: true },
1943
- { label: "access.project.frontend.url", path: ["access", "project", "frontend", "url"], filled: true },
1944
- { label: "access.project.frontend.username", path: ["access", "project", "frontend", "username"], filled: true },
1945
- { label: "access.project.frontend.password", path: ["access", "project", "frontend", "password"], filled: true },
1946
- { label: "access.project.backend.url", path: ["access", "project", "backend", "url"], filled: true },
1947
- { label: "access.project.backend.username", path: ["access", "project", "backend", "username"], filled: true },
1948
- { label: "access.project.backend.password", path: ["access", "project", "backend", "password"], filled: true },
1949
- { label: "access.jenkins.frontend.url", path: ["access", "jenkins", "frontend", "url"], filled: true },
1950
- { label: "access.jenkins.frontend.username", path: ["access", "jenkins", "frontend", "username"], filled: true },
1951
- { label: "access.jenkins.frontend.password", path: ["access", "jenkins", "frontend", "password"], filled: true },
1952
- { label: "access.jenkins.backend.url", path: ["access", "jenkins", "backend", "url"], filled: true },
1953
- { label: "access.jenkins.backend.username", path: ["access", "jenkins", "backend", "username"], filled: true },
1954
- { label: "access.jenkins.backend.password", path: ["access", "jenkins", "backend", "password"], filled: true },
1955
- { label: "access.gitlab.url", path: ["access", "gitlab", "url"], filled: true },
1956
- { label: "access.gitlab.username", path: ["access", "gitlab", "username"], filled: true },
1957
- { label: "access.gitlab.password", path: ["access", "gitlab", "password"], filled: true },
1958
- { label: "access.nexus.frontend.url", path: ["access", "nexus", "frontend", "url"], filled: true },
1959
- { label: "access.nexus.frontend.username", path: ["access", "nexus", "frontend", "username"], filled: true },
1960
- { label: "access.nexus.frontend.password", path: ["access", "nexus", "frontend", "password"], filled: true },
1961
- ];
1962
- let missingConfigPaths = requiredConfigPaths.map(item => item.label);
1963
- let unfilledConfigTokens = [];
1964
- let invalidConfigTokens = [];
1965
- const effectiveConfig = readEffectiveConfigStatus(root, assetSkill);
1966
- if (!engineeringMissing && effectiveConfig.ok) {
1967
- const states = requiredConfigPaths.map(item => ({
1968
- item,
1969
- state: effectiveConfig.fields[item.label] || { present: false, configured: false, item_count: -1 },
1970
- }));
1971
- missingConfigPaths = states.filter(({ state }) => !state.present).map(({ item }) => item.label);
1972
- unfilledConfigTokens = states
1973
- .filter(({ item, state }) => state.present && (
1974
- (item.filled === true && !state.configured)
1975
- || (item.sequence === true && state.item_count <= 0)
1976
- ))
1977
- .map(({ item }) => item.label);
1978
- const isolationState = effectiveConfig.fields["concurrency.isolation"] || {};
1979
- if (isolationState.present && !["adaptive", "worktree"].includes(String(isolationState.value || "").toLowerCase())) {
1980
- invalidConfigTokens.push("concurrency.isolation (must be adaptive or worktree)");
1981
- }
1982
- for (const label of [
1983
- "validation.max_command_seconds",
1984
- "validation.max_total_seconds",
1985
- ]) {
1986
- const state = effectiveConfig.fields[label] || {};
1987
- if (!state.present) continue;
1988
- const value = Number(state.value);
1989
- if (!Number.isFinite(value) || value <= 0) {
1990
- invalidConfigTokens.push(`${label} (must be > 0)`);
1991
- }
1992
- }
1993
- const commandState = effectiveConfig.fields["validation.max_command_seconds"] || {};
1994
- const totalState = effectiveConfig.fields["validation.max_total_seconds"] || {};
1995
- const commandBudget = Number(commandState.value);
1996
- const totalBudget = Number(totalState.value);
1997
- if (commandState.present && totalState.present && Number.isFinite(commandBudget) && Number.isFinite(totalBudget) && commandBudget > totalBudget) {
1998
- invalidConfigTokens.push("validation.max_command_seconds (cannot exceed max_total_seconds)");
1999
- }
2000
- invalidConfigTokens.push(...(effectiveConfig.policy_issues || []));
2001
- invalidConfigTokens.push(...(effectiveConfig.contract_issues || []));
2002
- } else if (!engineeringMissing) {
2003
- invalidConfigTokens.push(`effective configuration (${effectiveConfig.error || "invalid"})`);
2004
- }
2005
- invalidConfigTokens = [...new Set(invalidConfigTokens)];
2006
- const missingConfigTokens = [...missingConfigPaths, ...unfilledConfigTokens, ...invalidConfigTokens];
2007
- const scriptDiffs = [];
2008
- const launcherSrc = path.join(assetSkill, "data", "templates", "tools", "ap.py");
2009
- const launcherDst = path.join(toolDir, "ap.py");
2010
- if (!exists(launcherDst)) scriptDiffs.push({ path: "docs/tools/autopipeline/ap.py", status: "missing" });
2011
- else if (!fs.readFileSync(launcherSrc).equals(fs.readFileSync(launcherDst))) {
2012
- scriptDiffs.push({ path: "docs/tools/autopipeline/ap.py", status: "stale" });
2013
- }
2014
- const missingDocs = [];
2015
- for (const rel of CORE_DOCS) {
2016
- if (!exists(path.join(root, "docs", rel))) missingDocs.push(path.join("docs", rel));
2017
- }
2018
- let docsDiffs = [];
2019
- const convergenceCheck = spawnSync(
2020
- runtimePython(),
2021
- [path.join(assetSkill, "scripts", "ap.py"), "--repo", root, "project-converge", "--json"],
2022
- { encoding: "utf8", stdio: "pipe" },
2023
- );
2024
- if (convergenceCheck.status === 0) {
2025
- try {
2026
- docsDiffs = (JSON.parse(convergenceCheck.stdout).actions || []).filter(item =>
2027
- item.path === "docs/ENGINEERING.md" || item.path.startsWith("docs/"),
2028
- );
2029
- } catch {
2030
- docsDiffs = [{ action: "invalid", path: "docs", detail: "convergence check returned invalid JSON" }];
2031
- }
2032
- } else {
2033
- docsDiffs = [{
2034
- action: "invalid",
2035
- path: "docs",
2036
- detail: String(convergenceCheck.stderr || convergenceCheck.stdout || "convergence check failed").trim(),
2037
- }];
2038
- }
2039
- const skillDiffs = exists(skillDir) ? compareDirs(assetSkill, skillDir, { includeExtra: true }) : [{ path: ".agents/skills/auto-coding-skill", status: "missing" }];
2040
- const agentStatus = exists(agentsDir)
2041
- ? compareManagedAgents(assetAgents, agentsDir)
2042
- : { diffs: [{ path: ".agents/agents", status: "missing" }], bindings: [] };
2043
- const agentDiffs = agentStatus.diffs;
2044
- const installedManifest = installManifestTarget(root);
2045
- const installManifestDiffs = [];
2046
- if (!exists(installedManifest)) installManifestDiffs.push({ path: ".agents/managed-install.json", status: "missing" });
2047
- else if (!fs.readFileSync(assetManifest).equals(fs.readFileSync(installedManifest))) {
2048
- installManifestDiffs.push({ path: ".agents/managed-install.json", status: "stale" });
2049
- }
2050
- const installIntegrity = installIntegrityStatus(root, "project", releaseManifest.skill_version);
2051
- const feedback = feedbackLifecycleStatus(root, assetSkill);
2052
- const ok = !transactionPending
2053
- && skillDiffs.length === 0
2054
- && agentDiffs.length === 0
2055
- && scriptDiffs.length === 0
2056
- && installManifestDiffs.length === 0
2057
- && installIntegrity.ok
2058
- && missingDocs.length === 0
2059
- && docsDiffs.length === 0
2060
- && missingConfigTokens.length === 0
2061
- && managedWorkflow.state === "current"
2062
- && managedAgentsDocument.state === "current";
2063
- let next = "";
2064
- if (transactionPending) {
2065
- next = "run autocoding init or a single-project autocoding sync to recover the interrupted install transaction";
2066
- } else if (!exists(skillDir) || !exists(agentsDir)) {
2067
- next = "run autocoding init";
2068
- } else if (skillDiffs.length || agentDiffs.length || installManifestDiffs.length || !installIntegrity.ok) {
2069
- next = "run autocoding init";
2070
- } else if (engineeringMissing || managedWorkflow.state !== "current" || managedAgentsDocument.state !== "current" || scriptDiffs.length || missingDocs.length || docsDiffs.length) {
2071
- next = "run autocoding init";
2072
- } else if (missingConfigPaths.length) {
2073
- next = "run autocoding init, fill every required value in docs/project/auto-coding-skill.yaml, then run doctor";
2074
- } else if (invalidConfigTokens.length) {
2075
- next = "run autocoding init, then run doctor";
2076
- } else if (unfilledConfigTokens.length) {
2077
- next = "fill every required value in docs/project/auto-coding-skill.yaml, then run project-local ap.py doctor";
114
+ function buildManifest(project) {
115
+ const entries = [];
116
+ const installedSkill = path.join(project, ".agents", "skills", "auto-coding-skill");
117
+ for (const relative of listFiles(installedSkill)) {
118
+ const target = path.join(installedSkill, relative);
119
+ entries.push({ path: `.agents/skills/auto-coding-skill/${relative}`, sha256: sha256(target), ownership: "managed" });
2078
120
  }
121
+ const agentsTarget = path.join(project, "AGENTS.md");
122
+ entries.push({ path: "AGENTS.md", sha256: sha256(agentsTarget), ownership: "managed" });
123
+ const environmentTarget = path.join(project, "docs", "ENVIRONMENT.md");
124
+ entries.push({ path: "docs/ENVIRONMENT.md", sha256: sha256(environmentTarget), ownership: "managed" });
2079
125
  return {
2080
- project: root,
2081
- ok,
2082
- transactionPending,
2083
- skillDiffs,
2084
- agentDiffs,
2085
- agentBindings: agentStatus.bindings,
2086
- scriptDiffs,
2087
- installManifestDiffs,
2088
- installIntegrity,
2089
- docsDiffs,
2090
- missingDocs,
2091
- missingConfigTokens,
2092
- missingConfigPaths,
2093
- unfilledConfigTokens,
2094
- invalidConfigTokens,
2095
- managedWorkflow,
2096
- managedAgentsDocument,
2097
- feedback,
2098
- next,
126
+ schema_version: 3,
127
+ skill_version: pkg.version,
128
+ entries,
129
+ managed_documents: managedDocs.map(([, target]) => target),
130
+ project_documents: projectDocs.map(([, target]) => target),
131
+ note: "AGENTS.md and docs/ENVIRONMENT.md are refreshed by init/sync. Project documents are bootstrap-only and are never overwritten.",
2099
132
  };
2100
133
  }
2101
134
 
2102
- function printProjectStatus(result){
2103
- console.log(`[autocoding] project=${result.project}`);
2104
- console.log(`[autocoding] ok=${result.ok}`);
2105
- if (result.transactionPending) console.log("[autocoding] install transaction: recovery required");
2106
- for (const [label, items] of [["skill", result.skillDiffs], ["agents", result.agentDiffs], ["scripts", result.scriptDiffs]]) {
2107
- for (const item of items) {
2108
- const detail = item.detail ? ` - ${item.detail}` : "";
2109
- console.log(`[autocoding] ${label} ${item.status}: ${item.path}${detail}`);
2110
- }
2111
- }
2112
- for (const item of result.installManifestDiffs || []) {
2113
- console.log(`[autocoding] manifest ${item.status}: ${item.path}`);
2114
- }
2115
- for (const issue of result.installIntegrity?.errors || []) {
2116
- console.log(`[autocoding] install integrity: ${issue}`);
2117
- }
2118
- for (const item of result.missingDocs) console.log(`[autocoding] doc missing: ${item}`);
2119
- for (const item of result.docsDiffs || []) {
2120
- const detail = item.detail ? ` - ${item.detail}` : "";
2121
- console.log(`[autocoding] docs ${item.action}: ${item.path}${detail}`);
2122
- }
2123
- for (const item of result.missingConfigTokens) console.log(`[autocoding] config missing path: ${item}`);
2124
- if (result.managedWorkflow?.state !== "current") {
2125
- const detail = result.managedWorkflow?.detail ? ` - ${result.managedWorkflow.detail}` : "";
2126
- console.log(`[autocoding] engineering managed-workflow: ${result.managedWorkflow?.state || "unknown"} target=${result.managedWorkflow?.version || "unknown"}${detail}`);
2127
- }
2128
- if (result.managedAgentsDocument?.state !== "current") {
2129
- const detail = result.managedAgentsDocument?.detail ? ` - ${result.managedAgentsDocument.detail}` : "";
2130
- console.log(`[autocoding] agents managed-document: ${result.managedAgentsDocument?.state || "unknown"} target=${result.managedAgentsDocument?.version || "unknown"}${detail}`);
2131
- }
2132
- for (const item of result.agentBindings || []) console.log(`[autocoding] agent model: ${item.agent} -> ${item.model}`);
2133
- if (result.feedback?.available && result.feedback.actionRequiredCount) {
2134
- console.log(`[autocoding] feedback advisory: ${result.feedback.actionRequiredCount} report(s) need maintenance`);
2135
- for (const item of result.feedback.actionRequired || []) {
2136
- console.log(`[autocoding] feedback action: ${item.report_id} ${item.lifecycle} -> ${item.recommended_action}`);
2137
- }
2138
- } else if (result.feedback && !result.feedback.available) {
2139
- console.log(`[autocoding] feedback advisory: ${result.feedback.advisory}`);
2140
- }
2141
- if (result.next) console.log(`[autocoding] next: ${result.next}`);
2142
- }
2143
-
2144
- function engineeringPlanDetail(plan){
2145
- if (plan.state === "legacy-custom") return `managed workflow preserved-custom -> ${plan.version}`;
2146
- if (plan.state === "legacy-official") return `managed workflow official-legacy -> ${plan.version}`;
2147
- return `managed workflow ${plan.state} -> ${plan.version}`;
2148
- }
2149
-
2150
- function syncProject(project, assetSkill, assetAgents, assetManifest, releaseManifest, dryRun, resetAgentModels = false, components = "all", controlledPlans = null){
135
+ function init(project) {
2151
136
  const root = path.resolve(project);
2152
- const actions = [];
2153
- const skillDir = path.join(root, ".agents", "skills", "auto-coding-skill");
2154
- const plans = controlledPlans || planControlledDocuments(root, assetSkill);
2155
- let prepared = null;
2156
- let transaction = null;
2157
- if (!dryRun) safeProjectMutationRequired = true;
2158
- if (dryRun) {
2159
- const engineeringConvergence = plans.engineeringConvergence || runEngineeringConvergence(root, assetSkill, false);
2160
- for (const item of engineeringConvergence.actions || []) {
2161
- actions.push({
2162
- ...item,
2163
- action: String(item.action).startsWith("would-") ? item.action : `would-${item.action}`,
2164
- });
2165
- }
2166
- } else {
2167
- // Write only the project-owned overlay first. Keep the legacy ENGINEERING
2168
- // bytes in place until the effective-config-aware runtime has been copied.
2169
- prepared = runProjectConfigPrepare(root, assetSkill, true);
2170
- actions.push(...prepared.actions);
2171
- injectInstallFault("after-prepare");
2172
- transaction = beginInstallTransaction(root, assetSkill, assetManifest, prepared);
2173
- injectInstallFault("after-stage-copy");
2174
- }
2175
- actions.push({ action: dryRun ? "would-sync" : "sync", path: path.relative(root, skillDir) });
2176
- actions.push({ action: dryRun ? "would-sync" : "sync", path: ".agents/managed-install.json" });
2177
- if (!dryRun) {
2178
- switchInstallTransaction(root, transaction);
2179
- injectInstallFault("after-runtime-switch");
2180
- if (prepared.finalize_required) {
2181
- const finalized = runProjectConfigFinalize(
2182
- root,
2183
- skillDir,
2184
- prepared,
2185
- true,
2186
- transaction.token,
2187
- transaction,
2188
- );
2189
- actions.push(...finalized.actions);
2190
- }
2191
- injectInstallFault("after-config-finalize");
2192
- // Complete exact managed-document convergence while the rollback backups
2193
- // are still present, before unrelated managed files are touched.
2194
- const convergence = runEngineeringConvergence(
2195
- root,
2196
- skillDir,
2197
- true,
2198
- transaction.token,
2199
- transaction,
2200
- );
2201
- for (const item of convergence.actions || []) {
2202
- if (actions.some(action => action.path === item.path && action.action === item.action)) continue;
2203
- actions.push(item);
2204
- }
2205
- }
2206
-
2207
- const agentsDir = path.join(root, ".agents", "agents");
2208
- const toolDir = path.join(root, "docs", "tools", "autopipeline");
2209
- const agentsDocumentPlan = plans.agents;
2210
- actions.push({ action: dryRun ? "would-sync" : "sync", path: path.relative(root, agentsDir) });
2211
- actions.push({ action: dryRun ? "would-sync" : "sync", path: "docs/tools/autopipeline/ap.py" });
2212
- if (!dryRun) {
2213
- syncManagedAgents(assetAgents, agentsDir, { resetModel: resetAgentModels, projectRoot: root });
2214
- atomicWriteProjectFile(
2215
- root,
2216
- path.join(toolDir, "ap.py"),
2217
- fs.readFileSync(path.join(assetSkill, "data", "templates", "tools", "ap.py")),
2218
- );
2219
- for (const copied of copyMissingDocs(assetSkill, root)) actions.push({ action: "create", path: copied });
2220
- if (agentsDocumentPlan.state !== "current") {
2221
- if (agentsDocumentPlan.archiveRequired) {
2222
- atomicCreateProjectFile(root, agentsDocumentPlan.archiveDocument, agentsDocumentPlan.archiveOutput);
2223
- actions.push({
2224
- action: "archive",
2225
- path: path.relative(root, agentsDocumentPlan.archiveDocument),
2226
- detail: "previous root AGENTS.md; historical and non-authoritative",
2227
- });
2228
- }
2229
- atomicWriteProjectFile(root, agentsDocumentPlan.agentsDocument, agentsDocumentPlan.output);
2230
- actions.push({
2231
- action: agentsDocumentPlan.state === "missing" ? "create" : "update",
2232
- path: "AGENTS.md",
2233
- detail: `managed agents ${agentsDocumentPlan.state} -> ${agentsDocumentPlan.version}`,
2234
- });
2235
- }
2236
- applyManifestExecutableBits(root, releaseManifest, "project");
2237
- const integrity = requireInstallIntegrity(root, "project", releaseManifest.skill_version);
2238
- actions.push({ action: "verify", path: ".agents/managed-install.json", detail: `${integrity.checked} managed files` });
2239
- completeInstallTransaction(root, transaction);
2240
- } else {
2241
- for (const rel of CORE_DOCS) {
2242
- if (!exists(path.join(root, "docs", rel))) actions.push({ action: "would-create", path: path.join("docs", rel) });
2243
- }
2244
- if (agentsDocumentPlan.state !== "current") {
2245
- if (agentsDocumentPlan.archiveRequired) {
2246
- actions.push({
2247
- action: "would-archive",
2248
- path: path.relative(root, agentsDocumentPlan.archiveDocument),
2249
- detail: "previous root AGENTS.md; historical and non-authoritative",
2250
- });
2251
- }
2252
- actions.push({
2253
- action: agentsDocumentPlan.state === "missing" ? "would-create" : "would-update",
2254
- path: "AGENTS.md",
2255
- detail: `managed agents ${agentsDocumentPlan.state} -> ${agentsDocumentPlan.version}`,
2256
- });
2257
- }
2258
- }
2259
- const reportedPlans = dryRun ? plans : planControlledDocuments(root, assetSkill);
2260
- return {
2261
- project: root,
2262
- dryRun,
2263
- components,
2264
- managedWorkflow: publicEngineeringPlan(reportedPlans.engineering),
2265
- managedAgentsDocument: publicEngineeringPlan(reportedPlans.agents),
2266
- feedback: feedbackLifecycleStatus(root, assetSkill),
2267
- actions,
2268
- };
2269
- }
2270
-
2271
- function convergeProjectInstall(project, assetSkill, assetAgents, assetManifest, releaseManifest, resetAgentModels){
137
+ if (!exists(root)) fail(`project directory does not exist: ${root}`);
138
+ const retired = retireExactLegacyFiles(root);
139
+ const installedSkill = path.join(root, ".agents", "skills", "auto-coding-skill");
140
+ fs.rmSync(installedSkill, { recursive: true, force: true });
141
+ copyTree(assetSkill, installedSkill);
142
+ copyFile(assetAgents, path.join(root, "AGENTS.md"));
143
+ const migratedEnvironment = migrateLegacyEnvironment(root);
144
+ const created = [];
145
+ for (const [assetRelative, targetRelative] of managedDocs) {
146
+ const source = path.join(assetSkill, "data", "templates", assetRelative);
147
+ copyFile(source, path.join(root, targetRelative));
148
+ }
149
+ for (const [assetRelative, targetRelative] of projectDocs) {
150
+ const source = path.join(assetSkill, "data", "templates", assetRelative);
151
+ const target = path.join(root, targetRelative);
152
+ if (!exists(target)) {
153
+ copyFile(source, target);
154
+ created.push(targetRelative);
155
+ }
156
+ }
157
+ const manifest = buildManifest(root);
158
+ const manifestPath = path.join(root, ".agents", "managed-install.json");
159
+ mkdirFor(manifestPath);
160
+ fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
161
+ return { project: root, version: pkg.version, created, retired, migrated_environment: migratedEnvironment, managed: manifest.entries.length };
162
+ }
163
+
164
+ function status(project) {
2272
165
  const root = path.resolve(project);
2273
- const skillDir = path.join(root, ".agents", "skills", "auto-coding-skill");
2274
- const agentsDir = path.join(root, ".agents", "agents");
2275
- const toolDir = path.join(root, "docs", "tools", "autopipeline");
2276
- const actions = [];
2277
- safeProjectMutationRequired = true;
2278
-
2279
- recoverInstallTransaction(root, true);
2280
- validateInstallTransactionInputs(root, assetSkill, assetManifest);
2281
- validateProjectManagedTargets(root, assetAgents);
2282
- // Validate the authoritative template and legacy input before the first write.
2283
- runEngineeringConvergence(root, assetSkill, false);
2284
- // Materialize only the project-owned overlay while the previous installed
2285
- // template is still available as the semantic diff base. Replacing the
2286
- // managed document is deferred until the new runtime is in place.
2287
- const prepared = runProjectConfigPrepare(root, assetSkill, true);
2288
- actions.push(...prepared.actions);
2289
- injectInstallFault("after-prepare");
2290
- const transaction = beginInstallTransaction(root, assetSkill, assetManifest, prepared);
2291
- injectInstallFault("after-stage-copy");
2292
-
2293
- switchInstallTransaction(root, transaction);
2294
- actions.push({ action: "replace", path: path.relative(root, skillDir) });
2295
- actions.push({ action: "replace", path: ".agents/managed-install.json" });
2296
- injectInstallFault("after-runtime-switch");
2297
-
2298
- if (prepared.finalize_required) {
2299
- const finalized = runProjectConfigFinalize(
2300
- root,
2301
- skillDir,
2302
- prepared,
2303
- true,
2304
- transaction.token,
2305
- transaction,
2306
- );
2307
- actions.push(...finalized.actions);
2308
- }
2309
- injectInstallFault("after-config-finalize");
2310
- const engineering = runEngineeringConvergence(
2311
- root,
2312
- skillDir,
2313
- true,
2314
- transaction.token,
2315
- transaction,
2316
- );
2317
- for (const item of engineering.actions || []) {
2318
- if (actions.some(action => action.path === item.path && action.action === item.action)) continue;
2319
- actions.push(item);
2320
- }
2321
-
2322
- syncManagedAgents(assetAgents, agentsDir, { resetModel: resetAgentModels, projectRoot: root });
2323
- actions.push({ action: "sync", path: path.relative(root, agentsDir) });
2324
-
2325
- atomicWriteProjectFile(
2326
- root,
2327
- path.join(toolDir, "ap.py"),
2328
- fs.readFileSync(path.join(assetSkill, "data", "templates", "tools", "ap.py")),
2329
- );
2330
- actions.push({ action: "replace", path: "docs/tools/autopipeline/ap.py" });
2331
-
2332
- const agentsDocument = path.join(root, "AGENTS.md");
2333
- const canonicalAgents = fs.readFileSync(
2334
- path.join(assetSkill, "data", "templates", "bridges", "AGENTS.md"),
2335
- "utf8",
2336
- );
2337
- const currentAgents = exists(agentsDocument) ? fs.readFileSync(agentsDocument, "utf8") : "";
2338
- if (currentAgents !== canonicalAgents) {
2339
- if (currentAgents) {
2340
- const preferredArchive = path.join(
2341
- root,
2342
- ".agents",
2343
- "archive",
2344
- "auto-coding-skill",
2345
- readPackageVersion(),
2346
- "AGENTS.md",
2347
- );
2348
- const selected = selectProjectArchiveTarget(root, preferredArchive, currentAgents, {
2349
- legacyDigestPayload: currentAgents,
2350
- });
2351
- if (selected.archiveRequired) {
2352
- atomicCreateProjectFile(root, selected.path, currentAgents);
2353
- actions.push({
2354
- action: "archive",
2355
- path: path.relative(root, selected.path),
2356
- detail: "historical and non-authoritative",
2357
- });
2358
- }
2359
- }
2360
- atomicWriteProjectFile(root, agentsDocument, canonicalAgents);
2361
- actions.push({ action: "replace", path: "AGENTS.md" });
2362
- }
2363
-
2364
- applyManifestExecutableBits(root, releaseManifest, "project");
2365
- const integrity = requireInstallIntegrity(root, "project", releaseManifest.skill_version);
2366
- actions.push({ action: "verify", path: ".agents/managed-install.json", detail: `${integrity.checked} managed files` });
2367
- completeInstallTransaction(root, transaction);
2368
- return { project: root, feedback: feedbackLifecycleStatus(root, assetSkill), actions };
2369
- }
2370
-
2371
- function projectRoot(){ return process.cwd(); }
2372
-
2373
- function resolveInstallDirs(mode, destOverride){
2374
- if (mode !== "project" && mode !== "global") die(`--mode must be 'project' or 'global'`);
2375
-
2376
- if (destOverride) {
2377
- const dest = path.resolve(destOverride);
2378
- const parent = path.dirname(dest);
2379
- const grandparent = path.dirname(parent);
2380
- if (path.basename(dest) === "auto-coding-skill" && path.basename(parent) === "skills" && path.basename(grandparent) === ".agents") {
2381
- return {
2382
- skillDir: dest,
2383
- agentsDir: path.join(grandparent, "agents"),
2384
- projectDir: path.dirname(grandparent),
2385
- };
2386
- }
2387
- if (path.basename(dest) === "skills" && path.basename(parent) === ".agents") {
2388
- return {
2389
- skillDir: path.join(dest, "auto-coding-skill"),
2390
- agentsDir: path.join(parent, "agents"),
2391
- projectDir: path.dirname(parent),
2392
- };
2393
- }
2394
- if (path.basename(dest) === "agents" && path.basename(parent) === ".agents") {
2395
- return {
2396
- skillDir: path.join(parent, "skills", "auto-coding-skill"),
2397
- agentsDir: dest,
2398
- projectDir: path.dirname(parent),
2399
- };
2400
- }
2401
- if (path.basename(dest) === ".agents") {
2402
- return {
2403
- skillDir: path.join(dest, "skills", "auto-coding-skill"),
2404
- agentsDir: path.join(dest, "agents"),
2405
- projectDir: path.dirname(dest),
2406
- };
2407
- }
2408
- return {
2409
- skillDir: path.join(dest, ".agents", "skills", "auto-coding-skill"),
2410
- agentsDir: path.join(dest, ".agents", "agents"),
2411
- projectDir: dest,
2412
- };
166
+ const manifest = readManifest(root);
167
+ const errors = [];
168
+ if (!manifest) errors.push("managed install manifest is missing");
169
+ const entries = Array.isArray(manifest?.entries) ? manifest.entries : [];
170
+ for (const entry of entries) {
171
+ const target = path.join(root, ...entry.path.split("/"));
172
+ if (!exists(target)) errors.push(`missing managed file: ${entry.path}`);
173
+ else if (sha256(target) !== entry.sha256) errors.push(`modified managed file: ${entry.path}`);
2413
174
  }
2414
-
2415
- const root = mode === "project" ? projectRoot() : os.homedir();
2416
- return {
2417
- skillDir: path.join(root, ".agents", "skills", "auto-coding-skill"),
2418
- agentsDir: path.join(root, ".agents", "agents"),
2419
- projectDir: root,
2420
- };
175
+ const documents = Object.fromEntries(bootstrapDocs.map(([, target]) => [target, exists(path.join(root, target))]));
176
+ return { project: root, version: manifest?.skill_version || "", ok: errors.length === 0, errors, documents };
2421
177
  }
2422
178
 
2423
- function main(){
2424
- const args = parseArgs(process.argv);
2425
-
2426
- if (args.cmd === "help" || !args.cmd) {
2427
- console.log(`
2428
- autocoding - install auto-coding-skill into generic .agents paths
2429
-
2430
- Usage:
2431
- autocoding init [--mode project|global] [--dest <repo-root|.agents-dir|skill-dir>] [--reset-agent-models]
2432
- autocoding status --projects <path[,path...]> [--json]
2433
- autocoding sync --projects <path[,path...]> [--dry-run] [--json] [--reset-agent-models]
2434
- autocoding feedback --projects <path[,path...]> [--json]
2435
-
2436
- Examples:
2437
- autocoding init
2438
- autocoding status --projects /Users/elvis/Product/xjmate,/Users/elvis/Product/geesight
2439
- autocoding sync --projects /Users/elvis/Product/xjmate --dry-run
2440
- autocoding feedback --projects /Users/elvis/Product/xjmate,/Users/elvis/Product/geesight --json
2441
-
2442
- Compatibility:
2443
- --ai <value> is accepted for old scripts and ignored.
2444
- --force is accepted for old scripts; project init is already an idempotent full convergence.
2445
- Existing managed-agent model lines are preserved unless --reset-agent-models is used.
2446
- `);
2447
- process.exit(0);
2448
- }
2449
-
2450
- validateCommandArgs(args);
2451
-
2452
- const here = path.dirname(fileURLToPath(import.meta.url));
2453
- const packagedAssetSkill = path.resolve(here, "..", "assets", "skill");
2454
- const packagedAssetAgents = path.resolve(here, "..", "assets", "agents");
2455
- const assetManifest = path.resolve(here, "..", "assets", "managed-install.json");
2456
- const sourceAssetSkill = path.resolve(here, "..", "..", "src", "auto-coding-skill");
2457
- const sourceAssetAgents = path.resolve(here, "..", "..", "src", "agents");
2458
- const useSourceAssets = exists(sourceAssetSkill) && exists(sourceAssetAgents);
2459
- const assetSkill = useSourceAssets ? sourceAssetSkill : packagedAssetSkill;
2460
- const assetAgents = useSourceAssets ? sourceAssetAgents : packagedAssetAgents;
2461
- if (!exists(assetSkill)) die(`missing assets at ${assetSkill}`);
2462
- if (!exists(assetAgents)) die(`missing assets at ${assetAgents}`);
2463
- if (!exists(assetManifest)) die(`missing managed install manifest at ${assetManifest}`);
2464
- trustedProjectFileHelper = path.join(assetSkill, "scripts", "ap.py");
2465
- const releaseManifest = readInstallManifest(assetManifest);
2466
- if (releaseManifest.skill_version !== readPackageVersion()) {
2467
- die(`managed install manifest version ${releaseManifest.skill_version} does not match package ${readPackageVersion()}`);
2468
- }
2469
-
2470
- if (args.cmd === "feedback") {
2471
- const script = path.join(assetSkill, "scripts", "ap.py");
2472
- const command = [script, "feedback-collect"];
2473
- for (const project of args.projects) command.push("--project", project);
2474
- if (args.json) command.push("--json");
2475
- const result = spawnSync(runtimePython(), command, {
2476
- encoding: "utf8",
2477
- stdio: "pipe",
2478
- maxBuffer: 2 * 1024 * 1024,
2479
- });
2480
- if (result.error) {
2481
- const code = String(result.error.code || "spawn-error");
2482
- die(`feedback collector runtime failed: ${code}`);
2483
- }
2484
- if (result.signal) die(`feedback collector runtime stopped by signal: ${result.signal}`);
2485
- if (result.status !== 0) {
2486
- const detail = String(result.stderr || "feedback collection failed").trim();
2487
- die(detail || "feedback collection failed");
2488
- }
2489
- process.stdout.write(String(result.stdout || ""));
2490
- process.exit(0);
2491
- }
2492
-
2493
- if (args.cmd === "status") {
2494
- const projects = args.projects.length ? args.projects : [projectRoot()];
2495
- const results = projects.map(project => projectStatus(project, assetSkill, assetAgents, assetManifest, releaseManifest));
2496
- if (args.json) console.log(JSON.stringify({ version: readPackageVersion(), results }, null, 2));
2497
- else {
2498
- console.log(`[autocoding] version=${readPackageVersion()}`);
2499
- for (const result of results) printProjectStatus(result);
2500
- }
2501
- process.exit(results.every(result => result.ok) ? 0 : 2);
2502
- }
2503
-
2504
- if (args.cmd === "sync") {
2505
- const projects = args.projects.length ? args.projects : [projectRoot()];
2506
- const interrupted = projects
2507
- .map(project => path.resolve(project))
2508
- .filter(root => recoverInstallTransaction(root, false));
2509
- if (interrupted.length) {
2510
- if (args.dryRun) {
2511
- die(`dry-run cannot recover an interrupted install transaction: ${interrupted.join(", ")}`);
2512
- }
2513
- if (projects.length !== 1) {
2514
- die(
2515
- "multi-project sync remains zero-write when an interrupted install is present; "
2516
- + `recover it with a single-project sync first: ${interrupted.join(", ")}`,
2517
- );
2518
- }
2519
- recoverInstallTransaction(interrupted[0], true);
2520
- }
2521
- assertNoRegisteredTasks(projects);
2522
- const controlledPlans = new Map();
2523
- for (const project of projects) {
2524
- const root = path.resolve(project);
2525
- validateInstallTransactionInputs(root, assetSkill, assetManifest);
2526
- validateProjectManagedTargets(root, assetAgents);
2527
- const plans = planControlledDocuments(root, assetSkill);
2528
- plans.engineeringConvergence = runEngineeringConvergence(root, assetSkill, false);
2529
- plans.feedbackConvergence = runManagedScaffoldConvergence(root, assetSkill, "feedback", false);
2530
- for (const plan of [plans.engineering, plans.agents]) {
2531
- if (plan.archiveDocument) {
2532
- validateProjectFileTarget(root, plan.archiveDocument, "managed document archive");
2533
- }
2534
- }
2535
- for (const [document, plan] of Object.entries(plans)) {
2536
- if (document === "feedbackConvergence" || document === "engineeringConvergence") continue;
2537
- if (plan.state === "invalid" || plan.state === "conflict") {
2538
- const conflicts = (plan.conflicts || [])
2539
- .map(item => `${item.file}:${item.line} [${item.ruleId}] ${item.message}`)
2540
- .join("; ");
2541
- die(`refusing the entire sync batch before writes: ${root} ${document}: ${plan.detail || "invalid managed document"}${conflicts ? `; ${conflicts}` : ""}`);
2542
- }
2543
- }
2544
- controlledPlans.set(root, plans);
2545
- }
2546
- const results = projects.map(project => {
2547
- const root = path.resolve(project);
2548
- return syncProject(
2549
- root,
2550
- assetSkill,
2551
- assetAgents,
2552
- assetManifest,
2553
- releaseManifest,
2554
- args.dryRun,
2555
- args.resetAgentModels,
2556
- args.components,
2557
- controlledPlans.get(root) || null,
2558
- );
2559
- });
2560
- if (args.json) console.log(JSON.stringify({ version: readPackageVersion(), results }, null, 2));
2561
- else {
2562
- console.log(`[autocoding] version=${readPackageVersion()}`);
2563
- for (const result of results) {
2564
- console.log(`[autocoding] project=${result.project}`);
2565
- console.log(`[autocoding] dryRun=${result.dryRun}`);
2566
- console.log(`[autocoding] components=${result.components}`);
2567
- for (const item of result.actions) {
2568
- const detail = item.detail ? ` - ${item.detail}` : "";
2569
- console.log(`[autocoding] ${item.action}: ${item.path}${detail}`);
2570
- }
2571
- if (result.feedback?.available && result.feedback.actionRequiredCount) {
2572
- console.log(`[autocoding] feedback advisory: ${result.feedback.actionRequiredCount} report(s) need maintenance`);
2573
- } else if (result.feedback && !result.feedback.available) {
2574
- console.log(`[autocoding] feedback advisory: ${result.feedback.advisory}`);
2575
- }
2576
- }
2577
- }
2578
- process.exit(0);
2579
- }
2580
-
2581
- if (args.cmd !== "init") die(`unknown command: ${args.cmd}`);
2582
-
2583
- if (args.ai) console.warn("[autocoding] --ai is deprecated and ignored; installing generic .agents.");
2584
-
2585
- requireRuntimeDependencies(assetSkill);
2586
-
2587
- const { skillDir, agentsDir, projectDir } = resolveInstallDirs(args.mode, args.dest);
2588
- if (args.mode === "project") {
2589
- recoverInstallTransaction(projectDir, true);
2590
- assertNoRegisteredTasks([projectDir]);
2591
- const result = convergeProjectInstall(
2592
- projectDir,
2593
- assetSkill,
2594
- assetAgents,
2595
- assetManifest,
2596
- releaseManifest,
2597
- args.resetAgentModels,
2598
- );
2599
- console.log(`[autocoding] project=${result.project}`);
2600
- for (const item of result.actions) {
2601
- const detail = item.detail ? ` - ${item.detail}` : "";
2602
- console.log(`[autocoding] ${item.action}: ${item.path}${detail}`);
2603
- }
2604
- if (result.feedback?.available && result.feedback.actionRequiredCount) {
2605
- console.log(`[autocoding] feedback advisory: ${result.feedback.actionRequiredCount} report(s) need maintenance`);
2606
- } else if (result.feedback && !result.feedback.available) {
2607
- console.log(`[autocoding] feedback advisory: ${result.feedback.advisory}`);
2608
- }
2609
- console.log("[autocoding] next: fill any blank access.* values and validation.routes in docs/project/auto-coding-skill.yaml, then run doctor.");
2610
- } else {
2611
- rmrf(skillDir);
2612
- copyDir(assetSkill, skillDir);
2613
- syncManagedAgents(assetAgents, agentsDir, { resetModel: args.resetAgentModels, projectRoot: projectDir });
2614
- copyInstallManifest(assetManifest, projectDir);
2615
- applyManifestExecutableBits(projectDir, releaseManifest, "global");
2616
- const integrity = requireInstallIntegrity(projectDir, "global", releaseManifest.skill_version);
2617
- console.log(`[autocoding] installed skill to: ${skillDir}`);
2618
- console.log(`[autocoding] installed agents to: ${agentsDir}`);
2619
- console.log(`[autocoding] installed manifest to: ${installManifestTarget(projectDir)}`);
2620
- console.log(`[autocoding] verified managed install files: ${integrity.checked}`);
2621
- }
2622
- console.log("[autocoding] done.");
179
+ function help() {
180
+ console.log(`auto-coding-skill ${pkg.version}\n\nCommands:\n autocoding init [--dest PATH]\n autocoding sync [--projects PATH[,PATH...]]\n autocoding status [--projects PATH[,PATH...]] [--json]\n\nThese commands only install, preserve, and report documentation. They do not run or require Gates, reviews, tests, tasks, worktrees, or deployment checks.`);
2623
181
  }
2624
182
 
2625
- main();
183
+ const args = parseArgs(process.argv);
184
+ if (args.command === "help") help();
185
+ else if (args.command === "init") toJson(init(args.dest || process.cwd(), args), args.json);
186
+ else if (args.command === "sync") {
187
+ const projects = args.projects.length ? args.projects : [process.cwd()];
188
+ toJson({ version: pkg.version, results: projects.map(project => init(project, args)) }, args.json);
189
+ } else if (args.command === "status") {
190
+ const projects = args.projects.length ? args.projects : [process.cwd()];
191
+ const results = projects.map(status);
192
+ toJson({ version: pkg.version, results }, args.json);
193
+ if (results.some(result => !result.ok)) process.exitCode = 1;
194
+ } else fail(`unknown command: ${args.command}`);