@elvis1513/auto-coding-skill 4.2.8 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/src/index.js CHANGED
@@ -29,6 +29,7 @@ function parseArgs(argv){
29
29
  resetAgentModels: false,
30
30
  components: "all",
31
31
  projects: [],
32
+ projectsFlagProvided: false,
32
33
  provided: new Set(),
33
34
  };
34
35
  const [,, cmd, ...rest] = argv;
@@ -52,6 +53,7 @@ function parseArgs(argv){
52
53
  }
53
54
  else if (a === "--projects") {
54
55
  args.projects.push(...takeValue(rest, i, a).split(",").map(x => x.trim()).filter(Boolean));
56
+ args.projectsFlagProvided = true;
55
57
  args.provided.add("projects");
56
58
  i += 1;
57
59
  }
@@ -102,6 +104,7 @@ const COMMAND_ARGS = {
102
104
  init: new Set(["ai", "mode", "dest", "force", "resetAgentModels"]),
103
105
  status: new Set(["projects", "json"]),
104
106
  sync: new Set(["projects", "dryRun", "json", "resetAgentModels", "components"]),
107
+ feedback: new Set(["projects", "json"]),
105
108
  };
106
109
 
107
110
  function validateCommandArgs(args){
@@ -114,6 +117,9 @@ function validateCommandArgs(args){
114
117
  if (args.cmd === "sync" && args.components !== "all") {
115
118
  die("partial Skill sync was removed in 4.1; use --components all so Skill, AGENTS.md, ENGINEERING.md, agents, and runtime converge together");
116
119
  }
120
+ if (args.cmd === "feedback" && (!args.projectsFlagProvided || args.projects.length === 0)) {
121
+ die("'feedback' requires explicit --projects <path[,path...]>");
122
+ }
117
123
  }
118
124
 
119
125
  function exists(p){ try { fs.accessSync(p); return true; } catch { return false; } }
@@ -174,6 +180,20 @@ function copyInstallManifest(assetManifest, root){
174
180
  function applyManifestExecutableBits(root, manifest, mode){
175
181
  if (process.platform === "win32") return;
176
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
+ }
177
197
  for (const entry of manifest.entries) {
178
198
  if (!scopes.has(entry.scope) || typeof entry.path !== "string" || typeof entry.executable !== "boolean") continue;
179
199
  const target = path.join(root, ...entry.path.split("/"));
@@ -210,11 +230,18 @@ function requireInstallIntegrity(root, mode, expectedVersion){
210
230
  return result;
211
231
  }
212
232
 
213
- function runEngineeringConvergence(project, skillRoot, write){
233
+ function runEngineeringConvergence(project, skillRoot, write, installToken = "", transaction = null){
234
+ if (transaction) requireInstalledTransactionIntegrity(project, transaction);
214
235
  const script = path.join(skillRoot, "scripts", "ap.py");
215
236
  const command = [script, "--repo", project, "project-converge", "--json"];
216
237
  if (write) command.push("--write");
217
- const result = spawnSync(runtimePython(), command, { encoding: "utf8", stdio: "pipe" });
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
+ });
218
245
  if (result.status !== 0) {
219
246
  const detail = String(result.stderr || result.stdout || result.error?.message || "project convergence failed").trim();
220
247
  die(`unable to converge docs/ENGINEERING.md: ${detail}`);
@@ -225,6 +252,101 @@ function runEngineeringConvergence(project, skillRoot, write){
225
252
  die("project convergence returned invalid JSON");
226
253
  }
227
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
+ }
228
350
  function shouldSkip(name){
229
351
  return name === "__pycache__" || name === ".DS_Store" || /\.py[cod]$/i.test(name);
230
352
  }
@@ -240,12 +362,781 @@ function copyDir(src, dst){
240
362
  }
241
363
  }
242
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
+
243
1131
  function listFiles(root, base = root){
244
1132
  if (!exists(root)) return [];
245
1133
  const out = [];
246
1134
  for (const ent of fs.readdirSync(root, { withFileTypes: true })) {
247
1135
  if (shouldSkip(ent.name)) continue;
248
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
+ }
249
1140
  if (ent.isDirectory()) out.push(...listFiles(p, base));
250
1141
  else out.push(path.relative(base, p));
251
1142
  }
@@ -444,7 +1335,8 @@ function compareManagedAgents(assetAgents, agentsDir){
444
1335
  }
445
1336
 
446
1337
  function syncManagedAgents(assetAgents, agentsDir, options = {}){
447
- fs.mkdirSync(agentsDir, { recursive: true });
1338
+ const managedRoot = options.projectRoot || path.dirname(path.dirname(agentsDir));
1339
+ projectDirectoryChain(managedRoot, path.relative(path.resolve(managedRoot), path.resolve(agentsDir)), true);
448
1340
  const bindings = [];
449
1341
  const managedFiles = new Set(listFiles(assetAgents));
450
1342
  for (const rel of listFiles(assetAgents)) {
@@ -453,8 +1345,7 @@ function syncManagedAgents(assetAgents, agentsDir, options = {}){
453
1345
  const templateText = fs.readFileSync(src, "utf8");
454
1346
  const existingText = exists(dst) ? fs.readFileSync(dst, "utf8") : "";
455
1347
  const rendered = renderManagedAgent(templateText, existingText, options.resetModel === true);
456
- fs.mkdirSync(path.dirname(dst), { recursive: true });
457
- fs.writeFileSync(dst, rendered);
1348
+ atomicWriteProjectFile(managedRoot, dst, rendered);
458
1349
  const model = inspectTopLevelModel(rendered);
459
1350
  bindings.push({ agent: rel, model: model.present ? model.value : "inherit" });
460
1351
  }
@@ -474,38 +1365,16 @@ function copyMissingDocs(assetSkill, project){
474
1365
  const src = path.join(srcDocs, rel);
475
1366
  const dst = path.join(dstDocs, rel);
476
1367
  if (!exists(dst)) {
477
- fs.mkdirSync(path.dirname(dst), { recursive: true });
478
- fs.copyFileSync(src, dst);
1368
+ atomicCreateProjectFile(project, dst, fs.readFileSync(src));
479
1369
  copied.push(path.join("docs", rel));
480
1370
  }
481
1371
  }
482
1372
  return copied;
483
1373
  }
484
1374
 
485
- function inferredGateCommands(project){
486
- const pkg = path.join(project, "package.json");
487
- if (!exists(pkg)) return {};
488
- try {
489
- const parsed = JSON.parse(fs.readFileSync(pkg, "utf8"));
490
- const scripts = parsed?.scripts;
491
- if (!scripts || typeof scripts !== "object") return {};
492
- return typeof scripts["test:changed"] === "string" && scripts["test:changed"].trim()
493
- ? { project_fast: "npm run test:changed" }
494
- : {};
495
- } catch {
496
- return {};
497
- }
498
- }
499
-
500
1375
  function renderEngineeringTemplate(templateText, project){
501
- let rendered = templateText.replace(
502
- 'project:\n name: ""',
503
- `project:\n name: ${JSON.stringify(path.basename(path.resolve(project)))}`,
504
- );
505
- for (const [key, gate] of Object.entries(inferredGateCommands(project))) {
506
- rendered = rendered.replace(` ${key}: ""`, ` ${key}: ${JSON.stringify(gate)}`);
507
- }
508
- return rendered;
1376
+ void project;
1377
+ return templateText;
509
1378
  }
510
1379
 
511
1380
  const MANAGED_WORKFLOW_START_TOKEN = "auto-coding-skill:managed-workflow:start";
@@ -848,30 +1717,30 @@ function engineeringArchivePlan(root, current, version){
848
1717
  "",
849
1718
  "This file is historical and non-authoritative. Known duplicate workflow sections",
850
1719
  "were removed from docs/ENGINEERING.md. Move any still-current project facts into",
851
- "docs/ENGINEERING.md project-fact sections or docs/project/.",
1720
+ "docs/project/ and configuration into docs/project/auto-coding-skill.yaml.",
852
1721
  "",
853
1722
  "---",
854
1723
  "",
855
1724
  ].join("\n");
856
1725
  const archiveOutput = `${archiveHeader}${current}`;
857
1726
  const archiveDir = path.join(root, "docs", "archive", "workflow");
858
- let archiveDocument = path.join(archiveDir, `ENGINEERING.pre-${version}.md`);
859
- if (exists(archiveDocument) && fs.readFileSync(archiveDocument, "utf8") !== archiveOutput) {
860
- archiveDocument = path.join(
861
- archiveDir,
862
- `ENGINEERING.pre-${version}-${engineeringBodyHash(current).slice(0, 12)}.md`,
863
- );
864
- }
1727
+ const selected = selectProjectArchiveTarget(
1728
+ root,
1729
+ path.join(archiveDir, `ENGINEERING.pre-${version}.md`),
1730
+ archiveOutput,
1731
+ { legacyDigestPayload: current },
1732
+ );
865
1733
  return {
866
- archiveDocument,
1734
+ archiveDocument: selected.path,
867
1735
  archiveOutput,
868
- archiveRequired: !exists(archiveDocument),
1736
+ archiveRequired: selected.archiveRequired,
869
1737
  };
870
1738
  }
871
1739
 
872
1740
  function planAgentsDocumentSync(project, assetSkill, policy = loadWorkflowMigrationPolicy(assetSkill)){
873
1741
  const root = path.resolve(project);
874
1742
  const agentsDocument = path.join(root, "AGENTS.md");
1743
+ validateProjectFileTarget(root, agentsDocument, "root AGENTS.md");
875
1744
  const templatePath = path.join(assetSkill, "data", "templates", "bridges", "AGENTS.md");
876
1745
  const template = fs.readFileSync(templatePath, "utf8");
877
1746
  const templateRegion = inspectManagedAgentsDocument(template);
@@ -889,7 +1758,7 @@ function planAgentsDocumentSync(project, assetSkill, policy = loadWorkflowMigrat
889
1758
  `# Archived AGENTS.md before auto-coding-skill ${templateRegion.version}`,
890
1759
  "",
891
1760
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.",
892
- "Move any still-current project facts into docs/ENGINEERING.md or docs/project/",
1761
+ "Move any still-current project facts into docs/project/",
893
1762
  "without copying workflow rules back into the root AGENTS.md.",
894
1763
  "",
895
1764
  "---",
@@ -897,13 +1766,12 @@ function planAgentsDocumentSync(project, assetSkill, policy = loadWorkflowMigrat
897
1766
  ].join("\n");
898
1767
  const archiveOutput = `${archiveHeader}${current}`;
899
1768
  const archiveDir = path.join(root, "docs", "archive", "workflow");
900
- let archiveDocument = path.join(archiveDir, `AGENTS.pre-${templateRegion.version}.md`);
901
- if (exists(archiveDocument) && fs.readFileSync(archiveDocument, "utf8") !== archiveOutput) {
902
- archiveDocument = path.join(
903
- archiveDir,
904
- `AGENTS.pre-${templateRegion.version}-${engineeringBodyHash(current).slice(0, 12)}.md`,
905
- );
906
- }
1769
+ const selected = selectProjectArchiveTarget(
1770
+ root,
1771
+ path.join(archiveDir, `AGENTS.pre-${templateRegion.version}.md`),
1772
+ archiveOutput,
1773
+ { legacyDigestPayload: current },
1774
+ );
907
1775
  const currentRegion = inspectManagedAgentsDocument(current);
908
1776
  return {
909
1777
  state: currentRegion.state === "present" ? "stale" : "legacy-custom",
@@ -911,9 +1779,9 @@ function planAgentsDocumentSync(project, assetSkill, policy = loadWorkflowMigrat
911
1779
  ...(currentRegion.state === "present" ? { previousVersion: currentRegion.version } : {}),
912
1780
  output: template,
913
1781
  agentsDocument,
914
- archiveDocument,
1782
+ archiveDocument: selected.path,
915
1783
  archiveOutput,
916
- archiveRequired: !exists(archiveDocument),
1784
+ archiveRequired: selected.archiveRequired,
917
1785
  migrations: ["agents-whole-file-replacement"],
918
1786
  conflicts: [],
919
1787
  };
@@ -928,6 +1796,12 @@ function planControlledDocuments(project, assetSkill){
928
1796
  }
929
1797
 
930
1798
  function publicEngineeringPlan(plan){
1799
+ const publicConflicts = (plan.conflicts || []).map(conflict => ({
1800
+ ...(conflict.file ? { file: conflict.file } : {}),
1801
+ ...(Number.isInteger(conflict.line) ? { line: conflict.line } : {}),
1802
+ ...(conflict.ruleId ? { ruleId: conflict.ruleId } : {}),
1803
+ ...(conflict.message ? { message: conflict.message } : {}),
1804
+ }));
931
1805
  return {
932
1806
  state: plan.state,
933
1807
  version: plan.version || "unknown",
@@ -936,7 +1810,7 @@ function publicEngineeringPlan(plan){
936
1810
  ...(plan.preservedCustom ? { preservedCustom: true } : {}),
937
1811
  ...(plan.archiveDocument ? { archive: plan.archiveDocument } : {}),
938
1812
  ...(plan.migrations?.length ? { migrations: plan.migrations } : {}),
939
- ...(plan.conflicts?.length ? { conflicts: plan.conflicts } : {}),
1813
+ ...(publicConflicts.length ? { conflicts: publicConflicts } : {}),
940
1814
  ...(plan.detail ? { detail: plan.detail } : {}),
941
1815
  };
942
1816
  }
@@ -993,185 +1867,11 @@ function readPackageVersion(){
993
1867
  }
994
1868
  }
995
1869
 
996
- function extractFrontmatter(text){
997
- const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
998
- return match ? match[1] : "";
999
- }
1000
-
1001
- function frontmatterPathState(text, keyPath){
1002
- const frontmatter = extractFrontmatter(text);
1003
- if (!frontmatter) return { present: false, value: "" };
1004
-
1005
- const stack = [];
1006
- for (const rawLine of frontmatter.split(/\r?\n/)) {
1007
- if (!rawLine.trim() || rawLine.trim().startsWith("#")) continue;
1008
- const match = rawLine.match(/^(\s*)(["']?[^:"']+["']?)\s*:(.*)$/);
1009
- if (!match) continue;
1010
-
1011
- const indent = match[1].replace(/\t/g, " ").length;
1012
- const key = match[2].replace(/^["']|["']$/g, "").trim();
1013
- while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
1014
- const currentPath = [...stack.map(item => item.key), key];
1015
- if (currentPath.length === keyPath.length && currentPath.every((part, index) => part === keyPath[index])) {
1016
- return { present: true, value: match[3].trim() };
1017
- }
1018
- stack.push({ indent, key });
1019
- }
1020
- return { present: false, value: "" };
1021
- }
1022
-
1023
- function frontmatterSequenceHasItems(text, keyPath){
1024
- const frontmatter = extractFrontmatter(text);
1025
- if (!frontmatter) return false;
1026
- const lines = frontmatter.split(/\r?\n/);
1027
- const stack = [];
1028
- for (let index = 0; index < lines.length; index += 1) {
1029
- const rawLine = lines[index];
1030
- if (!rawLine.trim() || rawLine.trim().startsWith("#")) continue;
1031
- const match = rawLine.match(/^(\s*)(["']?[^:"']+["']?)\s*:(.*)$/);
1032
- if (!match) continue;
1033
- const indent = match[1].replace(/\t/g, " ").length;
1034
- const key = match[2].replace(/^["']|["']$/g, "").trim();
1035
- while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
1036
- const currentPath = [...stack.map(item => item.key), key];
1037
- if (currentPath.length === keyPath.length && currentPath.every((part, pathIndex) => part === keyPath[pathIndex])) {
1038
- const inline = match[3].trim();
1039
- if (/^\[(?:\s*[^\]])/.test(inline)) return true;
1040
- for (let child = index + 1; child < lines.length; child += 1) {
1041
- if (!lines[child].trim() || lines[child].trim().startsWith("#")) continue;
1042
- const childIndent = lines[child].match(/^\s*/)[0].replace(/\t/g, " ").length;
1043
- if (/^\s*-\s+\S/.test(lines[child]) && childIndent >= indent) return true;
1044
- if (childIndent <= indent) return false;
1045
- }
1046
- return false;
1047
- }
1048
- stack.push({ indent, key });
1049
- }
1050
- return false;
1051
- }
1052
-
1053
- function legacyGateEscalationTokens(text){
1054
- const frontmatter = extractFrontmatter(text);
1055
- if (!frontmatter) return [];
1056
- const tokens = [];
1057
- let gateIndent = null;
1058
- let rulesIndent = null;
1059
- for (const rawLine of frontmatter.split(/\r?\n/)) {
1060
- if (!rawLine.trim() || rawLine.trim().startsWith("#")) continue;
1061
- const indent = rawLine.match(/^\s*/)[0].replace(/\t/g, " ").length;
1062
- const match = rawLine.trim().match(/^(?:-\s*)?([A-Za-z0-9_-]+)\s*:(.*)$/);
1063
- if (gateIndent === null) {
1064
- if (match?.[1] === "gate") gateIndent = indent;
1065
- continue;
1066
- }
1067
- if (indent <= gateIndent) break;
1068
- if (rulesIndent !== null && indent <= rulesIndent) rulesIndent = null;
1069
- const key = match?.[1] || "";
1070
- const value = match?.[2]?.trim() || "";
1071
- if (key === "full_on") tokens.push("gate.full_on (legacy automatic full escalation)");
1072
- if (key === "full_on_unknown" && /^(?:true|yes|on|1)$/i.test(frontmatterScalarValue(value))) {
1073
- tokens.push("gate.full_on_unknown=true (legacy automatic full escalation)");
1074
- }
1075
- if (key === "rules") {
1076
- if (value && value !== "[]") tokens.push("gate.rules inline value (run upgrade to migrate safely)");
1077
- rulesIndent = indent;
1078
- continue;
1079
- }
1080
- if (rulesIndent !== null && indent > rulesIndent && (key === "scope" || key === "commands")) {
1081
- tokens.push(`gate.rules[].${key} (legacy automatic gate escalation)`);
1082
- }
1083
- }
1084
- return [...new Set(tokens)];
1085
- }
1086
-
1087
- function frontmatterValueIsFilled(raw){
1088
- const source = String(raw || "");
1089
- let quote = "";
1090
- let escaped = false;
1091
- let commentAt = -1;
1092
- for (let index = 0; index < source.length; index += 1) {
1093
- const char = source[index];
1094
- if (quote === '"' && char === "\\" && !escaped) {
1095
- escaped = true;
1096
- continue;
1097
- }
1098
- if ((char === '"' || char === "'") && !escaped) {
1099
- quote = quote === char ? "" : (quote || char);
1100
- } else if (char === "#" && !quote && (index === 0 || /\s/.test(source[index - 1]))) {
1101
- commentAt = index;
1102
- break;
1103
- }
1104
- escaped = false;
1105
- }
1106
- const value = (commentAt >= 0 ? source.slice(0, commentAt) : source).trim();
1107
- if (!value || value.startsWith("#")) return false;
1108
- const quoted = (
1109
- (value.startsWith('"') && value.endsWith('"'))
1110
- || (value.startsWith("'") && value.endsWith("'"))
1111
- );
1112
- const unquoted = quoted ? value.slice(1, -1).trim() : value;
1113
- let semanticValue = unquoted;
1114
- if (value.startsWith('"') && value.endsWith('"')) {
1115
- try {
1116
- semanticValue = JSON.parse(value).trim();
1117
- } catch {
1118
- // Be conservative for YAML-only escape sequences that this fast parser
1119
- // cannot decode consistently with PyYAML. Single quotes remain available
1120
- // for literal backslashes.
1121
- return false;
1122
- }
1123
- } else if (value.startsWith("'") && value.endsWith("'")) {
1124
- semanticValue = unquoted.replace(/''/g, "'").trim();
1125
- }
1126
- if (!semanticValue) return false;
1127
- if (!quoted && (
1128
- /^(?:null|true|false|yes|no|on|off|~)$/i.test(semanticValue)
1129
- || /^(?:\[|\{|\||>|&|\*|!)/.test(semanticValue)
1130
- || /^[+-]?(?:0b[01_]+|0o[0-7_]+|0x[\da-f_]+|\d[\d_]*(?:\.\d*)?(?:e[+-]?\d+)?|\.\d+(?:e[+-]?\d+)?|\.inf|\.nan)$/i.test(semanticValue)
1131
- || /^\d{4}-\d{1,2}-\d{1,2}(?:[Tt ]|$)/.test(semanticValue)
1132
- || /^\d+(?::\d+)+(?:\.\d+)?$/.test(semanticValue)
1133
- )) return false;
1134
- const upper = semanticValue.toUpperCase();
1135
- return ![
1136
- "N/A", "TODO", "TBD", "CHANGEME", "CHANGE_ME", "FILL_ME", "FILL-ME",
1137
- "PLACEHOLDER", "XXX", "NULL", "~",
1138
- ].includes(upper)
1139
- && !(semanticValue.startsWith("<") && semanticValue.endsWith(">"))
1140
- && !upper.startsWith("REPLACE_")
1141
- && !upper.startsWith("YOUR_");
1142
- }
1143
-
1144
- function frontmatterScalarValue(raw){
1145
- const source = String(raw || "");
1146
- let quote = "";
1147
- let escaped = false;
1148
- let commentAt = -1;
1149
- for (let index = 0; index < source.length; index += 1) {
1150
- const char = source[index];
1151
- if (quote === '"' && char === "\\" && !escaped) {
1152
- escaped = true;
1153
- continue;
1154
- }
1155
- if ((char === '"' || char === "'") && !escaped) {
1156
- quote = quote === char ? "" : (quote || char);
1157
- } else if (char === "#" && !quote && (index === 0 || /\s/.test(source[index - 1]))) {
1158
- commentAt = index;
1159
- break;
1160
- }
1161
- escaped = false;
1162
- }
1163
- const value = (commentAt >= 0 ? source.slice(0, commentAt) : source).trim();
1164
- if (value.startsWith('"') && value.endsWith('"')) {
1165
- try { return JSON.parse(value).trim(); } catch { return ""; }
1166
- }
1167
- if (value.startsWith("'") && value.endsWith("'")) {
1168
- return value.slice(1, -1).replace(/''/g, "'").trim();
1169
- }
1170
- return value;
1171
- }
1172
-
1173
1870
  function projectStatus(project, assetSkill, assetAgents, assetManifest, releaseManifest){
1174
1871
  const root = path.resolve(project);
1872
+ validateInstallTransactionInputs(root, assetSkill, assetManifest);
1873
+ validateProjectManagedTargets(root, assetAgents);
1874
+ const transactionPending = installTransactionPending(root);
1175
1875
  const skillDir = path.join(root, ".agents", "skills", "auto-coding-skill");
1176
1876
  const agentsDir = path.join(root, ".agents", "agents");
1177
1877
  const toolDir = path.join(root, "docs", "tools", "autopipeline");
@@ -1224,40 +1924,47 @@ function projectStatus(project, assetSkill, assetAgents, assetManifest, releaseM
1224
1924
  let missingConfigPaths = requiredConfigPaths.map(item => item.label);
1225
1925
  let unfilledConfigTokens = [];
1226
1926
  let invalidConfigTokens = [];
1227
- if (!engineeringMissing) {
1228
- const text = fs.readFileSync(engineering, "utf8");
1229
- const states = requiredConfigPaths.map(item => ({ item, state: frontmatterPathState(text, item.path) }));
1927
+ const effectiveConfig = readEffectiveConfigStatus(root, assetSkill);
1928
+ if (!engineeringMissing && effectiveConfig.ok) {
1929
+ const states = requiredConfigPaths.map(item => ({
1930
+ item,
1931
+ state: effectiveConfig.fields[item.label] || { present: false, configured: false, item_count: -1 },
1932
+ }));
1230
1933
  missingConfigPaths = states.filter(({ state }) => !state.present).map(({ item }) => item.label);
1231
1934
  unfilledConfigTokens = states
1232
1935
  .filter(({ item, state }) => state.present && (
1233
- (item.filled === true && !frontmatterValueIsFilled(state.value))
1234
- || (item.sequence === true && !frontmatterSequenceHasItems(text, item.path))
1936
+ (item.filled === true && !state.configured)
1937
+ || (item.sequence === true && state.item_count <= 0)
1235
1938
  ))
1236
1939
  .map(({ item }) => item.label);
1237
- const isolationState = frontmatterPathState(text, ["concurrency", "isolation"]);
1238
- if (isolationState.present && !["adaptive", "worktree"].includes(frontmatterScalarValue(isolationState.value).toLowerCase())) {
1940
+ const isolationState = effectiveConfig.fields["concurrency.isolation"] || {};
1941
+ if (isolationState.present && !["adaptive", "worktree"].includes(String(isolationState.value || "").toLowerCase())) {
1239
1942
  invalidConfigTokens.push("concurrency.isolation (must be adaptive or worktree)");
1240
1943
  }
1241
- for (const pathParts of [
1242
- ["validation", "max_command_seconds"],
1243
- ["validation", "max_total_seconds"],
1944
+ for (const label of [
1945
+ "validation.max_command_seconds",
1946
+ "validation.max_total_seconds",
1244
1947
  ]) {
1245
- const state = frontmatterPathState(text, pathParts);
1948
+ const state = effectiveConfig.fields[label] || {};
1246
1949
  if (!state.present) continue;
1247
- const value = Number(frontmatterScalarValue(state.value));
1950
+ const value = Number(state.value);
1248
1951
  if (!Number.isFinite(value) || value <= 0) {
1249
- invalidConfigTokens.push(`${pathParts.join(".")} (must be > 0)`);
1952
+ invalidConfigTokens.push(`${label} (must be > 0)`);
1250
1953
  }
1251
1954
  }
1252
- const commandState = frontmatterPathState(text, ["validation", "max_command_seconds"]);
1253
- const totalState = frontmatterPathState(text, ["validation", "max_total_seconds"]);
1254
- const commandBudget = Number(frontmatterScalarValue(commandState.value));
1255
- const totalBudget = Number(frontmatterScalarValue(totalState.value));
1955
+ const commandState = effectiveConfig.fields["validation.max_command_seconds"] || {};
1956
+ const totalState = effectiveConfig.fields["validation.max_total_seconds"] || {};
1957
+ const commandBudget = Number(commandState.value);
1958
+ const totalBudget = Number(totalState.value);
1256
1959
  if (commandState.present && totalState.present && Number.isFinite(commandBudget) && Number.isFinite(totalBudget) && commandBudget > totalBudget) {
1257
1960
  invalidConfigTokens.push("validation.max_command_seconds (cannot exceed max_total_seconds)");
1258
1961
  }
1259
- invalidConfigTokens.push(...legacyGateEscalationTokens(text));
1962
+ invalidConfigTokens.push(...(effectiveConfig.policy_issues || []));
1963
+ invalidConfigTokens.push(...(effectiveConfig.contract_issues || []));
1964
+ } else if (!engineeringMissing) {
1965
+ invalidConfigTokens.push(`effective configuration (${effectiveConfig.error || "invalid"})`);
1260
1966
  }
1967
+ invalidConfigTokens = [...new Set(invalidConfigTokens)];
1261
1968
  const missingConfigTokens = [...missingConfigPaths, ...unfilledConfigTokens, ...invalidConfigTokens];
1262
1969
  const scriptDiffs = [];
1263
1970
  const launcherSrc = path.join(assetSkill, "data", "templates", "tools", "ap.py");
@@ -1303,7 +2010,8 @@ function projectStatus(project, assetSkill, assetAgents, assetManifest, releaseM
1303
2010
  installManifestDiffs.push({ path: ".agents/managed-install.json", status: "stale" });
1304
2011
  }
1305
2012
  const installIntegrity = installIntegrityStatus(root, "project", releaseManifest.skill_version);
1306
- const ok = skillDiffs.length === 0
2013
+ const ok = !transactionPending
2014
+ && skillDiffs.length === 0
1307
2015
  && agentDiffs.length === 0
1308
2016
  && scriptDiffs.length === 0
1309
2017
  && installManifestDiffs.length === 0
@@ -1314,22 +2022,25 @@ function projectStatus(project, assetSkill, assetAgents, assetManifest, releaseM
1314
2022
  && managedWorkflow.state === "current"
1315
2023
  && managedAgentsDocument.state === "current";
1316
2024
  let next = "";
1317
- if (!exists(skillDir) || !exists(agentsDir)) {
2025
+ if (transactionPending) {
2026
+ next = "run autocoding init or a single-project autocoding sync to recover the interrupted install transaction";
2027
+ } else if (!exists(skillDir) || !exists(agentsDir)) {
1318
2028
  next = "run autocoding init";
1319
2029
  } else if (skillDiffs.length || agentDiffs.length || installManifestDiffs.length || !installIntegrity.ok) {
1320
2030
  next = "run autocoding init";
1321
2031
  } else if (engineeringMissing || managedWorkflow.state !== "current" || managedAgentsDocument.state !== "current" || scriptDiffs.length || missingDocs.length || docsDiffs.length) {
1322
2032
  next = "run autocoding init";
1323
2033
  } else if (missingConfigPaths.length) {
1324
- next = "run autocoding init, fill every required value in docs/ENGINEERING.md, then run doctor";
2034
+ next = "run autocoding init, fill every required value in docs/project/auto-coding-skill.yaml, then run doctor";
1325
2035
  } else if (invalidConfigTokens.length) {
1326
2036
  next = "run autocoding init, then run doctor";
1327
2037
  } else if (unfilledConfigTokens.length) {
1328
- next = "fill every required value in docs/ENGINEERING.md, then run project-local ap.py doctor";
2038
+ next = "fill every required value in docs/project/auto-coding-skill.yaml, then run project-local ap.py doctor";
1329
2039
  }
1330
2040
  return {
1331
2041
  project: root,
1332
2042
  ok,
2043
+ transactionPending,
1333
2044
  skillDiffs,
1334
2045
  agentDiffs,
1335
2046
  agentBindings: agentStatus.bindings,
@@ -1351,6 +2062,7 @@ function projectStatus(project, assetSkill, assetAgents, assetManifest, releaseM
1351
2062
  function printProjectStatus(result){
1352
2063
  console.log(`[autocoding] project=${result.project}`);
1353
2064
  console.log(`[autocoding] ok=${result.ok}`);
2065
+ if (result.transactionPending) console.log("[autocoding] install transaction: recovery required");
1354
2066
  for (const [label, items] of [["skill", result.skillDiffs], ["agents", result.agentDiffs], ["scripts", result.scriptDiffs]]) {
1355
2067
  for (const item of items) {
1356
2068
  const detail = item.detail ? ` - ${item.detail}` : "";
@@ -1391,57 +2103,82 @@ function syncProject(project, assetSkill, assetAgents, assetManifest, releaseMan
1391
2103
  const root = path.resolve(project);
1392
2104
  const actions = [];
1393
2105
  const skillDir = path.join(root, ".agents", "skills", "auto-coding-skill");
1394
- const skillOnly = components === "skill";
2106
+ const plans = controlledPlans || planControlledDocuments(root, assetSkill);
2107
+ let prepared = null;
2108
+ let transaction = null;
2109
+ if (!dryRun) safeProjectMutationRequired = true;
2110
+ if (dryRun) {
2111
+ const engineeringConvergence = plans.engineeringConvergence || runEngineeringConvergence(root, assetSkill, false);
2112
+ for (const item of engineeringConvergence.actions || []) {
2113
+ actions.push({
2114
+ ...item,
2115
+ action: String(item.action).startsWith("would-") ? item.action : `would-${item.action}`,
2116
+ });
2117
+ }
2118
+ } else {
2119
+ // Write only the project-owned overlay first. Keep the legacy ENGINEERING
2120
+ // bytes in place until the effective-config-aware runtime has been copied.
2121
+ prepared = runProjectConfigPrepare(root, assetSkill, true);
2122
+ actions.push(...prepared.actions);
2123
+ injectInstallFault("after-prepare");
2124
+ transaction = beginInstallTransaction(root, assetSkill, assetManifest, prepared);
2125
+ injectInstallFault("after-stage-copy");
2126
+ }
1395
2127
  actions.push({ action: dryRun ? "would-sync" : "sync", path: path.relative(root, skillDir) });
1396
2128
  actions.push({ action: dryRun ? "would-sync" : "sync", path: ".agents/managed-install.json" });
1397
2129
  if (!dryRun) {
1398
- rmrf(skillDir);
1399
- copyDir(assetSkill, skillDir);
1400
- copyInstallManifest(assetManifest, root);
2130
+ switchInstallTransaction(root, transaction);
2131
+ injectInstallFault("after-runtime-switch");
2132
+ if (prepared.finalize_required) {
2133
+ const finalized = runProjectConfigFinalize(
2134
+ root,
2135
+ skillDir,
2136
+ prepared,
2137
+ true,
2138
+ transaction.token,
2139
+ transaction,
2140
+ );
2141
+ actions.push(...finalized.actions);
2142
+ }
2143
+ injectInstallFault("after-config-finalize");
2144
+ // Complete exact managed-document convergence while the rollback backups
2145
+ // are still present, before unrelated managed files are touched.
2146
+ const convergence = runEngineeringConvergence(
2147
+ root,
2148
+ skillDir,
2149
+ true,
2150
+ transaction.token,
2151
+ transaction,
2152
+ );
2153
+ for (const item of convergence.actions || []) {
2154
+ if (actions.some(action => action.path === item.path && action.action === item.action)) continue;
2155
+ actions.push(item);
2156
+ }
1401
2157
  }
1402
- if (skillOnly) return { project: root, dryRun, components, actions };
1403
2158
 
1404
2159
  const agentsDir = path.join(root, ".agents", "agents");
1405
2160
  const toolDir = path.join(root, "docs", "tools", "autopipeline");
1406
- const plans = controlledPlans || planControlledDocuments(root, assetSkill);
1407
- const plan = plans.engineering;
1408
2161
  const agentsDocumentPlan = plans.agents;
1409
2162
  actions.push({ action: dryRun ? "would-sync" : "sync", path: path.relative(root, agentsDir) });
1410
2163
  actions.push({ action: dryRun ? "would-sync" : "sync", path: "docs/tools/autopipeline/ap.py" });
1411
2164
  if (!dryRun) {
1412
- syncManagedAgents(assetAgents, agentsDir, { resetModel: resetAgentModels });
1413
- fs.mkdirSync(toolDir, { recursive: true });
1414
- fs.copyFileSync(path.join(assetSkill, "data", "templates", "tools", "ap.py"), path.join(toolDir, "ap.py"));
2165
+ syncManagedAgents(assetAgents, agentsDir, { resetModel: resetAgentModels, projectRoot: root });
2166
+ atomicWriteProjectFile(
2167
+ root,
2168
+ path.join(toolDir, "ap.py"),
2169
+ fs.readFileSync(path.join(assetSkill, "data", "templates", "tools", "ap.py")),
2170
+ );
1415
2171
  for (const copied of copyMissingDocs(assetSkill, root)) actions.push({ action: "create", path: copied });
1416
- if (plan.state !== "current") {
1417
- if (plan.archiveRequired) {
1418
- fs.mkdirSync(path.dirname(plan.archiveDocument), { recursive: true });
1419
- fs.writeFileSync(plan.archiveDocument, plan.archiveOutput);
1420
- actions.push({
1421
- action: "archive",
1422
- path: path.relative(root, plan.archiveDocument),
1423
- detail: "previous ENGINEERING.md before duplicate workflow cleanup",
1424
- });
1425
- }
1426
- fs.mkdirSync(path.dirname(plan.engineering), { recursive: true });
1427
- fs.writeFileSync(plan.engineering, plan.output);
1428
- actions.push({
1429
- action: plan.state === "missing" ? "create" : "update",
1430
- path: path.join("docs", "ENGINEERING.md"),
1431
- detail: engineeringPlanDetail(plan),
1432
- });
1433
- }
1434
2172
  if (agentsDocumentPlan.state !== "current") {
1435
2173
  if (agentsDocumentPlan.archiveRequired) {
1436
- fs.mkdirSync(path.dirname(agentsDocumentPlan.archiveDocument), { recursive: true });
1437
- fs.writeFileSync(agentsDocumentPlan.archiveDocument, agentsDocumentPlan.archiveOutput);
2174
+ atomicCreateProjectFile(root, agentsDocumentPlan.archiveDocument, agentsDocumentPlan.archiveOutput);
1438
2175
  actions.push({
1439
2176
  action: "archive",
1440
2177
  path: path.relative(root, agentsDocumentPlan.archiveDocument),
1441
2178
  detail: "previous root AGENTS.md; historical and non-authoritative",
1442
2179
  });
1443
2180
  }
1444
- fs.writeFileSync(agentsDocumentPlan.agentsDocument, agentsDocumentPlan.output);
2181
+ atomicWriteProjectFile(root, agentsDocumentPlan.agentsDocument, agentsDocumentPlan.output);
1445
2182
  actions.push({
1446
2183
  action: agentsDocumentPlan.state === "missing" ? "create" : "update",
1447
2184
  path: "AGENTS.md",
@@ -1451,24 +2188,11 @@ function syncProject(project, assetSkill, assetAgents, assetManifest, releaseMan
1451
2188
  applyManifestExecutableBits(root, releaseManifest, "project");
1452
2189
  const integrity = requireInstallIntegrity(root, "project", releaseManifest.skill_version);
1453
2190
  actions.push({ action: "verify", path: ".agents/managed-install.json", detail: `${integrity.checked} managed files` });
2191
+ completeInstallTransaction(root, transaction);
1454
2192
  } else {
1455
2193
  for (const rel of CORE_DOCS) {
1456
2194
  if (!exists(path.join(root, "docs", rel))) actions.push({ action: "would-create", path: path.join("docs", rel) });
1457
2195
  }
1458
- if (plan.state !== "current") {
1459
- if (plan.archiveRequired) {
1460
- actions.push({
1461
- action: "would-archive",
1462
- path: path.relative(root, plan.archiveDocument),
1463
- detail: "previous ENGINEERING.md before duplicate workflow cleanup",
1464
- });
1465
- }
1466
- actions.push({
1467
- action: plan.state === "missing" ? "would-create" : "would-update",
1468
- path: path.join("docs", "ENGINEERING.md"),
1469
- detail: engineeringPlanDetail(plan),
1470
- });
1471
- }
1472
2196
  if (agentsDocumentPlan.state !== "current") {
1473
2197
  if (agentsDocumentPlan.archiveRequired) {
1474
2198
  actions.push({
@@ -1484,12 +2208,13 @@ function syncProject(project, assetSkill, assetAgents, assetManifest, releaseMan
1484
2208
  });
1485
2209
  }
1486
2210
  }
2211
+ const reportedPlans = dryRun ? plans : planControlledDocuments(root, assetSkill);
1487
2212
  return {
1488
2213
  project: root,
1489
2214
  dryRun,
1490
2215
  components,
1491
- managedWorkflow: publicEngineeringPlan(plan),
1492
- managedAgentsDocument: publicEngineeringPlan(agentsDocumentPlan),
2216
+ managedWorkflow: publicEngineeringPlan(reportedPlans.engineering),
2217
+ managedAgentsDocument: publicEngineeringPlan(reportedPlans.agents),
1493
2218
  actions,
1494
2219
  };
1495
2220
  }
@@ -1500,24 +2225,58 @@ function convergeProjectInstall(project, assetSkill, assetAgents, assetManifest,
1500
2225
  const agentsDir = path.join(root, ".agents", "agents");
1501
2226
  const toolDir = path.join(root, "docs", "tools", "autopipeline");
1502
2227
  const actions = [];
2228
+ safeProjectMutationRequired = true;
1503
2229
 
2230
+ recoverInstallTransaction(root, true);
2231
+ validateInstallTransactionInputs(root, assetSkill, assetManifest);
2232
+ validateProjectManagedTargets(root, assetAgents);
1504
2233
  // Validate the authoritative template and legacy input before the first write.
1505
2234
  runEngineeringConvergence(root, assetSkill, false);
1506
-
1507
- rmrf(skillDir);
1508
- copyDir(assetSkill, skillDir);
2235
+ // Materialize only the project-owned overlay while the previous installed
2236
+ // template is still available as the semantic diff base. Replacing the
2237
+ // managed document is deferred until the new runtime is in place.
2238
+ const prepared = runProjectConfigPrepare(root, assetSkill, true);
2239
+ actions.push(...prepared.actions);
2240
+ injectInstallFault("after-prepare");
2241
+ const transaction = beginInstallTransaction(root, assetSkill, assetManifest, prepared);
2242
+ injectInstallFault("after-stage-copy");
2243
+
2244
+ switchInstallTransaction(root, transaction);
1509
2245
  actions.push({ action: "replace", path: path.relative(root, skillDir) });
1510
-
1511
- copyInstallManifest(assetManifest, root);
1512
2246
  actions.push({ action: "replace", path: ".agents/managed-install.json" });
2247
+ injectInstallFault("after-runtime-switch");
2248
+
2249
+ if (prepared.finalize_required) {
2250
+ const finalized = runProjectConfigFinalize(
2251
+ root,
2252
+ skillDir,
2253
+ prepared,
2254
+ true,
2255
+ transaction.token,
2256
+ transaction,
2257
+ );
2258
+ actions.push(...finalized.actions);
2259
+ }
2260
+ injectInstallFault("after-config-finalize");
2261
+ const engineering = runEngineeringConvergence(
2262
+ root,
2263
+ skillDir,
2264
+ true,
2265
+ transaction.token,
2266
+ transaction,
2267
+ );
2268
+ for (const item of engineering.actions || []) {
2269
+ if (actions.some(action => action.path === item.path && action.action === item.action)) continue;
2270
+ actions.push(item);
2271
+ }
1513
2272
 
1514
- syncManagedAgents(assetAgents, agentsDir, { resetModel: resetAgentModels });
2273
+ syncManagedAgents(assetAgents, agentsDir, { resetModel: resetAgentModels, projectRoot: root });
1515
2274
  actions.push({ action: "sync", path: path.relative(root, agentsDir) });
1516
2275
 
1517
- fs.mkdirSync(toolDir, { recursive: true });
1518
- fs.copyFileSync(
1519
- path.join(assetSkill, "data", "templates", "tools", "ap.py"),
2276
+ atomicWriteProjectFile(
2277
+ root,
1520
2278
  path.join(toolDir, "ap.py"),
2279
+ fs.readFileSync(path.join(assetSkill, "data", "templates", "tools", "ap.py")),
1521
2280
  );
1522
2281
  actions.push({ action: "replace", path: "docs/tools/autopipeline/ap.py" });
1523
2282
 
@@ -1529,7 +2288,7 @@ function convergeProjectInstall(project, assetSkill, assetAgents, assetManifest,
1529
2288
  const currentAgents = exists(agentsDocument) ? fs.readFileSync(agentsDocument, "utf8") : "";
1530
2289
  if (currentAgents !== canonicalAgents) {
1531
2290
  if (currentAgents) {
1532
- let archive = path.join(
2291
+ const preferredArchive = path.join(
1533
2292
  root,
1534
2293
  ".agents",
1535
2294
  "archive",
@@ -1537,31 +2296,26 @@ function convergeProjectInstall(project, assetSkill, assetAgents, assetManifest,
1537
2296
  readPackageVersion(),
1538
2297
  "AGENTS.md",
1539
2298
  );
1540
- if (exists(archive) && fs.readFileSync(archive, "utf8") !== currentAgents) {
1541
- archive = path.join(
1542
- path.dirname(archive),
1543
- `AGENTS-${crypto.createHash("sha256").update(currentAgents).digest("hex").slice(0, 12)}.md`,
1544
- );
1545
- }
1546
- if (!exists(archive)) {
1547
- fs.mkdirSync(path.dirname(archive), { recursive: true });
1548
- fs.writeFileSync(archive, currentAgents);
2299
+ const selected = selectProjectArchiveTarget(root, preferredArchive, currentAgents, {
2300
+ legacyDigestPayload: currentAgents,
2301
+ });
2302
+ if (selected.archiveRequired) {
2303
+ atomicCreateProjectFile(root, selected.path, currentAgents);
1549
2304
  actions.push({
1550
2305
  action: "archive",
1551
- path: path.relative(root, archive),
2306
+ path: path.relative(root, selected.path),
1552
2307
  detail: "historical and non-authoritative",
1553
2308
  });
1554
2309
  }
1555
2310
  }
1556
- fs.writeFileSync(agentsDocument, canonicalAgents);
2311
+ atomicWriteProjectFile(root, agentsDocument, canonicalAgents);
1557
2312
  actions.push({ action: "replace", path: "AGENTS.md" });
1558
2313
  }
1559
2314
 
1560
- const engineering = runEngineeringConvergence(root, skillDir, true);
1561
- actions.push(...engineering.actions);
1562
2315
  applyManifestExecutableBits(root, releaseManifest, "project");
1563
2316
  const integrity = requireInstallIntegrity(root, "project", releaseManifest.skill_version);
1564
2317
  actions.push({ action: "verify", path: ".agents/managed-install.json", detail: `${integrity.checked} managed files` });
2318
+ completeInstallTransaction(root, transaction);
1565
2319
  return { project: root, actions };
1566
2320
  }
1567
2321
 
@@ -1628,11 +2382,13 @@ Usage:
1628
2382
  autocoding init [--mode project|global] [--dest <repo-root|.agents-dir|skill-dir>] [--reset-agent-models]
1629
2383
  autocoding status --projects <path[,path...]> [--json]
1630
2384
  autocoding sync --projects <path[,path...]> [--dry-run] [--json] [--reset-agent-models]
2385
+ autocoding feedback --projects <path[,path...]> [--json]
1631
2386
 
1632
2387
  Examples:
1633
2388
  autocoding init
1634
2389
  autocoding status --projects /Users/elvis/Product/xjmate,/Users/elvis/Product/geesight
1635
2390
  autocoding sync --projects /Users/elvis/Product/xjmate --dry-run
2391
+ autocoding feedback --projects /Users/elvis/Product/xjmate,/Users/elvis/Product/geesight --json
1636
2392
 
1637
2393
  Compatibility:
1638
2394
  --ai <value> is accepted for old scripts and ignored.
@@ -1656,11 +2412,35 @@ Compatibility:
1656
2412
  if (!exists(assetSkill)) die(`missing assets at ${assetSkill}`);
1657
2413
  if (!exists(assetAgents)) die(`missing assets at ${assetAgents}`);
1658
2414
  if (!exists(assetManifest)) die(`missing managed install manifest at ${assetManifest}`);
2415
+ trustedProjectFileHelper = path.join(assetSkill, "scripts", "ap.py");
1659
2416
  const releaseManifest = readInstallManifest(assetManifest);
1660
2417
  if (releaseManifest.skill_version !== readPackageVersion()) {
1661
2418
  die(`managed install manifest version ${releaseManifest.skill_version} does not match package ${readPackageVersion()}`);
1662
2419
  }
1663
2420
 
2421
+ if (args.cmd === "feedback") {
2422
+ const script = path.join(assetSkill, "scripts", "ap.py");
2423
+ const command = [script, "feedback-collect"];
2424
+ for (const project of args.projects) command.push("--project", project);
2425
+ if (args.json) command.push("--json");
2426
+ const result = spawnSync(runtimePython(), command, {
2427
+ encoding: "utf8",
2428
+ stdio: "pipe",
2429
+ maxBuffer: 2 * 1024 * 1024,
2430
+ });
2431
+ if (result.error) {
2432
+ const code = String(result.error.code || "spawn-error");
2433
+ die(`feedback collector runtime failed: ${code}`);
2434
+ }
2435
+ if (result.signal) die(`feedback collector runtime stopped by signal: ${result.signal}`);
2436
+ if (result.status !== 0) {
2437
+ const detail = String(result.stderr || "feedback collection failed").trim();
2438
+ die(detail || "feedback collection failed");
2439
+ }
2440
+ process.stdout.write(String(result.stdout || ""));
2441
+ process.exit(0);
2442
+ }
2443
+
1664
2444
  if (args.cmd === "status") {
1665
2445
  const projects = args.projects.length ? args.projects : [projectRoot()];
1666
2446
  const results = projects.map(project => projectStatus(project, assetSkill, assetAgents, assetManifest, releaseManifest));
@@ -1674,12 +2454,37 @@ Compatibility:
1674
2454
 
1675
2455
  if (args.cmd === "sync") {
1676
2456
  const projects = args.projects.length ? args.projects : [projectRoot()];
2457
+ const interrupted = projects
2458
+ .map(project => path.resolve(project))
2459
+ .filter(root => recoverInstallTransaction(root, false));
2460
+ if (interrupted.length) {
2461
+ if (args.dryRun) {
2462
+ die(`dry-run cannot recover an interrupted install transaction: ${interrupted.join(", ")}`);
2463
+ }
2464
+ if (projects.length !== 1) {
2465
+ die(
2466
+ "multi-project sync remains zero-write when an interrupted install is present; "
2467
+ + `recover it with a single-project sync first: ${interrupted.join(", ")}`,
2468
+ );
2469
+ }
2470
+ recoverInstallTransaction(interrupted[0], true);
2471
+ }
1677
2472
  assertNoRegisteredTasks(projects);
1678
2473
  const controlledPlans = new Map();
1679
2474
  for (const project of projects) {
1680
2475
  const root = path.resolve(project);
2476
+ validateInstallTransactionInputs(root, assetSkill, assetManifest);
2477
+ validateProjectManagedTargets(root, assetAgents);
1681
2478
  const plans = planControlledDocuments(root, assetSkill);
2479
+ plans.engineeringConvergence = runEngineeringConvergence(root, assetSkill, false);
2480
+ plans.feedbackConvergence = runManagedScaffoldConvergence(root, assetSkill, "feedback", false);
2481
+ for (const plan of [plans.engineering, plans.agents]) {
2482
+ if (plan.archiveDocument) {
2483
+ validateProjectFileTarget(root, plan.archiveDocument, "managed document archive");
2484
+ }
2485
+ }
1682
2486
  for (const [document, plan] of Object.entries(plans)) {
2487
+ if (document === "feedbackConvergence" || document === "engineeringConvergence") continue;
1683
2488
  if (plan.state === "invalid" || plan.state === "conflict") {
1684
2489
  const conflicts = (plan.conflicts || [])
1685
2490
  .map(item => `${item.file}:${item.line} [${item.ruleId}] ${item.message}`)
@@ -1727,6 +2532,7 @@ Compatibility:
1727
2532
 
1728
2533
  const { skillDir, agentsDir, projectDir } = resolveInstallDirs(args.mode, args.dest);
1729
2534
  if (args.mode === "project") {
2535
+ recoverInstallTransaction(projectDir, true);
1730
2536
  assertNoRegisteredTasks([projectDir]);
1731
2537
  const result = convergeProjectInstall(
1732
2538
  projectDir,
@@ -1741,11 +2547,11 @@ Compatibility:
1741
2547
  const detail = item.detail ? ` - ${item.detail}` : "";
1742
2548
  console.log(`[autocoding] ${item.action}: ${item.path}${detail}`);
1743
2549
  }
1744
- console.log("[autocoding] next: fill any blank access.* values and validation.routes in docs/ENGINEERING.md, then run doctor.");
2550
+ console.log("[autocoding] next: fill any blank access.* values and validation.routes in docs/project/auto-coding-skill.yaml, then run doctor.");
1745
2551
  } else {
1746
2552
  rmrf(skillDir);
1747
2553
  copyDir(assetSkill, skillDir);
1748
- syncManagedAgents(assetAgents, agentsDir, { resetModel: args.resetAgentModels });
2554
+ syncManagedAgents(assetAgents, agentsDir, { resetModel: args.resetAgentModels, projectRoot: projectDir });
1749
2555
  copyInstallManifest(assetManifest, projectDir);
1750
2556
  applyManifestExecutableBits(projectDir, releaseManifest, "global");
1751
2557
  const integrity = requireInstallIntegrity(projectDir, "global", releaseManifest.skill_version);