@elvis1513/auto-coding-skill 3.0.0 → 3.0.2

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
@@ -2,6 +2,8 @@
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import os from "node:os";
5
+ import crypto from "node:crypto";
6
+ import { execFileSync } from "node:child_process";
5
7
  import { fileURLToPath } from "node:url";
6
8
 
7
9
  function die(msg){
@@ -25,6 +27,7 @@ function parseArgs(argv){
25
27
  dryRun: false,
26
28
  json: false,
27
29
  resetAgentModels: false,
30
+ components: "all",
28
31
  projects: [],
29
32
  provided: new Set(),
30
33
  };
@@ -64,6 +67,11 @@ function parseArgs(argv){
64
67
  args.resetAgentModels = true;
65
68
  args.provided.add("resetAgentModels");
66
69
  }
70
+ else if (a === "--components") {
71
+ args.components = takeValue(rest, i, a).trim().toLowerCase();
72
+ args.provided.add("components");
73
+ i += 1;
74
+ }
67
75
  else if (a === "--force") {
68
76
  args.force = true;
69
77
  args.provided.add("force");
@@ -86,13 +94,14 @@ const ARG_FLAGS = {
86
94
  dryRun: "--dry-run",
87
95
  json: "--json",
88
96
  resetAgentModels: "--reset-agent-models",
97
+ components: "--components",
89
98
  projects: "--projects/positional project",
90
99
  };
91
100
 
92
101
  const COMMAND_ARGS = {
93
102
  init: new Set(["ai", "mode", "dest", "force", "resetAgentModels"]),
94
103
  status: new Set(["projects", "json"]),
95
- sync: new Set(["projects", "dryRun", "json", "resetAgentModels"]),
104
+ sync: new Set(["projects", "dryRun", "json", "resetAgentModels", "components"]),
96
105
  };
97
106
 
98
107
  function validateCommandArgs(args){
@@ -102,6 +111,12 @@ function validateCommandArgs(args){
102
111
  if (invalid.length) {
103
112
  die(`${invalid.map(name => ARG_FLAGS[name] || name).join(", ")} not valid for '${args.cmd}'`);
104
113
  }
114
+ if (args.cmd === "sync" && !["all", "skill"].includes(args.components)) {
115
+ die("--components must be 'all' or 'skill'");
116
+ }
117
+ if (args.cmd === "sync" && args.components === "skill" && args.resetAgentModels) {
118
+ die("--reset-agent-models cannot be used with --components skill");
119
+ }
105
120
  }
106
121
 
107
122
  function exists(p){ try { fs.accessSync(p); return true; } catch { return false; } }
@@ -364,19 +379,9 @@ function inferredGateCommands(project){
364
379
  const parsed = JSON.parse(fs.readFileSync(pkg, "utf8"));
365
380
  const scripts = parsed?.scripts;
366
381
  if (!scripts || typeof scripts !== "object") return {};
367
- const inferred = {};
368
- if (typeof scripts.test === "string" && scripts.test.trim()) {
369
- inferred.gate_changed = typeof scripts["test:changed"] === "string" && scripts["test:changed"].trim()
370
- ? "npm run test:changed"
371
- : "npm test";
372
- inferred.gate_standard = typeof scripts["test:standard"] === "string" && scripts["test:standard"].trim()
373
- ? "npm run test:standard"
374
- : "npm test";
375
- }
376
- if (typeof scripts["test:full"] === "string" && scripts["test:full"].trim()) {
377
- inferred.gate_full = "npm run test:full";
378
- }
379
- return inferred;
382
+ return typeof scripts["test:changed"] === "string" && scripts["test:changed"].trim()
383
+ ? { gate_changed: "npm run test:changed" }
384
+ : {};
380
385
  } catch {
381
386
  return {};
382
387
  }
@@ -388,11 +393,460 @@ function renderEngineeringTemplate(templateText, project){
388
393
  `project:\n name: ${JSON.stringify(path.basename(path.resolve(project)))}`,
389
394
  );
390
395
  for (const [key, gate] of Object.entries(inferredGateCommands(project))) {
391
- rendered = rendered.replace(` ${key}: ""`, ` ${key}: ${JSON.stringify(gate)}`);
396
+ rendered = rendered.replace(` ${key}: "git diff --check"`, ` ${key}: ${JSON.stringify(gate)}`);
392
397
  }
393
398
  return rendered;
394
399
  }
395
400
 
401
+ const MANAGED_WORKFLOW_START_TOKEN = "auto-coding-skill:managed-workflow:start";
402
+ const MANAGED_WORKFLOW_END_TOKEN = "auto-coding-skill:managed-workflow:end";
403
+ const MANAGED_WORKFLOW_START_RE = /<!--\s*auto-coding-skill:managed-workflow:start\s+version=([0-9]+\.[0-9]+\.[0-9]+)\s*-->/g;
404
+ const MANAGED_WORKFLOW_END_RE = /<!--\s*auto-coding-skill:managed-workflow:end\s*-->/g;
405
+ const MANAGED_AGENTS_START_TOKEN = "auto-coding-skill:managed-agents:start";
406
+ const MANAGED_AGENTS_END_TOKEN = "auto-coding-skill:managed-agents:end";
407
+ const MANAGED_AGENTS_START_RE = /<!--\s*auto-coding-skill:managed-agents:start\s+version=([0-9]+\.[0-9]+\.[0-9]+)\s*-->/g;
408
+ const MANAGED_AGENTS_END_RE = /<!--\s*auto-coding-skill:managed-agents:end\s*-->/g;
409
+
410
+ function tokenCount(text, token){
411
+ return text.split(token).length - 1;
412
+ }
413
+
414
+ function inspectManagedRegion(text, startToken, endToken, startPattern, endPattern, label){
415
+ const rawStarts = tokenCount(text, startToken);
416
+ const rawEnds = tokenCount(text, endToken);
417
+ if (rawStarts === 0 && rawEnds === 0) return { state: "absent" };
418
+
419
+ const starts = [...text.matchAll(startPattern)];
420
+ const ends = [...text.matchAll(endPattern)];
421
+ if (rawStarts !== starts.length || rawEnds !== ends.length) {
422
+ return { state: "invalid", detail: `managed ${label} marker is malformed` };
423
+ }
424
+ if (starts.length !== 1 || ends.length !== 1) {
425
+ return { state: "invalid", detail: `managed ${label} markers must contain exactly one start/end pair` };
426
+ }
427
+ const start = starts[0].index;
428
+ const end = ends[0].index;
429
+ if (start >= end) {
430
+ return { state: "invalid", detail: "managed workflow markers are out of order or nested" };
431
+ }
432
+ const endExclusive = end + ends[0][0].length;
433
+ return {
434
+ state: "present",
435
+ version: starts[0][1],
436
+ start,
437
+ endExclusive,
438
+ block: text.slice(start, endExclusive),
439
+ };
440
+ }
441
+
442
+ function inspectManagedWorkflow(text){
443
+ return inspectManagedRegion(
444
+ text,
445
+ MANAGED_WORKFLOW_START_TOKEN,
446
+ MANAGED_WORKFLOW_END_TOKEN,
447
+ MANAGED_WORKFLOW_START_RE,
448
+ MANAGED_WORKFLOW_END_RE,
449
+ "workflow",
450
+ );
451
+ }
452
+
453
+ function inspectManagedAgentsDocument(text){
454
+ return inspectManagedRegion(
455
+ text,
456
+ MANAGED_AGENTS_START_TOKEN,
457
+ MANAGED_AGENTS_END_TOKEN,
458
+ MANAGED_AGENTS_START_RE,
459
+ MANAGED_AGENTS_END_RE,
460
+ "agents",
461
+ );
462
+ }
463
+
464
+ function loadWorkflowMigrationPolicy(assetSkill){
465
+ const policyPath = path.join(assetSkill, "data", "policies", "workflow-migrations-v1.json");
466
+ let policy;
467
+ try {
468
+ policy = JSON.parse(fs.readFileSync(policyPath, "utf8"));
469
+ } catch (error) {
470
+ throw new Error(`invalid workflow migration policy ${policyPath}: ${error.message}`);
471
+ }
472
+ if (
473
+ policy?.schema_version !== 1
474
+ || !policy.managed_versions?.agents
475
+ || !policy.managed_versions?.engineering
476
+ || !Array.isArray(policy.known_official_agents_sha256)
477
+ || !Array.isArray(policy.known_official_engineering_body_sha256)
478
+ || !Array.isArray(policy.known_official_fragments)
479
+ || !Array.isArray(policy.conflict_rules)
480
+ ) {
481
+ throw new Error(`invalid workflow migration policy schema: ${policyPath}`);
482
+ }
483
+ return policy;
484
+ }
485
+
486
+ function escapeRegExp(text){
487
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
488
+ }
489
+
490
+ function applyKnownOfficialFragments(text, documentPath, policy){
491
+ let output = text;
492
+ const migrations = [];
493
+ for (const fragment of policy.known_official_fragments) {
494
+ if (!fragment.paths?.includes(documentPath) || !fragment.text) continue;
495
+ let pattern;
496
+ if (fragment.match === "exact-line") {
497
+ pattern = new RegExp(`^[\\t ]*${escapeRegExp(fragment.text.trim())}[\\t ]*(?:\\r?\\n|$)`, "gm");
498
+ } else if (fragment.match === "exact-block") {
499
+ const source = fragment.text.split("\n").map(escapeRegExp).join("\\r?\\n");
500
+ pattern = new RegExp(source, "g");
501
+ } else {
502
+ throw new Error(`unsupported workflow migration match '${fragment.match}' for ${fragment.id}`);
503
+ }
504
+ const replacement = typeof fragment.replacement === "string" ? fragment.replacement : "";
505
+ const updated = output.replace(pattern, matched => {
506
+ if (!replacement) return "";
507
+ if (fragment.match !== "exact-line") return replacement;
508
+ const eol = matched.endsWith("\r\n") ? "\r\n" : (matched.endsWith("\n") ? "\n" : "");
509
+ return `${replacement}${eol}`;
510
+ });
511
+ if (updated !== output) {
512
+ migrations.push(fragment.id);
513
+ output = updated;
514
+ }
515
+ }
516
+ return { output, migrations };
517
+ }
518
+
519
+ function scanWorkflowConflicts(text, documentPath, policy){
520
+ const conflicts = [];
521
+ const seen = new Set();
522
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
523
+ const candidates = lines.map((line, index) => ({ text: line, line: index + 1 }));
524
+ for (let index = 0; index < lines.length; index += 1) {
525
+ const line = lines[index];
526
+ if (!line.trim()) continue;
527
+ if (/^\s*(?:[-+*]|\d+\.)\s+/.test(line)) {
528
+ let end = index + 1;
529
+ while (end < lines.length && /^\s{2,}\S/.test(lines[end]) && !/^\s*(?:[-+*]|\d+\.)\s+/.test(lines[end])) end += 1;
530
+ if (end > index + 1) candidates.push({ text: lines.slice(index, end).join(" "), line: index + 1 });
531
+ continue;
532
+ }
533
+ if (/^\s*(?:#|\||```|~~~)/.test(line)) continue;
534
+ let end = index + 1;
535
+ while (end < lines.length && lines[end].trim() && !/^\s*(?:#|\||```|~~~|[-+*]|\d+\.)\s*/.test(lines[end])) end += 1;
536
+ if (end > index + 1) candidates.push({ text: lines.slice(index, end).join(" "), line: index + 1 });
537
+ }
538
+ for (const rule of policy.conflict_rules) {
539
+ if (!rule.paths?.includes(documentPath)) continue;
540
+ let pattern;
541
+ try {
542
+ pattern = new RegExp(rule.pattern, String(rule.flags || "").replaceAll("g", ""));
543
+ } catch (error) {
544
+ throw new Error(`invalid workflow conflict rule ${rule.id}: ${error.message}`);
545
+ }
546
+ for (const candidate of candidates) {
547
+ if (!pattern.test(candidate.text)) continue;
548
+ const key = `${rule.id}:${candidate.line}`;
549
+ if (seen.has(key)) continue;
550
+ seen.add(key);
551
+ conflicts.push({
552
+ file: documentPath,
553
+ line: candidate.line,
554
+ ruleId: rule.id,
555
+ message: rule.message,
556
+ excerpt: candidate.text.trim().slice(0, 240),
557
+ });
558
+ }
559
+ }
560
+ return conflicts;
561
+ }
562
+
563
+ function migrateDocumentText(text, documentPath, policy){
564
+ const migrated = applyKnownOfficialFragments(text, documentPath, policy);
565
+ return {
566
+ output: migrated.output,
567
+ migrations: migrated.migrations,
568
+ conflicts: scanWorkflowConflicts(migrated.output, documentPath, policy),
569
+ };
570
+ }
571
+
572
+ function replaceManagedBlock(text, region, block){
573
+ let before = text.slice(0, region.start);
574
+ let after = text.slice(region.endExclusive);
575
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
576
+ if (before && !/(?:\r?\n)$/.test(before)) before += eol;
577
+ if (after && !/^(?:\r?\n)/.test(after)) after = `${eol}${after}`;
578
+ return `${before}${block}${after}`;
579
+ }
580
+
581
+ function splitEngineeringDocument(text){
582
+ const frontmatter = text.match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/);
583
+ const bodyStart = frontmatter ? frontmatter[0].length : 0;
584
+ return { frontmatter: text.slice(0, bodyStart), body: text.slice(bodyStart) };
585
+ }
586
+
587
+ function engineeringBodyHash(body){
588
+ return crypto.createHash("sha256").update(body.replace(/\r\n/g, "\n")).digest("hex");
589
+ }
590
+
591
+ function insertManagedWorkflow(text, block){
592
+ const { frontmatter } = splitEngineeringDocument(text);
593
+ const bodyStart = frontmatter.length;
594
+ const body = text.slice(bodyStart);
595
+ const heading = /^# Engineering Workflow[^\r\n]*(?:\r?\n|$)/m.exec(body);
596
+ const insertion = heading ? bodyStart + heading.index + heading[0].length : bodyStart;
597
+ const before = text.slice(0, insertion);
598
+ const after = text.slice(insertion);
599
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
600
+ const left = before && !/(?:\r?\n)$/.test(before) ? `${before}${eol}` : before;
601
+ const right = after && !/^(?:\r?\n)/.test(after) ? `${eol}${after}` : after;
602
+ return `${left}${block}${right}`;
603
+ }
604
+
605
+ function lineCount(text){
606
+ return text ? text.replace(/\r\n/g, "\n").split("\n").length - 1 : 0;
607
+ }
608
+
609
+ function offsetConflicts(conflicts, offset){
610
+ return conflicts.map(conflict => ({ ...conflict, line: conflict.line + offset }));
611
+ }
612
+
613
+ function planEngineeringSync(project, assetSkill, policy = loadWorkflowMigrationPolicy(assetSkill)){
614
+ const root = path.resolve(project);
615
+ const engineering = path.join(root, "docs", "ENGINEERING.md");
616
+ const templatePath = path.join(assetSkill, "data", "templates", "ENGINEERING.md");
617
+ const renderedTemplate = renderEngineeringTemplate(fs.readFileSync(templatePath, "utf8"), root);
618
+ const templateRegion = inspectManagedWorkflow(renderedTemplate);
619
+ if (templateRegion.state !== "present") {
620
+ return { state: "invalid", detail: `packaged ENGINEERING template: ${templateRegion.detail || "managed workflow markers are missing"}` };
621
+ }
622
+ if (templateRegion.version !== policy.managed_versions.engineering) {
623
+ return { state: "invalid", detail: `packaged ENGINEERING version ${templateRegion.version} does not match migration policy ${policy.managed_versions.engineering}` };
624
+ }
625
+ if (!exists(engineering)) {
626
+ return { state: "missing", version: templateRegion.version, output: renderedTemplate, engineering, migrations: [], conflicts: [] };
627
+ }
628
+
629
+ const current = fs.readFileSync(engineering, "utf8");
630
+ const currentRegion = inspectManagedWorkflow(current);
631
+ if (currentRegion.state === "invalid") return { ...currentRegion, engineering };
632
+ if (currentRegion.state === "absent") {
633
+ const currentParts = splitEngineeringDocument(current);
634
+ const templateParts = splitEngineeringDocument(renderedTemplate);
635
+ const legacyHash = engineeringBodyHash(currentParts.body);
636
+ if (policy.known_official_engineering_body_sha256.includes(legacyHash)) {
637
+ return {
638
+ state: "legacy-official",
639
+ version: templateRegion.version,
640
+ previousBodyHash: legacyHash,
641
+ output: `${currentParts.frontmatter}${templateParts.body}`,
642
+ engineering,
643
+ migrations: [`engineering-body-sha256:${legacyHash}`],
644
+ conflicts: [],
645
+ };
646
+ }
647
+ const migrated = migrateDocumentText(currentParts.body, "docs/ENGINEERING.md", policy);
648
+ const conflicts = offsetConflicts(migrated.conflicts, lineCount(currentParts.frontmatter));
649
+ if (conflicts.length) {
650
+ return {
651
+ state: "conflict",
652
+ version: templateRegion.version,
653
+ engineering,
654
+ migrations: migrated.migrations,
655
+ conflicts,
656
+ detail: "unknown workflow directives conflict with the managed fast-gate policy",
657
+ };
658
+ }
659
+ return {
660
+ state: "legacy-custom",
661
+ version: templateRegion.version,
662
+ preservedCustom: true,
663
+ output: insertManagedWorkflow(`${currentParts.frontmatter}${migrated.output}`, templateRegion.block),
664
+ engineering,
665
+ migrations: migrated.migrations,
666
+ conflicts: [],
667
+ };
668
+ }
669
+ const beforeParts = splitEngineeringDocument(current.slice(0, currentRegion.start));
670
+ const migratedBefore = migrateDocumentText(beforeParts.body, "docs/ENGINEERING.md", policy);
671
+ const migratedAfter = migrateDocumentText(current.slice(currentRegion.endExclusive), "docs/ENGINEERING.md", policy);
672
+ const conflicts = [
673
+ ...offsetConflicts(migratedBefore.conflicts, lineCount(beforeParts.frontmatter)),
674
+ ...offsetConflicts(migratedAfter.conflicts, lineCount(current.slice(0, currentRegion.endExclusive))),
675
+ ];
676
+ const migrations = [...migratedBefore.migrations, ...migratedAfter.migrations];
677
+ if (conflicts.length) {
678
+ return {
679
+ state: "conflict",
680
+ version: templateRegion.version,
681
+ previousVersion: currentRegion.version,
682
+ engineering,
683
+ migrations,
684
+ conflicts,
685
+ detail: "unknown workflow directives conflict with the managed fast-gate policy",
686
+ };
687
+ }
688
+ const migratedCurrent = `${beforeParts.frontmatter}${migratedBefore.output}${currentRegion.block}${migratedAfter.output}`;
689
+ const migratedRegion = inspectManagedWorkflow(migratedCurrent);
690
+ const output = replaceManagedBlock(migratedCurrent, migratedRegion, templateRegion.block);
691
+ if (current === output) return { state: "current", version: templateRegion.version, output, engineering, migrations: [], conflicts: [] };
692
+ return {
693
+ state: "stale",
694
+ version: templateRegion.version,
695
+ previousVersion: currentRegion.version,
696
+ output,
697
+ engineering,
698
+ migrations,
699
+ conflicts: [],
700
+ };
701
+ }
702
+
703
+ function planAgentsDocumentSync(project, assetSkill, policy = loadWorkflowMigrationPolicy(assetSkill)){
704
+ const root = path.resolve(project);
705
+ const agentsDocument = path.join(root, "AGENTS.md");
706
+ const templatePath = path.join(assetSkill, "data", "templates", "bridges", "AGENTS.md");
707
+ const template = fs.readFileSync(templatePath, "utf8");
708
+ const templateRegion = inspectManagedAgentsDocument(template);
709
+ if (templateRegion.state !== "present" || templateRegion.version !== policy.managed_versions.agents) {
710
+ return { state: "invalid", detail: "packaged AGENTS template markers/version do not match the migration policy", agentsDocument };
711
+ }
712
+ if (!exists(agentsDocument)) {
713
+ return { state: "missing", version: templateRegion.version, output: template, agentsDocument, migrations: [], conflicts: [] };
714
+ }
715
+ const current = fs.readFileSync(agentsDocument, "utf8");
716
+ const currentHash = engineeringBodyHash(current);
717
+ if (policy.known_official_agents_sha256.includes(currentHash)) {
718
+ return {
719
+ state: "legacy-official",
720
+ version: templateRegion.version,
721
+ output: template,
722
+ agentsDocument,
723
+ migrations: [`agents-sha256:${currentHash}`],
724
+ conflicts: [],
725
+ };
726
+ }
727
+ const currentRegion = inspectManagedAgentsDocument(current);
728
+ if (currentRegion.state === "invalid") return { ...currentRegion, agentsDocument };
729
+ if (currentRegion.state === "absent") {
730
+ const migrated = migrateDocumentText(current, "AGENTS.md", policy);
731
+ if (migrated.conflicts.length) {
732
+ return {
733
+ state: "conflict",
734
+ version: templateRegion.version,
735
+ agentsDocument,
736
+ migrations: migrated.migrations,
737
+ conflicts: migrated.conflicts,
738
+ detail: "unknown workflow directives conflict with the managed fast-gate policy",
739
+ };
740
+ }
741
+ const separator = migrated.output ? (migrated.output.startsWith("\n") ? "" : "\n") : "";
742
+ return {
743
+ state: "legacy-custom",
744
+ version: templateRegion.version,
745
+ preservedCustom: true,
746
+ output: `${templateRegion.block}${separator}${migrated.output}`,
747
+ agentsDocument,
748
+ migrations: migrated.migrations,
749
+ conflicts: [],
750
+ };
751
+ }
752
+ const migratedBefore = migrateDocumentText(current.slice(0, currentRegion.start), "AGENTS.md", policy);
753
+ const migratedAfter = migrateDocumentText(current.slice(currentRegion.endExclusive), "AGENTS.md", policy);
754
+ const conflicts = [
755
+ ...migratedBefore.conflicts,
756
+ ...offsetConflicts(migratedAfter.conflicts, lineCount(current.slice(0, currentRegion.endExclusive))),
757
+ ];
758
+ const migrations = [...migratedBefore.migrations, ...migratedAfter.migrations];
759
+ if (conflicts.length) {
760
+ return {
761
+ state: "conflict",
762
+ version: templateRegion.version,
763
+ previousVersion: currentRegion.version,
764
+ agentsDocument,
765
+ migrations,
766
+ conflicts,
767
+ detail: "unknown workflow directives conflict with the managed fast-gate policy",
768
+ };
769
+ }
770
+ const migratedCurrent = `${migratedBefore.output}${currentRegion.block}${migratedAfter.output}`;
771
+ const migratedRegion = inspectManagedAgentsDocument(migratedCurrent);
772
+ const output = replaceManagedBlock(migratedCurrent, migratedRegion, templateRegion.block);
773
+ if (current === output) return { state: "current", version: templateRegion.version, output, agentsDocument, migrations: [], conflicts: [] };
774
+ return {
775
+ state: "stale",
776
+ version: templateRegion.version,
777
+ previousVersion: currentRegion.version,
778
+ output,
779
+ agentsDocument,
780
+ migrations,
781
+ conflicts: [],
782
+ };
783
+ }
784
+
785
+ function planControlledDocuments(project, assetSkill){
786
+ const policy = loadWorkflowMigrationPolicy(assetSkill);
787
+ return {
788
+ engineering: planEngineeringSync(project, assetSkill, policy),
789
+ agents: planAgentsDocumentSync(project, assetSkill, policy),
790
+ };
791
+ }
792
+
793
+ function publicEngineeringPlan(plan){
794
+ return {
795
+ state: plan.state,
796
+ version: plan.version || "unknown",
797
+ ...(plan.previousVersion ? { previousVersion: plan.previousVersion } : {}),
798
+ ...(plan.previousBodyHash ? { previousBodyHash: plan.previousBodyHash } : {}),
799
+ ...(plan.preservedCustom ? { preservedCustom: true } : {}),
800
+ ...(plan.migrations?.length ? { migrations: plan.migrations } : {}),
801
+ ...(plan.conflicts?.length ? { conflicts: plan.conflicts } : {}),
802
+ ...(plan.detail ? { detail: plan.detail } : {}),
803
+ };
804
+ }
805
+
806
+ function registeredLegacyTasks(project){
807
+ const root = path.resolve(project);
808
+ let commonDir;
809
+ try {
810
+ const raw = execFileSync("git", ["-C", root, "rev-parse", "--git-common-dir"], {
811
+ encoding: "utf8",
812
+ stdio: ["ignore", "pipe", "ignore"],
813
+ }).trim();
814
+ commonDir = path.resolve(root, raw);
815
+ } catch {
816
+ return [];
817
+ }
818
+ const tasksDir = path.join(commonDir, "auto-coding-skill", "tasks");
819
+ if (!exists(tasksDir)) return [];
820
+ const legacy = [];
821
+ for (const entry of fs.readdirSync(tasksDir, { withFileTypes: true })) {
822
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
823
+ const manifestPath = path.join(tasksDir, entry.name);
824
+ let manifest;
825
+ try {
826
+ manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
827
+ } catch {
828
+ legacy.push({ project: root, manifest: entry.name, schema: "invalid" });
829
+ continue;
830
+ }
831
+ const schema = Number(manifest?.schema ?? 0);
832
+ if (!Number.isFinite(schema) || schema < 2) {
833
+ legacy.push({ project: root, manifest: entry.name, schema: Number.isFinite(schema) ? schema : "invalid" });
834
+ }
835
+ }
836
+ return legacy;
837
+ }
838
+
839
+ function assertNoLegacyRegisteredTasks(projects){
840
+ const legacy = projects.flatMap(project => registeredLegacyTasks(project));
841
+ if (!legacy.length) return;
842
+ const locations = legacy.map(item => `${item.project}:${item.manifest}(schema=${item.schema})`).join(", ");
843
+ die(
844
+ "refusing the entire sync batch because registered auto-coding tasks use schema < 2: "
845
+ + `${locations}\nFinish, integrate, and clean these tasks with the currently installed 3.0.0 runtime before upgrading. `
846
+ + "sync will not infer or auto-claim owned paths for legacy tasks.",
847
+ );
848
+ }
849
+
396
850
  function readPackageVersion(){
397
851
  const here = path.dirname(fileURLToPath(import.meta.url));
398
852
  const pkgPath = path.resolve(here, "..", "..", "package.json");
@@ -408,14 +862,14 @@ function extractFrontmatter(text){
408
862
  return match ? match[1] : "";
409
863
  }
410
864
 
411
- function frontmatterHasPath(text, keyPath){
865
+ function frontmatterPathState(text, keyPath){
412
866
  const frontmatter = extractFrontmatter(text);
413
- if (!frontmatter) return false;
867
+ if (!frontmatter) return { present: false, value: "" };
414
868
 
415
869
  const stack = [];
416
870
  for (const rawLine of frontmatter.split(/\r?\n/)) {
417
871
  if (!rawLine.trim() || rawLine.trim().startsWith("#")) continue;
418
- const match = rawLine.match(/^(\s*)(["']?[^:"']+["']?)\s*:/);
872
+ const match = rawLine.match(/^(\s*)(["']?[^:"']+["']?)\s*:(.*)$/);
419
873
  if (!match) continue;
420
874
 
421
875
  const indent = match[1].replace(/\t/g, " ").length;
@@ -423,11 +877,130 @@ function frontmatterHasPath(text, keyPath){
423
877
  while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
424
878
  const currentPath = [...stack.map(item => item.key), key];
425
879
  if (currentPath.length === keyPath.length && currentPath.every((part, index) => part === keyPath[index])) {
426
- return true;
880
+ return { present: true, value: match[3].trim() };
427
881
  }
428
882
  stack.push({ indent, key });
429
883
  }
430
- return false;
884
+ return { present: false, value: "" };
885
+ }
886
+
887
+ function legacyGateEscalationTokens(text){
888
+ const frontmatter = extractFrontmatter(text);
889
+ if (!frontmatter) return [];
890
+ const tokens = [];
891
+ let gateIndent = null;
892
+ let rulesIndent = null;
893
+ for (const rawLine of frontmatter.split(/\r?\n/)) {
894
+ if (!rawLine.trim() || rawLine.trim().startsWith("#")) continue;
895
+ const indent = rawLine.match(/^\s*/)[0].replace(/\t/g, " ").length;
896
+ const match = rawLine.trim().match(/^(?:-\s*)?([A-Za-z0-9_-]+)\s*:(.*)$/);
897
+ if (gateIndent === null) {
898
+ if (match?.[1] === "gate") gateIndent = indent;
899
+ continue;
900
+ }
901
+ if (indent <= gateIndent) break;
902
+ if (rulesIndent !== null && indent <= rulesIndent) rulesIndent = null;
903
+ const key = match?.[1] || "";
904
+ const value = match?.[2]?.trim() || "";
905
+ if (key === "full_on") tokens.push("gate.full_on (legacy automatic full escalation)");
906
+ if (key === "full_on_unknown" && /^(?:true|yes|on|1)(?:\s+#.*)?$/i.test(value)) {
907
+ tokens.push("gate.full_on_unknown=true (legacy automatic full escalation)");
908
+ }
909
+ if (key === "rules") {
910
+ rulesIndent = indent;
911
+ continue;
912
+ }
913
+ if (rulesIndent !== null && indent > rulesIndent && (key === "scope" || key === "commands")) {
914
+ tokens.push(`gate.rules[].${key} (legacy automatic gate escalation)`);
915
+ }
916
+ }
917
+ return [...new Set(tokens)];
918
+ }
919
+
920
+ function frontmatterValueIsFilled(raw){
921
+ const source = String(raw || "");
922
+ let quote = "";
923
+ let escaped = false;
924
+ let commentAt = -1;
925
+ for (let index = 0; index < source.length; index += 1) {
926
+ const char = source[index];
927
+ if (quote === '"' && char === "\\" && !escaped) {
928
+ escaped = true;
929
+ continue;
930
+ }
931
+ if ((char === '"' || char === "'") && !escaped) {
932
+ quote = quote === char ? "" : (quote || char);
933
+ } else if (char === "#" && !quote && (index === 0 || /\s/.test(source[index - 1]))) {
934
+ commentAt = index;
935
+ break;
936
+ }
937
+ escaped = false;
938
+ }
939
+ const value = (commentAt >= 0 ? source.slice(0, commentAt) : source).trim();
940
+ if (!value || value.startsWith("#")) return false;
941
+ const quoted = (
942
+ (value.startsWith('"') && value.endsWith('"'))
943
+ || (value.startsWith("'") && value.endsWith("'"))
944
+ );
945
+ const unquoted = quoted ? value.slice(1, -1).trim() : value;
946
+ let semanticValue = unquoted;
947
+ if (value.startsWith('"') && value.endsWith('"')) {
948
+ try {
949
+ semanticValue = JSON.parse(value).trim();
950
+ } catch {
951
+ // Be conservative for YAML-only escape sequences that this fast parser
952
+ // cannot decode consistently with PyYAML. Single quotes remain available
953
+ // for literal backslashes.
954
+ return false;
955
+ }
956
+ } else if (value.startsWith("'") && value.endsWith("'")) {
957
+ semanticValue = unquoted.replace(/''/g, "'").trim();
958
+ }
959
+ if (!semanticValue) return false;
960
+ if (!quoted && (
961
+ /^(?:null|true|false|yes|no|on|off|~)$/i.test(semanticValue)
962
+ || /^(?:\[|\{|\||>|&|\*|!)/.test(semanticValue)
963
+ || /^[+-]?(?:0b[01_]+|0o[0-7_]+|0x[\da-f_]+|\d[\d_]*(?:\.\d*)?(?:e[+-]?\d+)?|\.\d+(?:e[+-]?\d+)?|\.inf|\.nan)$/i.test(semanticValue)
964
+ || /^\d{4}-\d{1,2}-\d{1,2}(?:[Tt ]|$)/.test(semanticValue)
965
+ || /^\d+(?::\d+)+(?:\.\d+)?$/.test(semanticValue)
966
+ )) return false;
967
+ const upper = semanticValue.toUpperCase();
968
+ return ![
969
+ "N/A", "TODO", "TBD", "CHANGEME", "CHANGE_ME", "FILL_ME", "FILL-ME",
970
+ "PLACEHOLDER", "XXX", "NULL", "~",
971
+ ].includes(upper)
972
+ && !(semanticValue.startsWith("<") && semanticValue.endsWith(">"))
973
+ && !upper.startsWith("REPLACE_")
974
+ && !upper.startsWith("YOUR_");
975
+ }
976
+
977
+ function frontmatterScalarValue(raw){
978
+ const source = String(raw || "");
979
+ let quote = "";
980
+ let escaped = false;
981
+ let commentAt = -1;
982
+ for (let index = 0; index < source.length; index += 1) {
983
+ const char = source[index];
984
+ if (quote === '"' && char === "\\" && !escaped) {
985
+ escaped = true;
986
+ continue;
987
+ }
988
+ if ((char === '"' || char === "'") && !escaped) {
989
+ quote = quote === char ? "" : (quote || char);
990
+ } else if (char === "#" && !quote && (index === 0 || /\s/.test(source[index - 1]))) {
991
+ commentAt = index;
992
+ break;
993
+ }
994
+ escaped = false;
995
+ }
996
+ const value = (commentAt >= 0 ? source.slice(0, commentAt) : source).trim();
997
+ if (value.startsWith('"') && value.endsWith('"')) {
998
+ try { return JSON.parse(value).trim(); } catch { return ""; }
999
+ }
1000
+ if (value.startsWith("'") && value.endsWith("'")) {
1001
+ return value.slice(1, -1).replace(/''/g, "'").trim();
1002
+ }
1003
+ return value;
431
1004
  }
432
1005
 
433
1006
  function projectStatus(project, assetSkill, assetAgents){
@@ -437,9 +1010,15 @@ function projectStatus(project, assetSkill, assetAgents){
437
1010
  const toolDir = path.join(root, "docs", "tools", "autopipeline");
438
1011
  const engineering = path.join(root, "docs", "ENGINEERING.md");
439
1012
  const engineeringMissing = !exists(engineering);
1013
+ const controlledPlans = planControlledDocuments(root, assetSkill);
1014
+ const engineeringPlan = controlledPlans.engineering;
1015
+ const agentsDocumentPlan = controlledPlans.agents;
1016
+ const managedWorkflow = publicEngineeringPlan(engineeringPlan);
1017
+ const managedAgentsDocument = publicEngineeringPlan(agentsDocumentPlan);
440
1018
  const requiredConfigPaths = [
441
1019
  { label: "workflow.mode", path: ["workflow", "mode"] },
442
1020
  { label: "workflow.profile", path: ["workflow", "profile"] },
1021
+ { label: "workflow.completion", path: ["workflow", "completion"] },
443
1022
  { label: "concurrency.isolation", path: ["concurrency", "isolation"] },
444
1023
  { label: "concurrency.base_ref", path: ["concurrency", "base_ref"] },
445
1024
  { label: "concurrency.target_branch", path: ["concurrency", "target_branch"] },
@@ -448,22 +1027,48 @@ function projectStatus(project, assetSkill, assetAgents){
448
1027
  { label: "concurrency.cleanup_merged", path: ["concurrency", "cleanup_merged"] },
449
1028
  { label: "concurrency.delete_remote_branch", path: ["concurrency", "delete_remote_branch"] },
450
1029
  { label: "concurrency.disposable_ignored", path: ["concurrency", "disposable_ignored"] },
451
- { label: "project.name", path: ["project", "name"] },
452
- { label: "verification.target_env_required", path: ["verification", "target_env_required"] },
453
- { label: "verification.jenkins_required", path: ["verification", "jenkins_required"] },
1030
+ { label: "project.name", path: ["project", "name"], filled: true },
1031
+ { label: "access.project.frontend.url", path: ["access", "project", "frontend", "url"], filled: true },
1032
+ { label: "access.project.frontend.username", path: ["access", "project", "frontend", "username"], filled: true },
1033
+ { label: "access.project.frontend.password", path: ["access", "project", "frontend", "password"], filled: true },
1034
+ { label: "access.project.backend.url", path: ["access", "project", "backend", "url"], filled: true },
1035
+ { label: "access.project.backend.username", path: ["access", "project", "backend", "username"], filled: true },
1036
+ { label: "access.project.backend.password", path: ["access", "project", "backend", "password"], filled: true },
1037
+ { label: "access.jenkins.frontend.url", path: ["access", "jenkins", "frontend", "url"], filled: true },
1038
+ { label: "access.jenkins.frontend.username", path: ["access", "jenkins", "frontend", "username"], filled: true },
1039
+ { label: "access.jenkins.frontend.password", path: ["access", "jenkins", "frontend", "password"], filled: true },
1040
+ { label: "access.jenkins.backend.url", path: ["access", "jenkins", "backend", "url"], filled: true },
1041
+ { label: "access.jenkins.backend.username", path: ["access", "jenkins", "backend", "username"], filled: true },
1042
+ { label: "access.jenkins.backend.password", path: ["access", "jenkins", "backend", "password"], filled: true },
1043
+ { label: "access.gitlab.url", path: ["access", "gitlab", "url"], filled: true },
1044
+ { label: "access.gitlab.username", path: ["access", "gitlab", "username"], filled: true },
1045
+ { label: "access.gitlab.password", path: ["access", "gitlab", "password"], filled: true },
1046
+ { label: "access.nexus.frontend.url", path: ["access", "nexus", "frontend", "url"], filled: true },
1047
+ { label: "access.nexus.frontend.username", path: ["access", "nexus", "frontend", "username"], filled: true },
1048
+ { label: "access.nexus.frontend.password", path: ["access", "nexus", "frontend", "password"], filled: true },
454
1049
  { label: "docs.taskbook", path: ["docs", "taskbook"] },
455
1050
  { label: "docs.closure_log", path: ["docs", "closure_log"] },
456
1051
  { label: "docs.active_task_dir", path: ["docs", "active_task_dir"] },
457
1052
  { label: "docs.task_closure_dir", path: ["docs", "task_closure_dir"] },
458
1053
  { label: "docs.task_evidence_dir", path: ["docs", "task_evidence_dir"] },
459
1054
  ];
460
- let missingConfigTokens = requiredConfigPaths.map(item => item.label);
1055
+ let missingConfigPaths = requiredConfigPaths.map(item => item.label);
1056
+ let unfilledConfigTokens = [];
1057
+ let invalidConfigTokens = [];
461
1058
  if (!engineeringMissing) {
462
1059
  const text = fs.readFileSync(engineering, "utf8");
463
- missingConfigTokens = requiredConfigPaths
464
- .filter(item => !frontmatterHasPath(text, item.path))
465
- .map(item => item.label);
1060
+ const states = requiredConfigPaths.map(item => ({ item, state: frontmatterPathState(text, item.path) }));
1061
+ missingConfigPaths = states.filter(({ state }) => !state.present).map(({ item }) => item.label);
1062
+ unfilledConfigTokens = states
1063
+ .filter(({ item, state }) => state.present && item.filled === true && !frontmatterValueIsFilled(state.value))
1064
+ .map(({ item }) => item.label);
1065
+ const isolationState = frontmatterPathState(text, ["concurrency", "isolation"]);
1066
+ if (isolationState.present && frontmatterScalarValue(isolationState.value).toLowerCase() !== "worktree") {
1067
+ invalidConfigTokens.push("concurrency.isolation (must be worktree)");
1068
+ }
1069
+ invalidConfigTokens.push(...legacyGateEscalationTokens(text));
466
1070
  }
1071
+ const missingConfigTokens = [...missingConfigPaths, ...unfilledConfigTokens, ...invalidConfigTokens];
467
1072
  const scriptDiffs = [];
468
1073
  const launcherSrc = path.join(assetSkill, "data", "templates", "tools", "ap.py");
469
1074
  const launcherDst = path.join(toolDir, "ap.py");
@@ -481,16 +1086,20 @@ function projectStatus(project, assetSkill, assetAgents){
481
1086
  ? compareManagedAgents(assetAgents, agentsDir)
482
1087
  : { diffs: [{ path: ".agents/agents", status: "missing" }], bindings: [] };
483
1088
  const agentDiffs = agentStatus.diffs;
484
- const ok = skillDiffs.length === 0 && agentDiffs.length === 0 && scriptDiffs.length === 0 && missingDocs.length === 0 && missingConfigTokens.length === 0;
1089
+ const ok = skillDiffs.length === 0 && agentDiffs.length === 0 && scriptDiffs.length === 0 && missingDocs.length === 0 && missingConfigTokens.length === 0 && managedWorkflow.state === "current" && managedAgentsDocument.state === "current";
485
1090
  let next = "";
486
1091
  if (!exists(skillDir) || !exists(agentsDir)) {
487
1092
  next = "run autocoding init --force";
488
1093
  } else if (skillDiffs.length || agentDiffs.length) {
489
1094
  next = "run autocoding sync --projects <repo>";
490
- } else if (engineeringMissing || scriptDiffs.length || missingDocs.length) {
1095
+ } else if (engineeringMissing || managedWorkflow.state !== "current" || managedAgentsDocument.state !== "current" || scriptDiffs.length || missingDocs.length) {
491
1096
  next = "run autocoding sync --projects <repo> or python3 .agents/skills/auto-coding-skill/scripts/ap.py --repo . install";
492
- } else if (missingConfigTokens.length) {
493
- next = "run project-local ap.py upgrade --write to merge docs/ENGINEERING.md safely";
1097
+ } else if (missingConfigPaths.length) {
1098
+ next = "run project-local ap.py upgrade --write to merge missing paths, fill every required value in docs/ENGINEERING.md, then run doctor";
1099
+ } else if (invalidConfigTokens.length) {
1100
+ next = "run project-local ap.py upgrade --write to migrate concurrency.isolation to worktree, then run doctor";
1101
+ } else if (unfilledConfigTokens.length) {
1102
+ next = "fill every required value in docs/ENGINEERING.md, then run project-local ap.py doctor";
494
1103
  }
495
1104
  return {
496
1105
  project: root,
@@ -501,6 +1110,11 @@ function projectStatus(project, assetSkill, assetAgents){
501
1110
  scriptDiffs,
502
1111
  missingDocs,
503
1112
  missingConfigTokens,
1113
+ missingConfigPaths,
1114
+ unfilledConfigTokens,
1115
+ invalidConfigTokens,
1116
+ managedWorkflow,
1117
+ managedAgentsDocument,
504
1118
  next,
505
1119
  };
506
1120
  }
@@ -516,44 +1130,92 @@ function printProjectStatus(result){
516
1130
  }
517
1131
  for (const item of result.missingDocs) console.log(`[autocoding] doc missing: ${item}`);
518
1132
  for (const item of result.missingConfigTokens) console.log(`[autocoding] config missing path: ${item}`);
1133
+ if (result.managedWorkflow?.state !== "current") {
1134
+ const detail = result.managedWorkflow?.detail ? ` - ${result.managedWorkflow.detail}` : "";
1135
+ console.log(`[autocoding] engineering managed-workflow: ${result.managedWorkflow?.state || "unknown"} target=${result.managedWorkflow?.version || "unknown"}${detail}`);
1136
+ }
1137
+ if (result.managedAgentsDocument?.state !== "current") {
1138
+ const detail = result.managedAgentsDocument?.detail ? ` - ${result.managedAgentsDocument.detail}` : "";
1139
+ console.log(`[autocoding] agents managed-document: ${result.managedAgentsDocument?.state || "unknown"} target=${result.managedAgentsDocument?.version || "unknown"}${detail}`);
1140
+ }
519
1141
  for (const item of result.agentBindings || []) console.log(`[autocoding] agent model: ${item.agent} -> ${item.model}`);
520
1142
  if (result.next) console.log(`[autocoding] next: ${result.next}`);
521
1143
  }
522
1144
 
523
- function syncProject(project, assetSkill, assetAgents, dryRun, resetAgentModels = false){
1145
+ function engineeringPlanDetail(plan){
1146
+ if (plan.state === "legacy-custom") return `managed workflow preserved-custom -> ${plan.version}`;
1147
+ if (plan.state === "legacy-official") return `managed workflow official-legacy -> ${plan.version}`;
1148
+ return `managed workflow ${plan.state} -> ${plan.version}`;
1149
+ }
1150
+
1151
+ function syncProject(project, assetSkill, assetAgents, dryRun, resetAgentModels = false, components = "all", controlledPlans = null){
524
1152
  const root = path.resolve(project);
525
1153
  const actions = [];
526
1154
  const skillDir = path.join(root, ".agents", "skills", "auto-coding-skill");
1155
+ const skillOnly = components === "skill";
1156
+ actions.push({ action: dryRun ? "would-sync" : "sync", path: path.relative(root, skillDir) });
1157
+ if (!dryRun) {
1158
+ rmrf(skillDir);
1159
+ copyDir(assetSkill, skillDir);
1160
+ }
1161
+ if (skillOnly) return { project: root, dryRun, components, actions };
1162
+
527
1163
  const agentsDir = path.join(root, ".agents", "agents");
528
1164
  const toolDir = path.join(root, "docs", "tools", "autopipeline");
529
- const engineering = path.join(root, "docs", "ENGINEERING.md");
530
- const engineeringWasMissing = !exists(engineering);
531
- const templateEngineering = path.join(assetSkill, "data", "templates", "ENGINEERING.md");
532
- actions.push({ action: dryRun ? "would-sync" : "sync", path: path.relative(root, skillDir) });
1165
+ const plans = controlledPlans || planControlledDocuments(root, assetSkill);
1166
+ const plan = plans.engineering;
1167
+ const agentsDocumentPlan = plans.agents;
533
1168
  actions.push({ action: dryRun ? "would-sync" : "sync", path: path.relative(root, agentsDir) });
534
1169
  actions.push({ action: dryRun ? "would-sync" : "sync", path: "docs/tools/autopipeline/ap.py" });
535
1170
  if (!dryRun) {
536
- rmrf(skillDir);
537
- copyDir(assetSkill, skillDir);
538
1171
  syncManagedAgents(assetAgents, agentsDir, { resetModel: resetAgentModels });
539
1172
  fs.mkdirSync(toolDir, { recursive: true });
540
1173
  fs.copyFileSync(path.join(assetSkill, "data", "templates", "tools", "ap.py"), path.join(toolDir, "ap.py"));
541
1174
  for (const copied of copyMissingDocs(assetSkill, root)) actions.push({ action: "create", path: copied });
542
- if (engineeringWasMissing) {
543
- fs.mkdirSync(path.dirname(engineering), { recursive: true });
544
- fs.writeFileSync(engineering, renderEngineeringTemplate(fs.readFileSync(templateEngineering, "utf8"), root));
545
- actions.push({ action: "create", path: path.join("docs", "ENGINEERING.md") });
1175
+ if (plan.state !== "current") {
1176
+ fs.mkdirSync(path.dirname(plan.engineering), { recursive: true });
1177
+ fs.writeFileSync(plan.engineering, plan.output);
1178
+ actions.push({
1179
+ action: plan.state === "missing" ? "create" : "update",
1180
+ path: path.join("docs", "ENGINEERING.md"),
1181
+ detail: engineeringPlanDetail(plan),
1182
+ });
1183
+ }
1184
+ if (agentsDocumentPlan.state !== "current") {
1185
+ fs.writeFileSync(agentsDocumentPlan.agentsDocument, agentsDocumentPlan.output);
1186
+ actions.push({
1187
+ action: agentsDocumentPlan.state === "missing" ? "create" : "update",
1188
+ path: "AGENTS.md",
1189
+ detail: `managed agents ${agentsDocumentPlan.state} -> ${agentsDocumentPlan.version}`,
1190
+ });
546
1191
  }
547
1192
  } else {
548
1193
  for (const rel of CORE_DOCS) {
549
1194
  if (!exists(path.join(root, "docs", rel))) actions.push({ action: "would-create", path: path.join("docs", rel) });
550
1195
  }
551
- if (engineeringWasMissing) actions.push({ action: "would-create", path: path.join("docs", "ENGINEERING.md") });
552
- }
553
- if (!engineeringWasMissing) {
554
- actions.push({ action: "manual", path: "docs/ENGINEERING.md", detail: "merge existing files with ap.py upgrade --write" });
1196
+ if (plan.state !== "current") {
1197
+ actions.push({
1198
+ action: plan.state === "missing" ? "would-create" : "would-update",
1199
+ path: path.join("docs", "ENGINEERING.md"),
1200
+ detail: engineeringPlanDetail(plan),
1201
+ });
1202
+ }
1203
+ if (agentsDocumentPlan.state !== "current") {
1204
+ actions.push({
1205
+ action: agentsDocumentPlan.state === "missing" ? "would-create" : "would-update",
1206
+ path: "AGENTS.md",
1207
+ detail: `managed agents ${agentsDocumentPlan.state} -> ${agentsDocumentPlan.version}`,
1208
+ });
1209
+ }
555
1210
  }
556
- return { project: root, dryRun, actions };
1211
+ return {
1212
+ project: root,
1213
+ dryRun,
1214
+ components,
1215
+ managedWorkflow: publicEngineeringPlan(plan),
1216
+ managedAgentsDocument: publicEngineeringPlan(agentsDocumentPlan),
1217
+ actions,
1218
+ };
557
1219
  }
558
1220
 
559
1221
  function projectRoot(){ return process.cwd(); }
@@ -612,12 +1274,13 @@ autocoding - install auto-coding-skill into generic .agents paths
612
1274
  Usage:
613
1275
  autocoding init [--mode project|global] [--dest <repo-root|.agents-dir|skill-dir>] [--force] [--reset-agent-models]
614
1276
  autocoding status --projects <path[,path...]> [--json]
615
- autocoding sync --projects <path[,path...]> [--dry-run] [--json] [--reset-agent-models]
1277
+ autocoding sync --projects <path[,path...]> [--components all|skill] [--dry-run] [--json] [--reset-agent-models]
616
1278
 
617
1279
  Examples:
618
1280
  autocoding init
619
1281
  autocoding status --projects /Users/elvis/Product/xjmate,/Users/elvis/Product/geesight
620
1282
  autocoding sync --projects /Users/elvis/Product/xjmate --dry-run
1283
+ autocoding sync --projects /Users/elvis/Product/geesight --components skill
621
1284
 
622
1285
  Compatibility:
623
1286
  --ai <value> is accepted for old scripts and ignored.
@@ -629,8 +1292,13 @@ Compatibility:
629
1292
  validateCommandArgs(args);
630
1293
 
631
1294
  const here = path.dirname(fileURLToPath(import.meta.url));
632
- const assetSkill = path.resolve(here, "..", "assets", "skill");
633
- const assetAgents = path.resolve(here, "..", "assets", "agents");
1295
+ const packagedAssetSkill = path.resolve(here, "..", "assets", "skill");
1296
+ const packagedAssetAgents = path.resolve(here, "..", "assets", "agents");
1297
+ const sourceAssetSkill = path.resolve(here, "..", "..", "src", "auto-coding-skill");
1298
+ const sourceAssetAgents = path.resolve(here, "..", "..", "src", "agents");
1299
+ const useSourceAssets = exists(sourceAssetSkill) && exists(sourceAssetAgents);
1300
+ const assetSkill = useSourceAssets ? sourceAssetSkill : packagedAssetSkill;
1301
+ const assetAgents = useSourceAssets ? sourceAssetAgents : packagedAssetAgents;
634
1302
  if (!exists(assetSkill)) die(`missing assets at ${assetSkill}`);
635
1303
  if (!exists(assetAgents)) die(`missing assets at ${assetAgents}`);
636
1304
 
@@ -647,13 +1315,40 @@ Compatibility:
647
1315
 
648
1316
  if (args.cmd === "sync") {
649
1317
  const projects = args.projects.length ? args.projects : [projectRoot()];
650
- const results = projects.map(project => syncProject(project, assetSkill, assetAgents, args.dryRun, args.resetAgentModels));
1318
+ assertNoLegacyRegisteredTasks(projects);
1319
+ const controlledPlans = new Map();
1320
+ for (const project of projects) {
1321
+ const root = path.resolve(project);
1322
+ const plans = planControlledDocuments(root, assetSkill);
1323
+ for (const [document, plan] of Object.entries(plans)) {
1324
+ if (plan.state === "invalid" || plan.state === "conflict") {
1325
+ const conflicts = (plan.conflicts || [])
1326
+ .map(item => `${item.file}:${item.line} [${item.ruleId}] ${item.message}`)
1327
+ .join("; ");
1328
+ die(`refusing the entire sync batch before writes: ${root} ${document}: ${plan.detail || "invalid managed document"}${conflicts ? `; ${conflicts}` : ""}`);
1329
+ }
1330
+ }
1331
+ controlledPlans.set(root, plans);
1332
+ }
1333
+ const results = projects.map(project => {
1334
+ const root = path.resolve(project);
1335
+ return syncProject(
1336
+ root,
1337
+ assetSkill,
1338
+ assetAgents,
1339
+ args.dryRun,
1340
+ args.resetAgentModels,
1341
+ args.components,
1342
+ controlledPlans.get(root) || null,
1343
+ );
1344
+ });
651
1345
  if (args.json) console.log(JSON.stringify({ version: readPackageVersion(), results }, null, 2));
652
1346
  else {
653
1347
  console.log(`[autocoding] version=${readPackageVersion()}`);
654
1348
  for (const result of results) {
655
1349
  console.log(`[autocoding] project=${result.project}`);
656
1350
  console.log(`[autocoding] dryRun=${result.dryRun}`);
1351
+ console.log(`[autocoding] components=${result.components}`);
657
1352
  for (const item of result.actions) {
658
1353
  const detail = item.detail ? ` - ${item.detail}` : "";
659
1354
  console.log(`[autocoding] ${item.action}: ${item.path}${detail}`);
@@ -681,6 +1376,9 @@ Compatibility:
681
1376
  syncManagedAgents(assetAgents, agentsDir, { resetModel: args.resetAgentModels });
682
1377
  console.log(`[autocoding] installed agents to: ${agentsDir}`);
683
1378
 
1379
+ if (args.mode === "project") {
1380
+ console.log("[autocoding] next: run autocoding sync --projects ., fill every access.* field in docs/ENGINEERING.md, then run doctor.");
1381
+ }
684
1382
  console.log("[autocoding] done.");
685
1383
  }
686
1384