@elvis1513/auto-coding-skill 3.0.1 → 3.0.3

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
@@ -402,29 +402,27 @@ const MANAGED_WORKFLOW_START_TOKEN = "auto-coding-skill:managed-workflow:start";
402
402
  const MANAGED_WORKFLOW_END_TOKEN = "auto-coding-skill:managed-workflow:end";
403
403
  const MANAGED_WORKFLOW_START_RE = /<!--\s*auto-coding-skill:managed-workflow:start\s+version=([0-9]+\.[0-9]+\.[0-9]+)\s*-->/g;
404
404
  const MANAGED_WORKFLOW_END_RE = /<!--\s*auto-coding-skill:managed-workflow:end\s*-->/g;
405
- const KNOWN_OFFICIAL_LEGACY_BODY_HASHES = new Set([
406
- // v2.2.0, v3.0.0, and origin/dev@c532734 respectively. Frontmatter is excluded.
407
- "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
408
- "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
409
- "198d675361337bc272880154266b3eb1f50e3f82f3c6ab04b2e559cd18d8c7b4",
410
- ]);
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;
411
409
 
412
410
  function tokenCount(text, token){
413
411
  return text.split(token).length - 1;
414
412
  }
415
413
 
416
- function inspectManagedWorkflow(text){
417
- const rawStarts = tokenCount(text, MANAGED_WORKFLOW_START_TOKEN);
418
- const rawEnds = tokenCount(text, MANAGED_WORKFLOW_END_TOKEN);
414
+ function inspectManagedRegion(text, startToken, endToken, startPattern, endPattern, label){
415
+ const rawStarts = tokenCount(text, startToken);
416
+ const rawEnds = tokenCount(text, endToken);
419
417
  if (rawStarts === 0 && rawEnds === 0) return { state: "absent" };
420
418
 
421
- const starts = [...text.matchAll(MANAGED_WORKFLOW_START_RE)];
422
- const ends = [...text.matchAll(MANAGED_WORKFLOW_END_RE)];
419
+ const starts = [...text.matchAll(startPattern)];
420
+ const ends = [...text.matchAll(endPattern)];
423
421
  if (rawStarts !== starts.length || rawEnds !== ends.length) {
424
- return { state: "invalid", detail: "managed workflow marker is malformed" };
422
+ return { state: "invalid", detail: `managed ${label} marker is malformed` };
425
423
  }
426
424
  if (starts.length !== 1 || ends.length !== 1) {
427
- return { state: "invalid", detail: "managed workflow markers must contain exactly one start/end pair" };
425
+ return { state: "invalid", detail: `managed ${label} markers must contain exactly one start/end pair` };
428
426
  }
429
427
  const start = starts[0].index;
430
428
  const end = ends[0].index;
@@ -441,6 +439,145 @@ function inspectManagedWorkflow(text){
441
439
  };
442
440
  }
443
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
+
444
581
  function splitEngineeringDocument(text){
445
582
  const frontmatter = text.match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/);
446
583
  const bodyStart = frontmatter ? frontmatter[0].length : 0;
@@ -459,10 +596,21 @@ function insertManagedWorkflow(text, block){
459
596
  const insertion = heading ? bodyStart + heading.index + heading[0].length : bodyStart;
460
597
  const before = text.slice(0, insertion);
461
598
  const after = text.slice(insertion);
462
- return `${before}${block}${after}`;
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 }));
463
611
  }
464
612
 
465
- function planEngineeringSync(project, assetSkill){
613
+ function planEngineeringSync(project, assetSkill, policy = loadWorkflowMigrationPolicy(assetSkill)){
466
614
  const root = path.resolve(project);
467
615
  const engineering = path.join(root, "docs", "ENGINEERING.md");
468
616
  const templatePath = path.join(assetSkill, "data", "templates", "ENGINEERING.md");
@@ -471,8 +619,11 @@ function planEngineeringSync(project, assetSkill){
471
619
  if (templateRegion.state !== "present") {
472
620
  return { state: "invalid", detail: `packaged ENGINEERING template: ${templateRegion.detail || "managed workflow markers are missing"}` };
473
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
+ }
474
625
  if (!exists(engineering)) {
475
- return { state: "missing", version: templateRegion.version, output: renderedTemplate, engineering };
626
+ return { state: "missing", version: templateRegion.version, output: renderedTemplate, engineering, migrations: [], conflicts: [] };
476
627
  }
477
628
 
478
629
  const current = fs.readFileSync(engineering, "utf8");
@@ -482,32 +633,160 @@ function planEngineeringSync(project, assetSkill){
482
633
  const currentParts = splitEngineeringDocument(current);
483
634
  const templateParts = splitEngineeringDocument(renderedTemplate);
484
635
  const legacyHash = engineeringBodyHash(currentParts.body);
485
- if (KNOWN_OFFICIAL_LEGACY_BODY_HASHES.has(legacyHash)) {
636
+ if (policy.known_official_engineering_body_sha256.includes(legacyHash)) {
486
637
  return {
487
638
  state: "legacy-official",
488
639
  version: templateRegion.version,
489
640
  previousBodyHash: legacyHash,
490
641
  output: `${currentParts.frontmatter}${templateParts.body}`,
491
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",
492
657
  };
493
658
  }
494
659
  return {
495
660
  state: "legacy-custom",
496
661
  version: templateRegion.version,
497
662
  preservedCustom: true,
498
- output: insertManagedWorkflow(current, templateRegion.block),
663
+ output: insertManagedWorkflow(`${currentParts.frontmatter}${migrated.output}`, templateRegion.block),
499
664
  engineering,
665
+ migrations: migrated.migrations,
666
+ conflicts: [],
500
667
  };
501
668
  }
502
- if (currentRegion.block === templateRegion.block) {
503
- return { state: "current", version: templateRegion.version, output: current, engineering };
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
+ };
504
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: [] };
505
692
  return {
506
693
  state: "stale",
507
694
  version: templateRegion.version,
508
695
  previousVersion: currentRegion.version,
509
- output: `${current.slice(0, currentRegion.start)}${templateRegion.block}${current.slice(currentRegion.endExclusive)}`,
696
+ output,
510
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),
511
790
  };
512
791
  }
513
792
 
@@ -518,6 +797,8 @@ function publicEngineeringPlan(plan){
518
797
  ...(plan.previousVersion ? { previousVersion: plan.previousVersion } : {}),
519
798
  ...(plan.previousBodyHash ? { previousBodyHash: plan.previousBodyHash } : {}),
520
799
  ...(plan.preservedCustom ? { preservedCustom: true } : {}),
800
+ ...(plan.migrations?.length ? { migrations: plan.migrations } : {}),
801
+ ...(plan.conflicts?.length ? { conflicts: plan.conflicts } : {}),
521
802
  ...(plan.detail ? { detail: plan.detail } : {}),
522
803
  };
523
804
  }
@@ -603,6 +884,40 @@ function frontmatterPathState(text, keyPath){
603
884
  return { present: false, value: "" };
604
885
  }
605
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)$/i.test(frontmatterScalarValue(value))) {
907
+ tokens.push("gate.full_on_unknown=true (legacy automatic full escalation)");
908
+ }
909
+ if (key === "rules") {
910
+ if (value && value !== "[]") tokens.push("gate.rules inline value (run upgrade to migrate safely)");
911
+ rulesIndent = indent;
912
+ continue;
913
+ }
914
+ if (rulesIndent !== null && indent > rulesIndent && (key === "scope" || key === "commands")) {
915
+ tokens.push(`gate.rules[].${key} (legacy automatic gate escalation)`);
916
+ }
917
+ }
918
+ return [...new Set(tokens)];
919
+ }
920
+
606
921
  function frontmatterValueIsFilled(raw){
607
922
  const source = String(raw || "");
608
923
  let quote = "";
@@ -696,8 +1011,11 @@ function projectStatus(project, assetSkill, assetAgents){
696
1011
  const toolDir = path.join(root, "docs", "tools", "autopipeline");
697
1012
  const engineering = path.join(root, "docs", "ENGINEERING.md");
698
1013
  const engineeringMissing = !exists(engineering);
699
- const engineeringPlan = planEngineeringSync(root, assetSkill);
1014
+ const controlledPlans = planControlledDocuments(root, assetSkill);
1015
+ const engineeringPlan = controlledPlans.engineering;
1016
+ const agentsDocumentPlan = controlledPlans.agents;
700
1017
  const managedWorkflow = publicEngineeringPlan(engineeringPlan);
1018
+ const managedAgentsDocument = publicEngineeringPlan(agentsDocumentPlan);
701
1019
  const requiredConfigPaths = [
702
1020
  { label: "workflow.mode", path: ["workflow", "mode"] },
703
1021
  { label: "workflow.profile", path: ["workflow", "profile"] },
@@ -746,9 +1064,10 @@ function projectStatus(project, assetSkill, assetAgents){
746
1064
  .filter(({ item, state }) => state.present && item.filled === true && !frontmatterValueIsFilled(state.value))
747
1065
  .map(({ item }) => item.label);
748
1066
  const isolationState = frontmatterPathState(text, ["concurrency", "isolation"]);
749
- if (isolationState.present && frontmatterScalarValue(isolationState.value).toLowerCase() !== "worktree") {
750
- invalidConfigTokens = ["concurrency.isolation (must be worktree)"];
1067
+ if (isolationState.present && !["adaptive", "worktree"].includes(frontmatterScalarValue(isolationState.value).toLowerCase())) {
1068
+ invalidConfigTokens.push("concurrency.isolation (must be adaptive or worktree)");
751
1069
  }
1070
+ invalidConfigTokens.push(...legacyGateEscalationTokens(text));
752
1071
  }
753
1072
  const missingConfigTokens = [...missingConfigPaths, ...unfilledConfigTokens, ...invalidConfigTokens];
754
1073
  const scriptDiffs = [];
@@ -768,18 +1087,18 @@ function projectStatus(project, assetSkill, assetAgents){
768
1087
  ? compareManagedAgents(assetAgents, agentsDir)
769
1088
  : { diffs: [{ path: ".agents/agents", status: "missing" }], bindings: [] };
770
1089
  const agentDiffs = agentStatus.diffs;
771
- const ok = skillDiffs.length === 0 && agentDiffs.length === 0 && scriptDiffs.length === 0 && missingDocs.length === 0 && missingConfigTokens.length === 0 && managedWorkflow.state === "current";
1090
+ const ok = skillDiffs.length === 0 && agentDiffs.length === 0 && scriptDiffs.length === 0 && missingDocs.length === 0 && missingConfigTokens.length === 0 && managedWorkflow.state === "current" && managedAgentsDocument.state === "current";
772
1091
  let next = "";
773
1092
  if (!exists(skillDir) || !exists(agentsDir)) {
774
1093
  next = "run autocoding init --force";
775
1094
  } else if (skillDiffs.length || agentDiffs.length) {
776
1095
  next = "run autocoding sync --projects <repo>";
777
- } else if (engineeringMissing || managedWorkflow.state !== "current" || scriptDiffs.length || missingDocs.length) {
1096
+ } else if (engineeringMissing || managedWorkflow.state !== "current" || managedAgentsDocument.state !== "current" || scriptDiffs.length || missingDocs.length) {
778
1097
  next = "run autocoding sync --projects <repo> or python3 .agents/skills/auto-coding-skill/scripts/ap.py --repo . install";
779
1098
  } else if (missingConfigPaths.length) {
780
1099
  next = "run project-local ap.py upgrade --write to merge missing paths, fill every required value in docs/ENGINEERING.md, then run doctor";
781
1100
  } else if (invalidConfigTokens.length) {
782
- next = "run project-local ap.py upgrade --write to migrate concurrency.isolation to worktree, then run doctor";
1101
+ next = "run project-local ap.py upgrade --write to migrate concurrency.isolation to adaptive, then run doctor";
783
1102
  } else if (unfilledConfigTokens.length) {
784
1103
  next = "fill every required value in docs/ENGINEERING.md, then run project-local ap.py doctor";
785
1104
  }
@@ -796,6 +1115,7 @@ function projectStatus(project, assetSkill, assetAgents){
796
1115
  unfilledConfigTokens,
797
1116
  invalidConfigTokens,
798
1117
  managedWorkflow,
1118
+ managedAgentsDocument,
799
1119
  next,
800
1120
  };
801
1121
  }
@@ -815,6 +1135,10 @@ function printProjectStatus(result){
815
1135
  const detail = result.managedWorkflow?.detail ? ` - ${result.managedWorkflow.detail}` : "";
816
1136
  console.log(`[autocoding] engineering managed-workflow: ${result.managedWorkflow?.state || "unknown"} target=${result.managedWorkflow?.version || "unknown"}${detail}`);
817
1137
  }
1138
+ if (result.managedAgentsDocument?.state !== "current") {
1139
+ const detail = result.managedAgentsDocument?.detail ? ` - ${result.managedAgentsDocument.detail}` : "";
1140
+ console.log(`[autocoding] agents managed-document: ${result.managedAgentsDocument?.state || "unknown"} target=${result.managedAgentsDocument?.version || "unknown"}${detail}`);
1141
+ }
818
1142
  for (const item of result.agentBindings || []) console.log(`[autocoding] agent model: ${item.agent} -> ${item.model}`);
819
1143
  if (result.next) console.log(`[autocoding] next: ${result.next}`);
820
1144
  }
@@ -825,7 +1149,7 @@ function engineeringPlanDetail(plan){
825
1149
  return `managed workflow ${plan.state} -> ${plan.version}`;
826
1150
  }
827
1151
 
828
- function syncProject(project, assetSkill, assetAgents, dryRun, resetAgentModels = false, components = "all", engineeringPlan = null){
1152
+ function syncProject(project, assetSkill, assetAgents, dryRun, resetAgentModels = false, components = "all", controlledPlans = null){
829
1153
  const root = path.resolve(project);
830
1154
  const actions = [];
831
1155
  const skillDir = path.join(root, ".agents", "skills", "auto-coding-skill");
@@ -839,7 +1163,9 @@ function syncProject(project, assetSkill, assetAgents, dryRun, resetAgentModels
839
1163
 
840
1164
  const agentsDir = path.join(root, ".agents", "agents");
841
1165
  const toolDir = path.join(root, "docs", "tools", "autopipeline");
842
- const plan = engineeringPlan || planEngineeringSync(root, assetSkill);
1166
+ const plans = controlledPlans || planControlledDocuments(root, assetSkill);
1167
+ const plan = plans.engineering;
1168
+ const agentsDocumentPlan = plans.agents;
843
1169
  actions.push({ action: dryRun ? "would-sync" : "sync", path: path.relative(root, agentsDir) });
844
1170
  actions.push({ action: dryRun ? "would-sync" : "sync", path: "docs/tools/autopipeline/ap.py" });
845
1171
  if (!dryRun) {
@@ -856,6 +1182,14 @@ function syncProject(project, assetSkill, assetAgents, dryRun, resetAgentModels
856
1182
  detail: engineeringPlanDetail(plan),
857
1183
  });
858
1184
  }
1185
+ if (agentsDocumentPlan.state !== "current") {
1186
+ fs.writeFileSync(agentsDocumentPlan.agentsDocument, agentsDocumentPlan.output);
1187
+ actions.push({
1188
+ action: agentsDocumentPlan.state === "missing" ? "create" : "update",
1189
+ path: "AGENTS.md",
1190
+ detail: `managed agents ${agentsDocumentPlan.state} -> ${agentsDocumentPlan.version}`,
1191
+ });
1192
+ }
859
1193
  } else {
860
1194
  for (const rel of CORE_DOCS) {
861
1195
  if (!exists(path.join(root, "docs", rel))) actions.push({ action: "would-create", path: path.join("docs", rel) });
@@ -867,8 +1201,22 @@ function syncProject(project, assetSkill, assetAgents, dryRun, resetAgentModels
867
1201
  detail: engineeringPlanDetail(plan),
868
1202
  });
869
1203
  }
1204
+ if (agentsDocumentPlan.state !== "current") {
1205
+ actions.push({
1206
+ action: agentsDocumentPlan.state === "missing" ? "would-create" : "would-update",
1207
+ path: "AGENTS.md",
1208
+ detail: `managed agents ${agentsDocumentPlan.state} -> ${agentsDocumentPlan.version}`,
1209
+ });
1210
+ }
870
1211
  }
871
- return { project: root, dryRun, components, managedWorkflow: publicEngineeringPlan(plan), actions };
1212
+ return {
1213
+ project: root,
1214
+ dryRun,
1215
+ components,
1216
+ managedWorkflow: publicEngineeringPlan(plan),
1217
+ managedAgentsDocument: publicEngineeringPlan(agentsDocumentPlan),
1218
+ actions,
1219
+ };
872
1220
  }
873
1221
 
874
1222
  function projectRoot(){ return process.cwd(); }
@@ -969,16 +1317,19 @@ Compatibility:
969
1317
  if (args.cmd === "sync") {
970
1318
  const projects = args.projects.length ? args.projects : [projectRoot()];
971
1319
  assertNoLegacyRegisteredTasks(projects);
972
- const engineeringPlans = new Map();
973
- if (args.components === "all") {
974
- for (const project of projects) {
975
- const root = path.resolve(project);
976
- const plan = planEngineeringSync(root, assetSkill);
977
- if (plan.state === "invalid") {
978
- die(`refusing to sync ${root}: ${plan.detail}`);
1320
+ const controlledPlans = new Map();
1321
+ for (const project of projects) {
1322
+ const root = path.resolve(project);
1323
+ const plans = planControlledDocuments(root, assetSkill);
1324
+ for (const [document, plan] of Object.entries(plans)) {
1325
+ if (plan.state === "invalid" || plan.state === "conflict") {
1326
+ const conflicts = (plan.conflicts || [])
1327
+ .map(item => `${item.file}:${item.line} [${item.ruleId}] ${item.message}`)
1328
+ .join("; ");
1329
+ die(`refusing the entire sync batch before writes: ${root} ${document}: ${plan.detail || "invalid managed document"}${conflicts ? `; ${conflicts}` : ""}`);
979
1330
  }
980
- engineeringPlans.set(root, plan);
981
1331
  }
1332
+ controlledPlans.set(root, plans);
982
1333
  }
983
1334
  const results = projects.map(project => {
984
1335
  const root = path.resolve(project);
@@ -989,7 +1340,7 @@ Compatibility:
989
1340
  args.dryRun,
990
1341
  args.resetAgentModels,
991
1342
  args.components,
992
- engineeringPlans.get(root) || null,
1343
+ controlledPlans.get(root) || null,
993
1344
  );
994
1345
  });
995
1346
  if (args.json) console.log(JSON.stringify({ version: readPackageVersion(), results }, null, 2));