@codedrifters/configulator 0.0.403 → 0.0.405

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/lib/index.mjs CHANGED
@@ -5556,6 +5556,409 @@ function buildBcmWriterBundle(paths = DEFAULT_AGENT_PATHS, issueDefaults = DEFAU
5556
5556
  }
5557
5557
  var bcmWriterBundle = buildBcmWriterBundle();
5558
5558
 
5559
+ // src/turbo/turbo-repo.ts
5560
+ import {
5561
+ Component as Component2,
5562
+ FileBase,
5563
+ JsonFile,
5564
+ SampleDir,
5565
+ SampleFile
5566
+ } from "projen/lib";
5567
+ import { JobPermission } from "projen/lib/github/workflows-model";
5568
+
5569
+ // src/turbo/turbo-repo-task.ts
5570
+ import { Component } from "projen/lib";
5571
+ var TurboRepoTask = class extends Component {
5572
+ constructor(project, options) {
5573
+ super(project);
5574
+ this.project = project;
5575
+ this.name = options.name;
5576
+ this.dependsOn = options.dependsOn ?? [];
5577
+ this.env = options.env ?? [];
5578
+ this.passThroughEnv = options.passThroughEnv ?? [];
5579
+ this.outputs = options.outputs ?? [];
5580
+ this.cache = options.cache ?? true;
5581
+ this.inputs = [
5582
+ ...options.inputs ?? [],
5583
+ // rerun if projen config changes
5584
+ ".projen/**",
5585
+ // ignore mac files
5586
+ "!.DS_Store",
5587
+ "!**/.DS_Store"
5588
+ ];
5589
+ this.outputLogs = options.outputLogs ?? "new-only";
5590
+ this.persistent = options.persistent ?? false;
5591
+ this.interactive = options.interactive ?? false;
5592
+ this.isActive = true;
5593
+ }
5594
+ taskConfig() {
5595
+ return {
5596
+ dependsOn: this.dependsOn,
5597
+ env: this.env,
5598
+ passThroughEnv: this.passThroughEnv,
5599
+ outputs: this.outputs,
5600
+ cache: this.cache,
5601
+ inputs: this.inputs,
5602
+ outputLogs: this.outputLogs,
5603
+ persistent: this.persistent,
5604
+ interactive: this.interactive
5605
+ };
5606
+ }
5607
+ };
5608
+
5609
+ // src/turbo/turbo-repo.ts
5610
+ var ROOT_TURBO_TASK_NAME = "turbo:build";
5611
+ var ROOT_CI_TASK_NAME = "build:all";
5612
+ var _TurboRepo = class _TurboRepo extends Component2 {
5613
+ constructor(project, options = {}) {
5614
+ super(project);
5615
+ this.project = project;
5616
+ /**
5617
+ * Sub-Tasks to run
5618
+ */
5619
+ this.tasks = [];
5620
+ this.turboVersion = options.turboVersion ?? "catalog:";
5621
+ this.isRootProject = project === project.root;
5622
+ if (this.isRootProject) {
5623
+ project.addDevDeps(`turbo@${this.turboVersion}`);
5624
+ }
5625
+ project.gitignore.addPatterns("/.turbo");
5626
+ project.npmignore?.addPatterns("/.turbo/");
5627
+ this.extends = options.extends ?? (this.isRootProject ? [] : ["//"]);
5628
+ this.globalDependencies = options.globalDependencies ?? [];
5629
+ this.globalEnv = options.globalEnv ?? [];
5630
+ this.globalPassThroughEnv = options.globalPassThroughEnv ?? [];
5631
+ this.ui = options.ui ?? "stream";
5632
+ this.dangerouslyDisablePackageManagerCheck = options.dangerouslyDisablePackageManagerCheck ?? false;
5633
+ this.cacheDir = options.cacheDir ?? ".turbo/cache";
5634
+ this.daemon = options.daemon ?? true;
5635
+ this.envMode = options.envMode ?? "strict";
5636
+ this.runOptions = {
5637
+ ...options.runOptions,
5638
+ summarize: options.runOptions?.summarize ?? true,
5639
+ concurrency: options.runOptions?.concurrency ?? 10
5640
+ };
5641
+ this.remoteCacheOptions = options.remoteCacheOptions;
5642
+ this.buildAllTaskEnvVars = options.buildAllTaskEnvVars ?? {};
5643
+ this.buildTask = new TurboRepoTask(this.project, {
5644
+ name: ROOT_TURBO_TASK_NAME,
5645
+ dependsOn: this.isRootProject ? [`^${ROOT_TURBO_TASK_NAME}`] : []
5646
+ });
5647
+ if (this.isRootProject) {
5648
+ this.buildAllTask = this.project.tasks.addTask(ROOT_CI_TASK_NAME, {
5649
+ description: "Root build followed by sub-project builds. Mimics the CI build process in one step."
5650
+ });
5651
+ this.buildAllTask.exec("turbo telemetry disable");
5652
+ if (this.buildAllTaskEnvVars) {
5653
+ Object.entries(this.buildAllTaskEnvVars).forEach(([name, value]) => {
5654
+ this.addGlobalEnvVar(name, value);
5655
+ });
5656
+ }
5657
+ if (!this.remoteCacheOptions) {
5658
+ this.buildAllTask.exec(
5659
+ `turbo ${ROOT_TURBO_TASK_NAME} ${this.renderRunArgs(false)}`
5660
+ );
5661
+ } else {
5662
+ this.buildAllTask.exec(
5663
+ `turbo ${ROOT_TURBO_TASK_NAME} ${this.renderRunArgs(true)}`,
5664
+ {
5665
+ condition: '[ ! -n "$CI" ]',
5666
+ env: {
5667
+ TURBO_ENDPOINT: `$(aws ssm get-parameter --name ${this.remoteCacheOptions.endpointParamName} --query Parameter.Value --output text --profile ${this.remoteCacheOptions.profileName})`,
5668
+ TURBO_TOKEN: `$(aws ssm get-parameter --name ${this.remoteCacheOptions.tokenParamName} --query Parameter.Value --output text --profile ${this.remoteCacheOptions.profileName})`
5669
+ }
5670
+ }
5671
+ );
5672
+ this.buildAllTask.exec(
5673
+ `turbo ${ROOT_TURBO_TASK_NAME} ${this.renderRunArgs(true)}`,
5674
+ {
5675
+ condition: '[ -n "$CI" ]',
5676
+ env: {
5677
+ TURBO_ENDPOINT: `$(aws ssm get-parameter --name ${this.remoteCacheOptions.endpointParamName} --query Parameter.Value --output text)`,
5678
+ TURBO_TOKEN: `$(aws ssm get-parameter --name ${this.remoteCacheOptions.tokenParamName} --query Parameter.Value --output text)`
5679
+ }
5680
+ }
5681
+ );
5682
+ }
5683
+ }
5684
+ if (!this.isRootProject) {
5685
+ this.preCompileTask = new TurboRepoTask(project, {
5686
+ name: options.preCompileTask?.name ?? "pre-compile",
5687
+ inputs: ["src/**"]
5688
+ });
5689
+ this.compileTask = new TurboRepoTask(project, {
5690
+ name: options.compileTask?.name ?? "compile",
5691
+ inputs: ["src/**"]
5692
+ });
5693
+ this.postCompileTask = new TurboRepoTask(project, {
5694
+ name: options.postCompileTask?.name ?? "post-compile",
5695
+ inputs: ["src/**"]
5696
+ });
5697
+ this.testTask = new TurboRepoTask(project, {
5698
+ name: options.testTask?.name ?? "test"
5699
+ });
5700
+ this.packageTask = new TurboRepoTask(project, {
5701
+ name: options.packageTask?.name ?? "package",
5702
+ inputs: [".npmignore"]
5703
+ });
5704
+ this.tasks.push(
5705
+ this.preCompileTask,
5706
+ this.compileTask,
5707
+ this.postCompileTask,
5708
+ this.testTask,
5709
+ this.packageTask
5710
+ );
5711
+ }
5712
+ }
5713
+ /**
5714
+ * Static method to discovert turbo in a project.
5715
+ */
5716
+ static of(project) {
5717
+ const isDefined = (c) => c instanceof _TurboRepo;
5718
+ return project.components.find(isDefined);
5719
+ }
5720
+ /**
5721
+ * Render the `turbo run` CLI flag string for the `build:all` / `reset:all`
5722
+ * task commands from {@link runOptions}. With no `runOptions` configured the
5723
+ * output matches the historically hard-coded flags exactly.
5724
+ *
5725
+ * @param remote - when `true`, also emit the remote-cache flags
5726
+ * (`--cache=remote:rw` plus `--api` / `--token` / `--team` derived from
5727
+ * {@link remoteCacheOptions}). The remote-cache `build:all` variant passes
5728
+ * `true`; `reset:all` and the local `build:all` variant pass `false`.
5729
+ */
5730
+ renderRunArgs(remote) {
5731
+ const run = this.runOptions;
5732
+ const args = [];
5733
+ if (run.summarize) {
5734
+ args.push("--summarize");
5735
+ }
5736
+ args.push(`--concurrency=${run.concurrency}`);
5737
+ if (run.force) {
5738
+ args.push("--force");
5739
+ }
5740
+ if (run.noCache) {
5741
+ args.push("--no-cache");
5742
+ }
5743
+ if (run.only) {
5744
+ args.push("--only");
5745
+ }
5746
+ if (run.affected) {
5747
+ args.push("--affected");
5748
+ }
5749
+ if (run.cacheWorkers !== void 0) {
5750
+ args.push(`--cache-workers=${run.cacheWorkers}`);
5751
+ }
5752
+ if (run.continueOn !== void 0) {
5753
+ args.push(`--continue=${run.continueOn}`);
5754
+ }
5755
+ if (run.frameworkInference !== void 0) {
5756
+ args.push(`--framework-inference=${run.frameworkInference}`);
5757
+ }
5758
+ for (const filter of run.filter ?? []) {
5759
+ args.push(`--filter=${filter}`);
5760
+ }
5761
+ if (run.outputLogs !== void 0) {
5762
+ args.push(`--output-logs=${run.outputLogs}`);
5763
+ }
5764
+ if (run.logOrder !== void 0) {
5765
+ args.push(`--log-order=${run.logOrder}`);
5766
+ }
5767
+ if (run.logPrefix !== void 0) {
5768
+ args.push(`--log-prefix=${run.logPrefix}`);
5769
+ }
5770
+ if (run.dryRun !== void 0) {
5771
+ args.push(`--dry-run=${run.dryRun}`);
5772
+ }
5773
+ const cache = run.cache ?? (remote ? "remote:rw" : void 0);
5774
+ if (cache !== void 0) {
5775
+ args.push(`--cache=${cache}`);
5776
+ }
5777
+ if (remote && this.remoteCacheOptions) {
5778
+ args.push(
5779
+ "--api=$TURBO_ENDPOINT",
5780
+ "--token=$TURBO_TOKEN",
5781
+ `--team=${this.remoteCacheOptions.teamName}`
5782
+ );
5783
+ }
5784
+ if (run.additionalArgs) {
5785
+ args.push(...run.additionalArgs);
5786
+ }
5787
+ return args.join(" ");
5788
+ }
5789
+ /**
5790
+ * Add an env var to the global env vars for all tasks.
5791
+ * This will also become an input for the build:all task cache at the root.
5792
+ */
5793
+ addGlobalEnvVar(name, value) {
5794
+ this.buildAllTask?.env(name, value);
5795
+ if (this.isRootProject) {
5796
+ this.globalEnv.push(name);
5797
+ }
5798
+ }
5799
+ activateBranchNameEnvVar(options) {
5800
+ const value = '$([ -n "$GIT_BRANCH_NAME" ] && echo "$GIT_BRANCH_NAME" || git rev-parse --abbrev-ref HEAD)';
5801
+ if (options === void 0) {
5802
+ this.project.logger.warn(
5803
+ "TurboRepo.activateBranchNameEnvVar() with no arguments is deprecated. It writes GIT_BRANCH_NAME to the root `globalEnv`, which forces every task in the monorepo to miss cache on every branch switch. Pass `{ tasks: [...] }` and name only the tasks that actually consume the branch (e.g. CDK synth/package) to preserve cross-branch cache hits for everything else."
5804
+ );
5805
+ this.addGlobalEnvVar("GIT_BRANCH_NAME", value);
5806
+ return;
5807
+ }
5808
+ const knownTaskNames = this.tasks.map((task) => task.name);
5809
+ const unknown = options.tasks.filter(
5810
+ (name) => !knownTaskNames.includes(name)
5811
+ );
5812
+ if (unknown.length > 0) {
5813
+ throw new Error(
5814
+ `TurboRepo.activateBranchNameEnvVar: unknown task name(s) ${JSON.stringify(
5815
+ unknown
5816
+ )}. Known tasks on this TurboRepo: ${JSON.stringify(knownTaskNames)}.`
5817
+ );
5818
+ }
5819
+ for (const name of options.tasks) {
5820
+ const task = this.tasks.find((t) => t.name === name);
5821
+ if (task && !task.env.includes("GIT_BRANCH_NAME")) {
5822
+ task.env.push("GIT_BRANCH_NAME");
5823
+ }
5824
+ }
5825
+ }
5826
+ /**
5827
+ * Paths of all generated files in the project, deduped, for use as task
5828
+ * inputs so the compile cache invalidates when they change. Includes
5829
+ * projen-managed `FileBase` files plus generated-once `SampleFile` /
5830
+ * `SampleDir` — whose paths projen keeps private, so they are read defensively
5831
+ * and skipped if that internal shape ever changes. Computed at synth time so
5832
+ * files added after this component (e.g. a subclass's SampleFiles) are seen.
5833
+ */
5834
+ generatedFileInputs() {
5835
+ const inputs = /* @__PURE__ */ new Set();
5836
+ for (const component of this.project.components) {
5837
+ if (component instanceof FileBase) {
5838
+ inputs.add(component.path);
5839
+ } else if (component instanceof SampleFile) {
5840
+ const filePath = component.filePath;
5841
+ if (typeof filePath === "string") {
5842
+ inputs.add(filePath);
5843
+ }
5844
+ } else if (component instanceof SampleDir) {
5845
+ const dir = component.dir;
5846
+ if (typeof dir === "string") {
5847
+ inputs.add(`${dir}/**`);
5848
+ }
5849
+ }
5850
+ }
5851
+ return Array.from(inputs);
5852
+ }
5853
+ preSynthesize() {
5854
+ let nextDependsOn = this.project.deps.all.filter((d) => d.version === "workspace:*").map((d) => [d.name, ROOT_TURBO_TASK_NAME].join("#"));
5855
+ if (!this.isRootProject) {
5856
+ [
5857
+ [this.project.preCompileTask, this.preCompileTask],
5858
+ [this.project.compileTask, this.compileTask],
5859
+ [this.project.postCompileTask, this.postCompileTask],
5860
+ [this.project.testTask, this.testTask],
5861
+ [this.project.packageTask, this.packageTask]
5862
+ ].forEach(([pjTask, turboTask]) => {
5863
+ if (pjTask && turboTask && pjTask.steps.length > 0) {
5864
+ if (nextDependsOn.length > 0) {
5865
+ turboTask.dependsOn.push(...nextDependsOn);
5866
+ }
5867
+ nextDependsOn = [turboTask.name];
5868
+ } else {
5869
+ turboTask.isActive = false;
5870
+ }
5871
+ });
5872
+ this.buildTask.dependsOn.push(...nextDependsOn);
5873
+ }
5874
+ const generatedInputs = this.generatedFileInputs();
5875
+ const appendGeneratedInputs = (task) => {
5876
+ if (!task) {
5877
+ return;
5878
+ }
5879
+ for (const input of generatedInputs) {
5880
+ if (!task.inputs.includes(input)) {
5881
+ task.inputs.push(input);
5882
+ }
5883
+ }
5884
+ };
5885
+ if (this.isRootProject) {
5886
+ appendGeneratedInputs(this.buildTask);
5887
+ } else {
5888
+ appendGeneratedInputs(this.preCompileTask);
5889
+ appendGeneratedInputs(this.compileTask);
5890
+ appendGeneratedInputs(this.postCompileTask);
5891
+ }
5892
+ const fileName = "turbo.json";
5893
+ this.project.addPackageIgnore(fileName);
5894
+ new JsonFile(this.project, fileName, {
5895
+ obj: {
5896
+ extends: this.extends.length ? this.extends : void 0,
5897
+ globalDependencies: this.isRootProject && this.globalDependencies.length ? this.globalDependencies : void 0,
5898
+ globalEnv: this.isRootProject && this.globalEnv.length ? this.globalEnv : void 0,
5899
+ globalPassThroughEnv: this.isRootProject && this.globalPassThroughEnv.length ? this.globalPassThroughEnv : void 0,
5900
+ ui: this.isRootProject ? this.ui : void 0,
5901
+ dangerouslyDisablePackageManagerCheck: this.isRootProject ? this.dangerouslyDisablePackageManagerCheck : void 0,
5902
+ cacheDir: this.isRootProject ? this.cacheDir : void 0,
5903
+ envMode: this.isRootProject ? this.envMode : void 0,
5904
+ /**
5905
+ * All tasks
5906
+ */
5907
+ tasks: this.tasks.filter((task) => task.isActive).reduce(
5908
+ (acc, task) => {
5909
+ acc[task.name] = {
5910
+ ...task.taskConfig()
5911
+ };
5912
+ return acc;
5913
+ },
5914
+ {
5915
+ [this.buildTask.name]: { ...this.buildTask.taskConfig() }
5916
+ }
5917
+ )
5918
+ }
5919
+ });
5920
+ super.preSynthesize();
5921
+ }
5922
+ };
5923
+ _TurboRepo.buildWorkflowOptions = (remoteCacheOptions) => {
5924
+ return {
5925
+ env: {
5926
+ GIT_BRANCH_NAME: "${{ github.head_ref || github.ref_name }}"
5927
+ },
5928
+ permissions: {
5929
+ contents: JobPermission.WRITE,
5930
+ idToken: JobPermission.WRITE
5931
+ },
5932
+ preBuildSteps: [
5933
+ {
5934
+ name: "AWS Creds for SSM",
5935
+ uses: "aws-actions/configure-aws-credentials@v6",
5936
+ with: {
5937
+ ["role-to-assume"]: remoteCacheOptions.oidcRole,
5938
+ ["aws-region"]: "us-east-1",
5939
+ ["role-duration-seconds"]: "900"
5940
+ }
5941
+ }
5942
+ ]
5943
+ };
5944
+ };
5945
+ var TurboRepo = _TurboRepo;
5946
+
5947
+ // src/agent/bundles/build-policy.ts
5948
+ var DEFAULT_BUILD_POLICY = {
5949
+ remoteCacheEnabled: false
5950
+ };
5951
+ function resolveBuildPolicy(project) {
5952
+ const remoteCacheOptions = TurboRepo.of(project)?.remoteCacheOptions;
5953
+ if (!remoteCacheOptions) {
5954
+ return DEFAULT_BUILD_POLICY;
5955
+ }
5956
+ return {
5957
+ remoteCacheEnabled: true,
5958
+ awsProfileName: remoteCacheOptions.profileName
5959
+ };
5960
+ }
5961
+
5559
5962
  // src/agent/bundles/business-models.ts
5560
5963
  var TEMPLATE_CANVAS = `---
5561
5964
  title: "Business Model: <Segment Name>"
@@ -10494,188 +10897,210 @@ var cleanMergedBranchesSkill = {
10494
10897
  }
10495
10898
  ]
10496
10899
  };
10497
- var githubWorkflowBundle = {
10498
- name: "github-workflow",
10499
- description: "GitHub issue and PR workflow automation patterns",
10500
- appliesWhen: (project) => hasComponent(project, GitHub),
10501
- rules: [
10502
- {
10503
- name: "issue-workflow",
10504
- description: "Automated workflow for starting work on a GitHub issue",
10505
- scope: AGENT_RULE_SCOPE.ALWAYS,
10506
- content: [
10507
- "# Issue Workflow",
10508
- "",
10509
- '## "Work on issue X" Automation',
10510
- "",
10511
- "When the user says **work on issue X** (or similar), invoke the `issue-worker` agent in interactive mode, passing the issue number in the prompt. Do not perform the branch creation, issue fetching, or planning steps yourself \u2014 the agent handles the full workflow (claim, branch, plan, implement, PR) and will pause for your approval at the appropriate checkpoints."
10512
- ].join("\n"),
10513
- tags: ["workflow"]
10514
- },
10515
- {
10516
- name: "create-issue-workflow",
10517
- description: "Automated workflow for creating a new GitHub issue",
10518
- // ALWAYS scope: users invoke "create an issue" from any
10519
- // context, not only when editing agent / skill / bundle source.
10520
- // Consumers that want to narrow the load can override via
10521
- // `agentConfig.additionalRulePaths` or `excludeRules`.
10522
- scope: AGENT_RULE_SCOPE.ALWAYS,
10523
- content: [
10524
- "# Create Issue Workflow",
10525
- "",
10526
- '## "Create an issue" Automation',
10527
- "",
10528
- "When the user says **create an issue** (or similar), follow these steps exactly:",
10529
- "",
10530
- "1. **Determine the issue type prefix** from the user's description:",
10531
- " - `epic:` \u2014 Large initiatives spanning multiple child issues",
10532
- " - `feat:` \u2014 New features or functionality",
10533
- " - `fix:` \u2014 Bug fixes",
10534
- " - `chore:` \u2014 Maintenance: deps, tooling, config",
10535
- " - `docs:` \u2014 Documentation-only work",
10536
- " - `refactor:` \u2014 Code restructure, no behavior change",
10537
- " - `release:` \u2014 Release preparation, version bumps",
10538
- " - `hotfix:` \u2014 Urgent production fixes",
10539
- " - If unclear, ask the user which type applies",
10540
- "2. **Compose the issue title** in the format: `<type>: <short description>`",
10541
- "3. **Determine the GitHub issue type** based on the prefix:",
10542
- " - `epic:` \u2192 Epic",
10543
- " - `feat:` \u2192 Feature",
10544
- " - `fix:` \u2192 Bug",
10545
- " - `chore:`, `docs:`, `refactor:`, `release:`, `hotfix:` \u2192 Task",
10546
- "4. **Identify prerequisite issues** \u2014 if the user mentions dependencies or blockers, include a **Dependencies** section in the body with `Depends on: #<issue-number>`",
10547
- "5. **Determine labels** \u2014 every issue must be created with the following labels:",
10548
- " - **`type:*`** \u2014 derived from the issue title prefix:",
10549
- " - `epic:` \u2192 `type:feat`",
10550
- " - `feat:` \u2192 `type:feat`",
10551
- " - `fix:` \u2192 `type:fix`",
10552
- " - `chore:` \u2192 `type:chore`",
10553
- " - `docs:` \u2192 `type:docs`",
10554
- " - `refactor:` \u2192 `type:refactor`",
10555
- " - `release:` \u2192 `type:release`",
10556
- " - `hotfix:` \u2192 `type:hotfix`",
10557
- ' - **`priority:*`** \u2014 infer from the user\'s description when possible (e.g., "urgent"/"critical" \u2192 `priority:critical`, "important" \u2192 `priority:high`, "minor"/"low priority" \u2192 `priority:low`). If the priority is unclear, ask the user before creating the issue. Valid values: `priority:critical`, `priority:high`, `priority:medium`, `priority:low`, `priority:trivial`',
10558
- " - **`status:ready`** \u2014 always add unless the issue has dependencies or blockers, in which case use `status:blocked`",
10559
- "6. **Create the issue** using `gh issue create`:",
10560
- " - `--title '<type>: <description>'`",
10561
- " - `--body '<issue body>'`",
10562
- " - `--label '<type-label>' --label '<priority-label>' --label '<status-label>'`",
10563
- "7. **Set the GitHub issue type** by invoking the `set-issue-type.sh` helper (shipped with this bundle):",
10564
- "",
10565
- " ```sh",
10566
- " .claude/procedures/set-issue-type.sh <issue-number> <Feature|Task|Epic|Bug>",
10567
- " ```",
10568
- "",
10569
- " The helper resolves owner/repo, looks up the issue type node ID, looks up the issue node ID, and applies the `updateIssueIssueType` mutation in one step. It exits non-zero with a clear diagnostic on any error and lists available types if the type name is not recognised.",
10570
- "",
10571
- " **Under the hood** (documented fallback if the helper is unavailable): the helper performs a two-step GraphQL flow \u2014 first a `repository(...).issueTypes` query to map the human-readable type name to a node ID, then the `updateIssueIssueType` mutation. The canonical queries are:",
10572
- "",
10573
- " ```sh",
10574
- " gh api graphql -f query='query($owner:String!,$repo:String!){repository(owner:$owner,name:$repo){issueTypes(first:50){nodes{id name}}}}' -f owner=<owner> -f repo=<repo>",
10575
- " gh api graphql -f query='mutation($issueId:ID!,$typeId:ID!){updateIssueIssueType(input:{issueId:$issueId,issueTypeId:$typeId}){issue{number issueType{name}}}}' -f issueId=<issue-node-id> -f typeId=<issue-type-node-id>",
10576
- " ```",
10577
- "",
10578
- "### Issue Body Template",
10579
- "",
10580
- "```markdown",
10581
- "## Summary",
10582
- "",
10583
- "<1-3 sentences describing the issue>",
10584
- "",
10585
- "## Details",
10586
- "",
10587
- "<Detailed description, acceptance criteria, or reproduction steps as appropriate>",
10588
- "",
10589
- "## Dependencies",
10590
- "",
10591
- "Depends on: #<issue-number> (if any, otherwise omit this section)",
10592
- "```",
10593
- "",
10594
- "### Important",
10595
- "",
10596
- "- Always use the conventional prefix in the issue title",
10597
- "- Always assign the correct GitHub issue type via the `set-issue-type.sh` helper (step 7) \u2014 never via `gh issue create --type`",
10598
- "- Always include `type:*`, `priority:*`, and `status:*` labels",
10599
- "- If the user does not specify a type, ask before creating the issue",
10600
- "- If the priority cannot be inferred from the description, ask the user before creating the issue",
10601
- "- Keep titles concise and descriptive"
10602
- ].join("\n"),
10603
- tags: ["workflow"]
10604
- },
10605
- {
10606
- name: "pr-workflow",
10607
- description: "Automated workflow for opening a pull request",
10608
- scope: AGENT_RULE_SCOPE.ALWAYS,
10609
- content: [
10610
- "# PR Workflow",
10611
- "",
10612
- '## "Open a PR" Automation',
10613
- "",
10614
- "When the user says **open a PR** (or similar), follow these steps exactly:",
10615
- "",
10616
- "1. **Regenerate project files** \u2014 run the three-step regen sequence (`pnpm i`, then `pnpm exec projen`, then `pnpm i` again) to ensure all generated files are up to date. The leading `pnpm i` is required because `pnpm exec projen` synthesises against whatever version of configulator (and projen, and any projen plugins) is currently resolved in `node_modules`; if the lockfile has moved past `node_modules` (typically right after `git pull` lands a dependency upgrade, or on a fresh checkout), synth runs against stale templates and produces phantom drift in `.claude/`, `.github/labels.yml`, `CLAUDE.md`, and other generated files. The trailing `pnpm i` picks up any dependency changes projen wrote into `package.json` during synth. Check `git diff` after the third step \u2014 if there are changes, commit them before proceeding.",
10617
- "2. **Run the full monorepo build** \u2014 run `pnpm build:all` to compile, lint, and test all packages (mirrors the CI pipeline). This command requires the user to be authenticated to AWS on the prod account used for Turborepo remote caching (`readonlyaccess-prod-525259625215-us-east-1` profile). If the command fails due to AWS credentials, ask the user to authenticate first. If the build produces changes to turbo inputs (typically snapshot files or ESLint auto-fixes), commit those changes and run `pnpm build:all` again \u2014 the build must complete cleanly with no uncommitted changes.",
10618
- "3. **Check for uncommitted changes** \u2014 if any exist, commit them with a conventional commit message",
10619
- "4. **Pull and rebase from the default branch** \u2014 run `git pull origin {{repository.defaultBranch}} --rebase` to incorporate the latest changes and resolve any conflicts before pushing",
10620
- "5. **Push the branch** to origin: `git push -u origin <branch>`",
10621
- "6. **Create the PR** using `gh pr create`:",
10622
- " - **Title**: use a conventional commit style title (e.g., `feat(scope): short description`)",
10623
- " - **Body**: include `Closes #<issue-number>` (derived from the branch name) and a brief summary of changes",
10624
- "7. **Delegate review and merge to the `pr-reviewer` sub-agent.** After the PR is created, invoke the `/review-pr <pr-number>` skill (or otherwise hand the new PR number to the `pr-reviewer` sub-agent). The reviewer verifies the diff against the linked issue's acceptance criteria and enables squash auto-merge when all checks pass. Do **not** run `gh pr merge --auto` yourself \u2014 review/merge policy lives solely in the `pr-reviewer` agent.",
10625
- "",
10626
- "### PR Body Template",
10627
- "",
10628
- "```markdown",
10629
- "## Summary",
10630
- "",
10631
- "<1-3 bullet points describing what changed and why>",
10632
- "",
10633
- "Closes #<issue-number>",
10634
- "",
10635
- "## Test Plan",
10636
- "",
10637
- "- [ ] Tests pass locally",
10638
- "- [ ] Relevant changes have been reviewed",
10639
- "```",
10640
- "",
10641
- "### Important",
10642
- "",
10643
- "- Always derive the issue number from the branch name (e.g., `feat/42-add-login` \u2192 `#42`)",
10644
- "- Use conventional commit format for the PR title",
10645
- "- Delegate merge to the `pr-reviewer` sub-agent \u2014 do not merge manually and do not enable auto-merge directly"
10646
- ].join("\n"),
10647
- tags: ["workflow"]
10648
- },
10649
- {
10650
- name: "branch-cleanup",
10651
- description: "Local-branch hygiene helpers shipped with the github-workflow bundle, including the /clean-merged-branches skill for safely force-deleting branches whose content has already merged into the base (handles squash merges).",
10652
- scope: AGENT_RULE_SCOPE.ALWAYS,
10653
- content: [
10654
- "# Branch Cleanup",
10655
- "",
10656
- "Local branches accumulate after every merged PR. In squash-merge",
10657
- "repositories `git branch -d` refuses to delete them because the",
10658
- "commit hash on the base differs, even when the branch content is",
10659
- "fully merged. The `github-workflow` bundle ships two affordances",
10660
- "that use content-equality (not commit-graph reachability) to",
10661
- "identify branches safe to force-delete:",
10662
- "",
10663
- "- `/clean-merged-branches` \u2014 interactive slash-command skill that",
10664
- " classifies every local branch, prompts for confirmation, then",
10665
- " runs `git branch -D` on the confirmed list. See",
10666
- " `.claude/skills/clean-merged-branches/SKILL.md` for usage,",
10667
- " output format, and the squash-merge verification algorithm.",
10668
- "- `.claude/procedures/clean-merged-branches.sh` \u2014 analysis-only",
10669
- " procedure for non-interactive agent use (orchestrator,",
10670
- " maintenance-audit). NEVER deletes \u2014 only reports `MERGED` /",
10671
- " `UNMERGED` / `EMPTY` / `SKIP_WORKTREE` lines."
10672
- ].join("\n"),
10673
- tags: ["workflow"]
10674
- }
10675
- ],
10676
- skills: [cleanMergedBranchesSkill],
10677
- procedures: [setIssueTypeProcedure, cleanMergedBranchesProcedure]
10678
- };
10900
+ function renderPrWorkflowBuildStep(policy) {
10901
+ const lines = [
10902
+ "2. **Run the build \u2014 scoped to what changed.**",
10903
+ "",
10904
+ " - **Documentation-only changes** \u2014 a diff confined to documentation content (markdown pages, no source, config, or projen inputs) does **not** require `pnpm build:all`. There is nothing to compile, and CI is the authoritative content gate. Commit the content and proceed to the next step.",
10905
+ " - **Everything else** \u2014 when the change touches build inputs (source code, `.projenrc.ts`, `projenrc/**`, or any other projen-generated config), run `pnpm build:all` to compile, lint, and test all packages (mirrors the CI pipeline). If the build produces changes to turbo inputs (typically snapshot files or ESLint auto-fixes), commit those changes and run `pnpm build:all` again \u2014 the build must complete cleanly with no uncommitted changes."
10906
+ ];
10907
+ if (policy.remoteCacheEnabled && policy.awsProfileName) {
10908
+ lines.push(
10909
+ "",
10910
+ ` \`pnpm build:all\` uses the Turborepo **remote cache**, which requires the user to be authenticated to AWS on the \`${policy.awsProfileName}\` profile. If the command fails due to AWS credentials, ask the user to authenticate first.`
10911
+ );
10912
+ }
10913
+ lines.push(
10914
+ "",
10915
+ " **Never background a long build and end the turn.** If you run a build, run it in the **foreground** to completion before committing, pushing, or opening the PR. Launching `pnpm build:all` as a background process and ending your turn while it is still running strands the deliverable uncommitted \u2014 that work is lost. This is the documented root cause of autonomous worker-stall incidents."
10916
+ );
10917
+ return lines;
10918
+ }
10919
+ function buildGithubWorkflowBundle(buildPolicy = DEFAULT_BUILD_POLICY) {
10920
+ return {
10921
+ name: "github-workflow",
10922
+ description: "GitHub issue and PR workflow automation patterns",
10923
+ appliesWhen: (project) => hasComponent(project, GitHub),
10924
+ rules: [
10925
+ {
10926
+ name: "issue-workflow",
10927
+ description: "Automated workflow for starting work on a GitHub issue",
10928
+ scope: AGENT_RULE_SCOPE.ALWAYS,
10929
+ content: [
10930
+ "# Issue Workflow",
10931
+ "",
10932
+ '## "Work on issue X" Automation',
10933
+ "",
10934
+ "When the user says **work on issue X** (or similar), invoke the `issue-worker` agent in interactive mode, passing the issue number in the prompt. Do not perform the branch creation, issue fetching, or planning steps yourself \u2014 the agent handles the full workflow (claim, branch, plan, implement, PR) and will pause for your approval at the appropriate checkpoints."
10935
+ ].join("\n"),
10936
+ tags: ["workflow"]
10937
+ },
10938
+ {
10939
+ name: "create-issue-workflow",
10940
+ description: "Automated workflow for creating a new GitHub issue",
10941
+ // ALWAYS scope: users invoke "create an issue" from any
10942
+ // context, not only when editing agent / skill / bundle source.
10943
+ // Consumers that want to narrow the load can override via
10944
+ // `agentConfig.additionalRulePaths` or `excludeRules`.
10945
+ scope: AGENT_RULE_SCOPE.ALWAYS,
10946
+ content: [
10947
+ "# Create Issue Workflow",
10948
+ "",
10949
+ '## "Create an issue" Automation',
10950
+ "",
10951
+ "When the user says **create an issue** (or similar), follow these steps exactly:",
10952
+ "",
10953
+ "1. **Determine the issue type prefix** from the user's description:",
10954
+ " - `epic:` \u2014 Large initiatives spanning multiple child issues",
10955
+ " - `feat:` \u2014 New features or functionality",
10956
+ " - `fix:` \u2014 Bug fixes",
10957
+ " - `chore:` \u2014 Maintenance: deps, tooling, config",
10958
+ " - `docs:` \u2014 Documentation-only work",
10959
+ " - `refactor:` \u2014 Code restructure, no behavior change",
10960
+ " - `release:` \u2014 Release preparation, version bumps",
10961
+ " - `hotfix:` \u2014 Urgent production fixes",
10962
+ " - If unclear, ask the user which type applies",
10963
+ "2. **Compose the issue title** in the format: `<type>: <short description>`",
10964
+ "3. **Determine the GitHub issue type** based on the prefix:",
10965
+ " - `epic:` \u2192 Epic",
10966
+ " - `feat:` \u2192 Feature",
10967
+ " - `fix:` \u2192 Bug",
10968
+ " - `chore:`, `docs:`, `refactor:`, `release:`, `hotfix:` \u2192 Task",
10969
+ "4. **Identify prerequisite issues** \u2014 if the user mentions dependencies or blockers, include a **Dependencies** section in the body with `Depends on: #<issue-number>`",
10970
+ "5. **Determine labels** \u2014 every issue must be created with the following labels:",
10971
+ " - **`type:*`** \u2014 derived from the issue title prefix:",
10972
+ " - `epic:` \u2192 `type:feat`",
10973
+ " - `feat:` \u2192 `type:feat`",
10974
+ " - `fix:` \u2192 `type:fix`",
10975
+ " - `chore:` \u2192 `type:chore`",
10976
+ " - `docs:` \u2192 `type:docs`",
10977
+ " - `refactor:` \u2192 `type:refactor`",
10978
+ " - `release:` \u2192 `type:release`",
10979
+ " - `hotfix:` \u2192 `type:hotfix`",
10980
+ ' - **`priority:*`** \u2014 infer from the user\'s description when possible (e.g., "urgent"/"critical" \u2192 `priority:critical`, "important" \u2192 `priority:high`, "minor"/"low priority" \u2192 `priority:low`). If the priority is unclear, ask the user before creating the issue. Valid values: `priority:critical`, `priority:high`, `priority:medium`, `priority:low`, `priority:trivial`',
10981
+ " - **`status:ready`** \u2014 always add unless the issue has dependencies or blockers, in which case use `status:blocked`",
10982
+ "6. **Create the issue** using `gh issue create`:",
10983
+ " - `--title '<type>: <description>'`",
10984
+ " - `--body '<issue body>'`",
10985
+ " - `--label '<type-label>' --label '<priority-label>' --label '<status-label>'`",
10986
+ "7. **Set the GitHub issue type** by invoking the `set-issue-type.sh` helper (shipped with this bundle):",
10987
+ "",
10988
+ " ```sh",
10989
+ " .claude/procedures/set-issue-type.sh <issue-number> <Feature|Task|Epic|Bug>",
10990
+ " ```",
10991
+ "",
10992
+ " The helper resolves owner/repo, looks up the issue type node ID, looks up the issue node ID, and applies the `updateIssueIssueType` mutation in one step. It exits non-zero with a clear diagnostic on any error and lists available types if the type name is not recognised.",
10993
+ "",
10994
+ " **Under the hood** (documented fallback if the helper is unavailable): the helper performs a two-step GraphQL flow \u2014 first a `repository(...).issueTypes` query to map the human-readable type name to a node ID, then the `updateIssueIssueType` mutation. The canonical queries are:",
10995
+ "",
10996
+ " ```sh",
10997
+ " gh api graphql -f query='query($owner:String!,$repo:String!){repository(owner:$owner,name:$repo){issueTypes(first:50){nodes{id name}}}}' -f owner=<owner> -f repo=<repo>",
10998
+ " gh api graphql -f query='mutation($issueId:ID!,$typeId:ID!){updateIssueIssueType(input:{issueId:$issueId,issueTypeId:$typeId}){issue{number issueType{name}}}}' -f issueId=<issue-node-id> -f typeId=<issue-type-node-id>",
10999
+ " ```",
11000
+ "",
11001
+ "### Issue Body Template",
11002
+ "",
11003
+ "```markdown",
11004
+ "## Summary",
11005
+ "",
11006
+ "<1-3 sentences describing the issue>",
11007
+ "",
11008
+ "## Details",
11009
+ "",
11010
+ "<Detailed description, acceptance criteria, or reproduction steps as appropriate>",
11011
+ "",
11012
+ "## Dependencies",
11013
+ "",
11014
+ "Depends on: #<issue-number> (if any, otherwise omit this section)",
11015
+ "```",
11016
+ "",
11017
+ "### Important",
11018
+ "",
11019
+ "- Always use the conventional prefix in the issue title",
11020
+ "- Always assign the correct GitHub issue type via the `set-issue-type.sh` helper (step 7) \u2014 never via `gh issue create --type`",
11021
+ "- Always include `type:*`, `priority:*`, and `status:*` labels",
11022
+ "- If the user does not specify a type, ask before creating the issue",
11023
+ "- If the priority cannot be inferred from the description, ask the user before creating the issue",
11024
+ "- Keep titles concise and descriptive"
11025
+ ].join("\n"),
11026
+ tags: ["workflow"]
11027
+ },
11028
+ {
11029
+ name: "pr-workflow",
11030
+ description: "Automated workflow for opening a pull request",
11031
+ scope: AGENT_RULE_SCOPE.ALWAYS,
11032
+ content: [
11033
+ "# PR Workflow",
11034
+ "",
11035
+ '## "Open a PR" Automation',
11036
+ "",
11037
+ "When the user says **open a PR** (or similar), follow these steps exactly:",
11038
+ "",
11039
+ "1. **Regenerate project files** \u2014 run the three-step regen sequence (`pnpm i`, then `pnpm exec projen`, then `pnpm i` again) to ensure all generated files are up to date. The leading `pnpm i` is required because `pnpm exec projen` synthesises against whatever version of configulator (and projen, and any projen plugins) is currently resolved in `node_modules`; if the lockfile has moved past `node_modules` (typically right after `git pull` lands a dependency upgrade, or on a fresh checkout), synth runs against stale templates and produces phantom drift in `.claude/`, `.github/labels.yml`, `CLAUDE.md`, and other generated files. The trailing `pnpm i` picks up any dependency changes projen wrote into `package.json` during synth. Check `git diff` after the third step \u2014 if there are changes, commit them before proceeding.",
11040
+ ...renderPrWorkflowBuildStep(buildPolicy),
11041
+ "3. **Check for uncommitted changes** \u2014 if any exist, commit them with a conventional commit message",
11042
+ "4. **Pull and rebase from the default branch** \u2014 run `git pull origin {{repository.defaultBranch}} --rebase` to incorporate the latest changes and resolve any conflicts before pushing",
11043
+ "5. **Push the branch** to origin: `git push -u origin <branch>`",
11044
+ "6. **Create the PR** using `gh pr create`:",
11045
+ " - **Title**: use a conventional commit style title (e.g., `feat(scope): short description`)",
11046
+ " - **Body**: include `Closes #<issue-number>` (derived from the branch name) and a brief summary of changes",
11047
+ "7. **Delegate review and merge to the `pr-reviewer` sub-agent.** After the PR is created, invoke the `/review-pr <pr-number>` skill (or otherwise hand the new PR number to the `pr-reviewer` sub-agent). The reviewer verifies the diff against the linked issue's acceptance criteria and enables squash auto-merge when all checks pass. Do **not** run `gh pr merge --auto` yourself \u2014 review/merge policy lives solely in the `pr-reviewer` agent.",
11048
+ "",
11049
+ "### PR Body Template",
11050
+ "",
11051
+ "```markdown",
11052
+ "## Summary",
11053
+ "",
11054
+ "<1-3 bullet points describing what changed and why>",
11055
+ "",
11056
+ "Closes #<issue-number>",
11057
+ "",
11058
+ "## Test Plan",
11059
+ "",
11060
+ "- [ ] Tests pass locally",
11061
+ "- [ ] Relevant changes have been reviewed",
11062
+ "```",
11063
+ "",
11064
+ "### Important",
11065
+ "",
11066
+ "- Always derive the issue number from the branch name (e.g., `feat/42-add-login` \u2192 `#42`)",
11067
+ "- Use conventional commit format for the PR title",
11068
+ "- Delegate merge to the `pr-reviewer` sub-agent \u2014 do not merge manually and do not enable auto-merge directly"
11069
+ ].join("\n"),
11070
+ tags: ["workflow"]
11071
+ },
11072
+ {
11073
+ name: "branch-cleanup",
11074
+ description: "Local-branch hygiene helpers shipped with the github-workflow bundle, including the /clean-merged-branches skill for safely force-deleting branches whose content has already merged into the base (handles squash merges).",
11075
+ scope: AGENT_RULE_SCOPE.ALWAYS,
11076
+ content: [
11077
+ "# Branch Cleanup",
11078
+ "",
11079
+ "Local branches accumulate after every merged PR. In squash-merge",
11080
+ "repositories `git branch -d` refuses to delete them because the",
11081
+ "commit hash on the base differs, even when the branch content is",
11082
+ "fully merged. The `github-workflow` bundle ships two affordances",
11083
+ "that use content-equality (not commit-graph reachability) to",
11084
+ "identify branches safe to force-delete:",
11085
+ "",
11086
+ "- `/clean-merged-branches` \u2014 interactive slash-command skill that",
11087
+ " classifies every local branch, prompts for confirmation, then",
11088
+ " runs `git branch -D` on the confirmed list. See",
11089
+ " `.claude/skills/clean-merged-branches/SKILL.md` for usage,",
11090
+ " output format, and the squash-merge verification algorithm.",
11091
+ "- `.claude/procedures/clean-merged-branches.sh` \u2014 analysis-only",
11092
+ " procedure for non-interactive agent use (orchestrator,",
11093
+ " maintenance-audit). NEVER deletes \u2014 only reports `MERGED` /",
11094
+ " `UNMERGED` / `EMPTY` / `SKIP_WORKTREE` lines."
11095
+ ].join("\n"),
11096
+ tags: ["workflow"]
11097
+ }
11098
+ ],
11099
+ skills: [cleanMergedBranchesSkill],
11100
+ procedures: [setIssueTypeProcedure, cleanMergedBranchesProcedure]
11101
+ };
11102
+ }
11103
+ var githubWorkflowBundle = buildGithubWorkflowBundle();
10679
11104
 
10680
11105
  // src/agent/bundles/industry-discovery.ts
10681
11106
  function buildIndustryDiscoveryAnalystSubAgent(paths, issueDefaults) {
@@ -12875,188 +13300,6 @@ function buildMeetingAnalysisBundle(tier = AGENT_MODEL.BALANCED) {
12875
13300
  }
12876
13301
  var meetingAnalysisBundle = buildMeetingAnalysisBundle();
12877
13302
 
12878
- // src/agent/bundles/run-ratio.ts
12879
- var DEFAULT_DISPATCH_TO_HOUSEKEEPING_RATIO = 4;
12880
- var DEFAULT_STATE_FILE_PATH = ".state/orchestrator-runs.json";
12881
- var DEFAULT_DISPATCH_MODEL = "opus";
12882
- var DEFAULT_HOUSEKEEPING_MODEL = "sonnet";
12883
- function resolveRunRatio(config) {
12884
- const ratio = config?.ratio ?? DEFAULT_DISPATCH_TO_HOUSEKEEPING_RATIO;
12885
- assertValidRatio(ratio);
12886
- const stateFilePath = config?.stateFilePath ?? DEFAULT_STATE_FILE_PATH;
12887
- assertValidStateFilePath(stateFilePath);
12888
- return {
12889
- enabled: config?.enabled ?? true,
12890
- ratio,
12891
- stateFilePath,
12892
- dispatchModel: config?.dispatchModel ?? DEFAULT_DISPATCH_MODEL,
12893
- housekeepingModel: config?.housekeepingModel ?? DEFAULT_HOUSEKEEPING_MODEL
12894
- };
12895
- }
12896
- function validateRunRatioConfig(config) {
12897
- return resolveRunRatio(config);
12898
- }
12899
- function classifyRun(runCounter, ratio) {
12900
- if (!ratio.enabled) {
12901
- return "dispatch";
12902
- }
12903
- const cycle = ratio.ratio + 1;
12904
- return runCounter > 0 && runCounter % cycle === 0 ? "housekeeping" : "dispatch";
12905
- }
12906
- function renderRunRatioSection(ratio) {
12907
- const lines = [
12908
- "## Run ratio (dispatch vs housekeeping)",
12909
- "",
12910
- "The orchestrator keeps a **persistent run counter** and interleaves",
12911
- "dispatch runs (pick the next ready issue, recommend a worker) with",
12912
- "**housekeeping runs** (batch PR review + maintenance scan) on a",
12913
- "configurable ratio. This mirrors openhi's `DISPATCHER.md` contract:",
12914
- "multiple dispatch runs feed the worker queue, then one batched",
12915
- "housekeeping run flushes review backlog and runs maintenance",
12916
- "triage so the pipeline never drifts.",
12917
- ""
12918
- ];
12919
- if (!ratio.enabled) {
12920
- lines.push(
12921
- "**The run ratio is disabled for this project.** Every orchestrator",
12922
- "run executes the full dispatch pipeline; PR review and maintenance",
12923
- "remain manual invocations. Enable the ratio via",
12924
- "`AgentConfigOptions.runRatio.enabled = true` once the operator is",
12925
- "comfortable with the counter-backed cadence.",
12926
- ""
12927
- );
12928
- return lines.join("\n");
12929
- }
12930
- const cycle = ratio.ratio + 1;
12931
- lines.push(
12932
- "### Cadence",
12933
- "",
12934
- `The cycle length is **${cycle}** runs:`,
12935
- "",
12936
- `- Runs 1 through ${ratio.ratio} execute the **dispatch** pipeline`,
12937
- ` (recommended model: \`${ratio.dispatchModel}\`).`,
12938
- `- Run ${cycle} executes the **housekeeping** pipeline`,
12939
- ` (recommended model: \`${ratio.housekeepingModel}\`).`,
12940
- `- The counter wraps \u2014 run ${cycle + 1} is a dispatch run again, run ${cycle * 2} is the next housekeeping run, and so on.`,
12941
- "",
12942
- "The orchestrator increments the counter **once per invocation** at",
12943
- "the top of the run, before any pipeline phase executes. The",
12944
- "pre-increment value is never observed \u2014 the tick always returns",
12945
- "the post-increment counter and the classified run type in a single",
12946
- "atomic update.",
12947
- "",
12948
- "### State file",
12949
- "",
12950
- `The run counter persists at \`${ratio.stateFilePath}\`. The file is`,
12951
- "plain JSON with a single `run_counter` integer field:",
12952
- "",
12953
- "```json",
12954
- '{ "run_counter": 42 }',
12955
- "```",
12956
- "",
12957
- "The state file is **gitignored** in consumer repos (it is local to",
12958
- "each operator's machine). On a first run, or if the file is missing",
12959
- "or corrupt, the orchestrator recreates it with `run_counter: 1`.",
12960
- "",
12961
- "### Dispatch-run pipeline",
12962
- "",
12963
- "1. Phase A \u2014 startup (fetch + checkout default branch).",
12964
- "2. Phase C \u2014 triage unblock (resolve `Depends on:` chains).",
12965
- "3. Phase E \u2014 queue scan (pick the top `PICK` line, run the scope",
12966
- " gate, emit `NEXT_WORK_ITEM`).",
12967
- "4. Phase F \u2014 cleanup.",
12968
- "",
12969
- "### Housekeeping-run pipeline",
12970
- "",
12971
- "1. Phase A \u2014 startup.",
12972
- "2. Phase B \u2014 batch PR review across every eligible open PR.",
12973
- "3. Phase D \u2014 maintenance scan (stale detection, orphaned branches,",
12974
- " needs-attention summary).",
12975
- "4. Phase F \u2014 cleanup.",
12976
- "",
12977
- "### Model recommendations",
12978
- "",
12979
- `Dispatch runs should use \`${ratio.dispatchModel}\` \u2014 the routing`,
12980
- "logic, scope gate, and funnel-tier sort benefit from the stronger",
12981
- "reasoning model. Housekeeping runs are mechanical (read CI status,",
12982
- "toggle labels, post canned comments) and should use",
12983
- `\`${ratio.housekeepingModel}\` so the batched PR review and`,
12984
- "maintenance scan cost less per invocation.",
12985
- "",
12986
- "These strings are **informational** \u2014 they surface in the",
12987
- "orchestrator's rendered rule content so operators know which model",
12988
- "to run each session against. Configulator does not inject them as",
12989
- "`model:` frontmatter on the sub-agent definition; the operator (or",
12990
- "a scheduled task) picks the model at invocation time."
12991
- );
12992
- return lines.join("\n");
12993
- }
12994
- function renderRunRatioShellHelpers(ratio) {
12995
- const cycle = ratio.ratio + 1;
12996
- return [
12997
- "# Increment the orchestrator run counter and classify the run.",
12998
- "# Reads the state file (creating it on first run or corruption),",
12999
- "# increments the counter, writes back atomically, and echoes",
13000
- "# `run=<n> type=<dispatch|housekeeping>` on stdout.",
13001
- "#",
13002
- "# Uses the cycle length (ratio + 1) hard-coded from the resolved",
13003
- "# RunRatioConfig so the shell helper matches the rendered rule",
13004
- "# content byte-for-byte.",
13005
- "run_counter_tick() {",
13006
- ' local state_file="$ORCHESTRATOR_STATE_FILE"',
13007
- " local state_dir",
13008
- ' state_dir=$(dirname "$state_file")',
13009
- ' mkdir -p "$state_dir" 2>/dev/null || true',
13010
- "",
13011
- " local current=0",
13012
- ' if [ -f "$state_file" ]; then',
13013
- " # jq returns empty string on parse failure; guard against it.",
13014
- ` current=$(jq -r '.run_counter // 0' "$state_file" 2>/dev/null || echo 0)`,
13015
- ' case "$current" in',
13016
- " ''|*[!0-9]*) current=0 ;;",
13017
- " esac",
13018
- " fi",
13019
- "",
13020
- " local next=$((current + 1))",
13021
- "",
13022
- ' local tmp_file="${state_file}.tmp.$$"',
13023
- ` printf '{ "run_counter": %d }\\n' "$next" > "$tmp_file"`,
13024
- ' mv "$tmp_file" "$state_file"',
13025
- "",
13026
- " local run_type=dispatch",
13027
- ` if [ $((next % ${cycle})) -eq 0 ]; then`,
13028
- " run_type=housekeeping",
13029
- " fi",
13030
- ` printf 'run=%d type=%s\\n' "$next" "$run_type"`,
13031
- "}"
13032
- ].join("\n");
13033
- }
13034
- function assertValidRatio(ratio) {
13035
- if (!Number.isInteger(ratio)) {
13036
- throw new Error(
13037
- `RunRatioConfig.ratio must be a positive integer; got ${ratio}`
13038
- );
13039
- }
13040
- if (ratio < 1) {
13041
- throw new Error(
13042
- `RunRatioConfig.ratio must be a positive integer; got ${ratio}`
13043
- );
13044
- }
13045
- }
13046
- function assertValidStateFilePath(stateFilePath) {
13047
- const trimmed = stateFilePath.trim();
13048
- if (trimmed.length === 0) {
13049
- throw new Error(
13050
- "RunRatioConfig.stateFilePath must be a non-empty string relative to the repo root"
13051
- );
13052
- }
13053
- if (trimmed.startsWith("/")) {
13054
- throw new Error(
13055
- `RunRatioConfig.stateFilePath must be relative to the repo root (no leading '/'); got ${stateFilePath}`
13056
- );
13057
- }
13058
- }
13059
-
13060
13303
  // src/agent/bundles/bundle-ownership.ts
13061
13304
  var BUNDLE_OWNERSHIP = {
13062
13305
  agenda: {
@@ -13200,6 +13443,255 @@ var BUNDLE_OWNERSHIP = {
13200
13443
  downstreamIssueKinds: true
13201
13444
  }
13202
13445
  };
13446
+ var CONVENTIONAL_COMMIT_TYPE_LABELS = [
13447
+ "type:chore",
13448
+ "type:docs",
13449
+ "type:feat",
13450
+ "type:fix",
13451
+ "type:hotfix",
13452
+ "type:refactor",
13453
+ "type:release"
13454
+ ];
13455
+ var PHASE_LABEL_TYPE_MAP = buildPhaseLabelTypeMap();
13456
+ function typeLabelForPhaseLabel(phaseLabel) {
13457
+ const exact = PHASE_LABEL_TYPE_MAP[phaseLabel];
13458
+ if (exact !== void 0 && !phaseLabel.endsWith(":")) {
13459
+ return exact;
13460
+ }
13461
+ let bestMatcher;
13462
+ for (const matcher of Object.keys(PHASE_LABEL_TYPE_MAP)) {
13463
+ if (!matcher.endsWith(":")) {
13464
+ continue;
13465
+ }
13466
+ if (!phaseLabel.startsWith(matcher)) {
13467
+ continue;
13468
+ }
13469
+ if (bestMatcher === void 0 || matcher.length > bestMatcher.length) {
13470
+ bestMatcher = matcher;
13471
+ }
13472
+ }
13473
+ return bestMatcher === void 0 ? void 0 : PHASE_LABEL_TYPE_MAP[bestMatcher];
13474
+ }
13475
+ function resolveTypeLabelForLabels(labels) {
13476
+ const phaseLabels = [];
13477
+ const candidates = /* @__PURE__ */ new Set();
13478
+ for (const label of labels) {
13479
+ const typeLabel = typeLabelForPhaseLabel(label);
13480
+ if (typeLabel === void 0) {
13481
+ continue;
13482
+ }
13483
+ phaseLabels.push(label);
13484
+ candidates.add(typeLabel);
13485
+ }
13486
+ const candidateTypeLabels = Array.from(candidates).sort();
13487
+ if (candidateTypeLabels.length === 0) {
13488
+ return { outcome: "none", candidateTypeLabels: [], phaseLabels: [] };
13489
+ }
13490
+ if (candidateTypeLabels.length === 1) {
13491
+ return {
13492
+ outcome: "match",
13493
+ typeLabel: candidateTypeLabels[0],
13494
+ candidateTypeLabels,
13495
+ phaseLabels
13496
+ };
13497
+ }
13498
+ return { outcome: "ambiguous", candidateTypeLabels, phaseLabels };
13499
+ }
13500
+ function renderPhaseTypeInvariantSection(excludeBundles = []) {
13501
+ const rows = Object.keys(PHASE_LABEL_TYPE_MAP).filter(
13502
+ (matcher) => !isPhaseLabelMatcherOwnedByExcluded(matcher, excludeBundles)
13503
+ ).sort().map((matcher) => {
13504
+ const display = matcher.endsWith(":") ? `${matcher}*` : matcher;
13505
+ const kind = matcher.endsWith(":") ? "prefix" : "exact";
13506
+ return `| \`${display}\` | ${kind} | \`${PHASE_LABEL_TYPE_MAP[matcher]}\` |`;
13507
+ });
13508
+ return [
13509
+ "## Phase-label \u2192 `type:<bundle>` invariant",
13510
+ "",
13511
+ "Every phased-pipeline bundle pairs its `<bundle>:<phase>` labels",
13512
+ "with exactly one `type:<bundle>` label. That type label is the",
13513
+ "**dedup + dispatch signal**: agents de-duplicate downstream work",
13514
+ 'with `gh issue list --label "type:<bundle>"`, and Phase E derives',
13515
+ "its funnel-tier sort key from the issue's `type:*` label. An issue",
13516
+ "that carries the phase label but a conventional-commit `type:*`",
13517
+ "(`type:feat`, `type:docs`, \u2026, stamped from its title prefix by the",
13518
+ "generic create-issue workflow) is invisible to that dedup query and",
13519
+ "mis-tiers in dispatch.",
13520
+ "",
13521
+ "The pairing below is derived from the canonical bundle-ownership",
13522
+ "map \u2014 the same source of truth that generates the label registry.",
13523
+ "Matchers ending in `*` match by prefix; the rest match exactly, and",
13524
+ "an exact match always beats a prefix match.",
13525
+ "",
13526
+ "| Phase label | Match | Required type label |",
13527
+ "|-------------|-------|---------------------|",
13528
+ ...rows,
13529
+ "",
13530
+ "### Enforcement",
13531
+ "",
13532
+ "The Phase D maintenance sweep runs the invariant in auto-correct",
13533
+ "mode and emits one summary line:",
13534
+ "",
13535
+ "```",
13536
+ "LABEL_INVARIANT_DONE mode=fix checked=<N> ok=<O> violations=<V> corrected=<C> flagged=<F>",
13537
+ "```",
13538
+ "",
13539
+ "A **report-only** audit is available for repos that prefer",
13540
+ "report-then-fix over auto-correct \u2014 same sweep, no mutations:",
13541
+ "",
13542
+ "```bash",
13543
+ ".claude/procedures/check-blocked.sh label-invariant # report only",
13544
+ ".claude/procedures/check-blocked.sh label-invariant --fix # apply",
13545
+ "```",
13546
+ "",
13547
+ "### Correction policy",
13548
+ "",
13549
+ "An issue must carry **exactly one** `type:*` label. Merely *adding*",
13550
+ "the required type label to an issue that already carries a",
13551
+ "conventional-commit one would leave two, making the funnel-tier sort",
13552
+ "key (which reads the **first** `type:*` label) non-deterministic and",
13553
+ "violating the label conventions. The correction therefore",
13554
+ "**replaces**, in a single atomic `gh issue edit`, so the issue is",
13555
+ "never observable carrying two `type:*` labels:",
13556
+ "",
13557
+ "| Issue state | Action |",
13558
+ "|-------------|--------|",
13559
+ "| Required type label present, nothing else | none \u2014 compliant, left untouched |",
13560
+ "| No `type:*` label at all | **add** the required label |",
13561
+ "| Only conventional-commit `type:*` label(s) | **replace** \u2014 remove them, add the required label |",
13562
+ "| Required label present **plus** a stray conventional-commit one | **remove** the stray, leaving exactly one |",
13563
+ "| A `type:*` label owned by a **different** bundle | **flag** `status:needs-attention` \u2014 never guessed at |",
13564
+ "| Phase labels imply **two or more** type labels | **flag** `status:needs-attention` \u2014 never auto-corrected |",
13565
+ "",
13566
+ "Only a conventional-commit `type:*` label is ever removed. A",
13567
+ "`type:*` label owned by another bundle carries real routing",
13568
+ "information, so the sweep refuses to guess and hands the issue to a",
13569
+ "human instead. Ambiguity is narrower than it looks: all three",
13570
+ "requirements bundles declare `type:requirement`, so every `req:*`",
13571
+ "phase label resolves to the same type label \u2014 genuine ambiguity",
13572
+ "needs phase labels from two bundles with *different* type labels.",
13573
+ "",
13574
+ "`status:needs-attention` is applied **additively** \u2014 the base",
13575
+ "`status:*` label always stays, per the additive-flag rule. Flagging",
13576
+ "is idempotent: an issue already carrying the flag is reported but",
13577
+ "not re-flagged."
13578
+ ].join("\n");
13579
+ }
13580
+ function isPhaseLabelMatcherOwnedByExcluded(matcher, excludeBundles) {
13581
+ if (excludeBundles.length === 0) {
13582
+ return false;
13583
+ }
13584
+ let owned = false;
13585
+ for (const [bundleName, ownership] of Object.entries(BUNDLE_OWNERSHIP)) {
13586
+ if (!ownership.phaseLabelPrefixes.includes(matcher)) {
13587
+ continue;
13588
+ }
13589
+ owned = true;
13590
+ if (!excludeBundles.includes(bundleName)) {
13591
+ return false;
13592
+ }
13593
+ }
13594
+ return owned;
13595
+ }
13596
+ function renderPhaseTypeInvariantShellHelpers() {
13597
+ const matchers = Object.keys(PHASE_LABEL_TYPE_MAP);
13598
+ const exactMatchers = matchers.filter((m) => !m.endsWith(":")).sort();
13599
+ const prefixMatchers = matchers.filter((m) => m.endsWith(":")).sort((a, b) => b.length - a.length || a.localeCompare(b));
13600
+ const lines = [
13601
+ "# Resolve ONE phase label to the `type:<bundle>` label its owning",
13602
+ "# bundle declares. Echoes the label (with the `type:` prefix) or",
13603
+ "# nothing when no bundle owns it. Exact-match branches come first,",
13604
+ "# so `req:write` (requirements-writer) beats the `req:` prefix",
13605
+ "# (requirements-analyst). Generated from BUNDLE_OWNERSHIP \u2014 do not",
13606
+ "# hand-edit.",
13607
+ "phase_label_type_of() {",
13608
+ ' case "${1:-}" in'
13609
+ ];
13610
+ for (const matcher of exactMatchers) {
13611
+ lines.push(` ${matcher}) echo "${PHASE_LABEL_TYPE_MAP[matcher]}" ;;`);
13612
+ }
13613
+ for (const matcher of prefixMatchers) {
13614
+ lines.push(` ${matcher}*) echo "${PHASE_LABEL_TYPE_MAP[matcher]}" ;;`);
13615
+ }
13616
+ lines.push(
13617
+ " *) : ;;",
13618
+ " esac",
13619
+ "}",
13620
+ "",
13621
+ "# Return 0 when the argument is a conventional-commit `type:*`",
13622
+ "# label \u2014 the ONLY type labels the invariant correction may remove.",
13623
+ "# A `type:*` label owned by another bundle is never removed; the",
13624
+ "# issue is flagged for human triage instead.",
13625
+ "is_conventional_type_label() {",
13626
+ ` case "\${1:-}" in`,
13627
+ ` ${CONVENTIONAL_COMMIT_TYPE_LABELS.join("|")}) return 0 ;;`,
13628
+ " *) return 1 ;;",
13629
+ " esac",
13630
+ "}",
13631
+ "",
13632
+ "# Resolve an issue's FULL label list (one label per line on stdin)",
13633
+ "# to the type label the phase-label invariant requires. Emits",
13634
+ "# KEY=VALUE assignments the caller parses:",
13635
+ "# OUTCOME=none \u2014 no recognised phase label; invariant N/A",
13636
+ "# OUTCOME=match \u2014 plus TYPE_LABEL=<type:bundle>",
13637
+ "# OUTCOME=ambiguous \u2014 plus CANDIDATE_TYPE_LABELS=<space-separated>",
13638
+ "# PHASE_LABELS=<space-separated recognised phase labels>",
13639
+ "phase_type_of() {",
13640
+ " local label resolved",
13641
+ ' local matched_types=""',
13642
+ ' local matched_phase=""',
13643
+ " while IFS= read -r label; do",
13644
+ ' [ -z "$label" ] && continue',
13645
+ ' resolved=$(phase_label_type_of "$label")',
13646
+ ' [ -z "$resolved" ] && continue',
13647
+ ' matched_phase="${matched_phase}${label} "',
13648
+ ' case " ${matched_types} " in',
13649
+ ' *" ${resolved} "*) ;;',
13650
+ ' *) matched_types="${matched_types}${resolved} " ;;',
13651
+ " esac",
13652
+ " done",
13653
+ " local count=0",
13654
+ " for resolved in $matched_types; do",
13655
+ " count=$((count + 1))",
13656
+ " done",
13657
+ ' if [ "$count" -eq 0 ]; then',
13658
+ ' echo "OUTCOME=none"',
13659
+ ' elif [ "$count" -eq 1 ]; then',
13660
+ ' echo "OUTCOME=match"',
13661
+ ' echo "TYPE_LABEL=${matched_types% }"',
13662
+ " else",
13663
+ ' echo "OUTCOME=ambiguous"',
13664
+ ' echo "CANDIDATE_TYPE_LABELS=${matched_types% }"',
13665
+ " fi",
13666
+ ' echo "PHASE_LABELS=${matched_phase% }"',
13667
+ "}"
13668
+ );
13669
+ return lines.join("\n");
13670
+ }
13671
+ function buildPhaseLabelTypeMap() {
13672
+ const map = {};
13673
+ for (const [bundleName, ownership] of Object.entries(BUNDLE_OWNERSHIP)) {
13674
+ if (ownership.phaseLabelPrefixes.length === 0) {
13675
+ continue;
13676
+ }
13677
+ if (ownership.typeLabels.length !== 1) {
13678
+ throw new Error(
13679
+ `BUNDLE_OWNERSHIP["${bundleName}"] declares ${ownership.phaseLabelPrefixes.length} phase-label matcher(s) but ${ownership.typeLabels.length} type label(s); a phase label must pair with exactly one type label`
13680
+ );
13681
+ }
13682
+ const typeLabel = `type:${ownership.typeLabels[0]}`;
13683
+ for (const matcher of ownership.phaseLabelPrefixes) {
13684
+ const existing = map[matcher];
13685
+ if (existing !== void 0 && existing !== typeLabel) {
13686
+ throw new Error(
13687
+ `Phase-label matcher "${matcher}" resolves to both "${existing}" and "${typeLabel}"; a matcher must imply exactly one type label`
13688
+ );
13689
+ }
13690
+ map[matcher] = typeLabel;
13691
+ }
13692
+ }
13693
+ return map;
13694
+ }
13203
13695
  function isTypeLabelOwnedByExcluded(typeLabel, excludedBundles) {
13204
13696
  if (excludedBundles.length === 0) {
13205
13697
  return false;
@@ -13289,6 +13781,188 @@ function findOwnersOfTypeLabel(typeLabel) {
13289
13781
  return owners;
13290
13782
  }
13291
13783
 
13784
+ // src/agent/bundles/run-ratio.ts
13785
+ var DEFAULT_DISPATCH_TO_HOUSEKEEPING_RATIO = 4;
13786
+ var DEFAULT_STATE_FILE_PATH = ".state/orchestrator-runs.json";
13787
+ var DEFAULT_DISPATCH_MODEL = "opus";
13788
+ var DEFAULT_HOUSEKEEPING_MODEL = "sonnet";
13789
+ function resolveRunRatio(config) {
13790
+ const ratio = config?.ratio ?? DEFAULT_DISPATCH_TO_HOUSEKEEPING_RATIO;
13791
+ assertValidRatio(ratio);
13792
+ const stateFilePath = config?.stateFilePath ?? DEFAULT_STATE_FILE_PATH;
13793
+ assertValidStateFilePath(stateFilePath);
13794
+ return {
13795
+ enabled: config?.enabled ?? true,
13796
+ ratio,
13797
+ stateFilePath,
13798
+ dispatchModel: config?.dispatchModel ?? DEFAULT_DISPATCH_MODEL,
13799
+ housekeepingModel: config?.housekeepingModel ?? DEFAULT_HOUSEKEEPING_MODEL
13800
+ };
13801
+ }
13802
+ function validateRunRatioConfig(config) {
13803
+ return resolveRunRatio(config);
13804
+ }
13805
+ function classifyRun(runCounter, ratio) {
13806
+ if (!ratio.enabled) {
13807
+ return "dispatch";
13808
+ }
13809
+ const cycle = ratio.ratio + 1;
13810
+ return runCounter > 0 && runCounter % cycle === 0 ? "housekeeping" : "dispatch";
13811
+ }
13812
+ function renderRunRatioSection(ratio) {
13813
+ const lines = [
13814
+ "## Run ratio (dispatch vs housekeeping)",
13815
+ "",
13816
+ "The orchestrator keeps a **persistent run counter** and interleaves",
13817
+ "dispatch runs (pick the next ready issue, recommend a worker) with",
13818
+ "**housekeeping runs** (batch PR review + maintenance scan) on a",
13819
+ "configurable ratio. This mirrors openhi's `DISPATCHER.md` contract:",
13820
+ "multiple dispatch runs feed the worker queue, then one batched",
13821
+ "housekeeping run flushes review backlog and runs maintenance",
13822
+ "triage so the pipeline never drifts.",
13823
+ ""
13824
+ ];
13825
+ if (!ratio.enabled) {
13826
+ lines.push(
13827
+ "**The run ratio is disabled for this project.** Every orchestrator",
13828
+ "run executes the full dispatch pipeline; PR review and maintenance",
13829
+ "remain manual invocations. Enable the ratio via",
13830
+ "`AgentConfigOptions.runRatio.enabled = true` once the operator is",
13831
+ "comfortable with the counter-backed cadence.",
13832
+ ""
13833
+ );
13834
+ return lines.join("\n");
13835
+ }
13836
+ const cycle = ratio.ratio + 1;
13837
+ lines.push(
13838
+ "### Cadence",
13839
+ "",
13840
+ `The cycle length is **${cycle}** runs:`,
13841
+ "",
13842
+ `- Runs 1 through ${ratio.ratio} execute the **dispatch** pipeline`,
13843
+ ` (recommended model: \`${ratio.dispatchModel}\`).`,
13844
+ `- Run ${cycle} executes the **housekeeping** pipeline`,
13845
+ ` (recommended model: \`${ratio.housekeepingModel}\`).`,
13846
+ `- The counter wraps \u2014 run ${cycle + 1} is a dispatch run again, run ${cycle * 2} is the next housekeeping run, and so on.`,
13847
+ "",
13848
+ "The orchestrator increments the counter **once per invocation** at",
13849
+ "the top of the run, before any pipeline phase executes. The",
13850
+ "pre-increment value is never observed \u2014 the tick always returns",
13851
+ "the post-increment counter and the classified run type in a single",
13852
+ "atomic update.",
13853
+ "",
13854
+ "### State file",
13855
+ "",
13856
+ `The run counter persists at \`${ratio.stateFilePath}\`. The file is`,
13857
+ "plain JSON with a single `run_counter` integer field:",
13858
+ "",
13859
+ "```json",
13860
+ '{ "run_counter": 42 }',
13861
+ "```",
13862
+ "",
13863
+ "The state file is **gitignored** in consumer repos (it is local to",
13864
+ "each operator's machine). On a first run, or if the file is missing",
13865
+ "or corrupt, the orchestrator recreates it with `run_counter: 1`.",
13866
+ "",
13867
+ "### Dispatch-run pipeline",
13868
+ "",
13869
+ "1. Phase A \u2014 startup (fetch + checkout default branch).",
13870
+ "2. Phase C \u2014 triage unblock (resolve `Depends on:` chains).",
13871
+ "3. Phase E \u2014 queue scan (pick the top `PICK` line, run the scope",
13872
+ " gate, emit `NEXT_WORK_ITEM`).",
13873
+ "4. Phase F \u2014 cleanup.",
13874
+ "",
13875
+ "### Housekeeping-run pipeline",
13876
+ "",
13877
+ "1. Phase A \u2014 startup.",
13878
+ "2. Phase B \u2014 batch PR review across every eligible open PR.",
13879
+ "3. Phase D \u2014 maintenance scan (stale detection, orphaned branches,",
13880
+ " needs-attention summary).",
13881
+ "4. Phase F \u2014 cleanup.",
13882
+ "",
13883
+ "### Model recommendations",
13884
+ "",
13885
+ `Dispatch runs should use \`${ratio.dispatchModel}\` \u2014 the routing`,
13886
+ "logic, scope gate, and funnel-tier sort benefit from the stronger",
13887
+ "reasoning model. Housekeeping runs are mechanical (read CI status,",
13888
+ "toggle labels, post canned comments) and should use",
13889
+ `\`${ratio.housekeepingModel}\` so the batched PR review and`,
13890
+ "maintenance scan cost less per invocation.",
13891
+ "",
13892
+ "These strings are **informational** \u2014 they surface in the",
13893
+ "orchestrator's rendered rule content so operators know which model",
13894
+ "to run each session against. Configulator does not inject them as",
13895
+ "`model:` frontmatter on the sub-agent definition; the operator (or",
13896
+ "a scheduled task) picks the model at invocation time."
13897
+ );
13898
+ return lines.join("\n");
13899
+ }
13900
+ function renderRunRatioShellHelpers(ratio) {
13901
+ const cycle = ratio.ratio + 1;
13902
+ return [
13903
+ "# Increment the orchestrator run counter and classify the run.",
13904
+ "# Reads the state file (creating it on first run or corruption),",
13905
+ "# increments the counter, writes back atomically, and echoes",
13906
+ "# `run=<n> type=<dispatch|housekeeping>` on stdout.",
13907
+ "#",
13908
+ "# Uses the cycle length (ratio + 1) hard-coded from the resolved",
13909
+ "# RunRatioConfig so the shell helper matches the rendered rule",
13910
+ "# content byte-for-byte.",
13911
+ "run_counter_tick() {",
13912
+ ' local state_file="$ORCHESTRATOR_STATE_FILE"',
13913
+ " local state_dir",
13914
+ ' state_dir=$(dirname "$state_file")',
13915
+ ' mkdir -p "$state_dir" 2>/dev/null || true',
13916
+ "",
13917
+ " local current=0",
13918
+ ' if [ -f "$state_file" ]; then',
13919
+ " # jq returns empty string on parse failure; guard against it.",
13920
+ ` current=$(jq -r '.run_counter // 0' "$state_file" 2>/dev/null || echo 0)`,
13921
+ ' case "$current" in',
13922
+ " ''|*[!0-9]*) current=0 ;;",
13923
+ " esac",
13924
+ " fi",
13925
+ "",
13926
+ " local next=$((current + 1))",
13927
+ "",
13928
+ ' local tmp_file="${state_file}.tmp.$$"',
13929
+ ` printf '{ "run_counter": %d }\\n' "$next" > "$tmp_file"`,
13930
+ ' mv "$tmp_file" "$state_file"',
13931
+ "",
13932
+ " local run_type=dispatch",
13933
+ ` if [ $((next % ${cycle})) -eq 0 ]; then`,
13934
+ " run_type=housekeeping",
13935
+ " fi",
13936
+ ` printf 'run=%d type=%s\\n' "$next" "$run_type"`,
13937
+ "}"
13938
+ ].join("\n");
13939
+ }
13940
+ function assertValidRatio(ratio) {
13941
+ if (!Number.isInteger(ratio)) {
13942
+ throw new Error(
13943
+ `RunRatioConfig.ratio must be a positive integer; got ${ratio}`
13944
+ );
13945
+ }
13946
+ if (ratio < 1) {
13947
+ throw new Error(
13948
+ `RunRatioConfig.ratio must be a positive integer; got ${ratio}`
13949
+ );
13950
+ }
13951
+ }
13952
+ function assertValidStateFilePath(stateFilePath) {
13953
+ const trimmed = stateFilePath.trim();
13954
+ if (trimmed.length === 0) {
13955
+ throw new Error(
13956
+ "RunRatioConfig.stateFilePath must be a non-empty string relative to the repo root"
13957
+ );
13958
+ }
13959
+ if (trimmed.startsWith("/")) {
13960
+ throw new Error(
13961
+ `RunRatioConfig.stateFilePath must be relative to the repo root (no leading '/'); got ${stateFilePath}`
13962
+ );
13963
+ }
13964
+ }
13965
+
13292
13966
  // src/agent/bundles/scheduled-tasks.ts
13293
13967
  var SCHEDULED_TASK_MODEL_VALUES = ["opus", "sonnet", "haiku"];
13294
13968
  var SCHEDULED_TASK_KIND_VALUES = ["issue-worker", "pipeline"];
@@ -15244,6 +15918,7 @@ function buildCheckBlockedScript(tiers, scopeGate, _runRatio) {
15244
15918
  "# .claude/procedures/check-blocked.sh maintenance",
15245
15919
  "# .claude/procedures/check-blocked.sh prs",
15246
15920
  "# .claude/procedures/check-blocked.sh scope <issue-number>",
15921
+ "# .claude/procedures/check-blocked.sh label-invariant [--fix]",
15247
15922
  "",
15248
15923
  "set -uo pipefail",
15249
15924
  "",
@@ -15293,6 +15968,8 @@ function buildCheckBlockedScript(tiers, scopeGate, _runRatio) {
15293
15968
  "",
15294
15969
  scopeHelperIndented,
15295
15970
  "",
15971
+ renderPhaseTypeInvariantShellHelpers(),
15972
+ "",
15296
15973
  ...renderDelegationActiveSignalsHelper(),
15297
15974
  "",
15298
15975
  "# \u2500\u2500 subcommands \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",
@@ -15928,16 +16605,43 @@ function buildCheckBlockedScript(tiers, scopeGate, _runRatio) {
15928
16605
  " esac",
15929
16606
  ' done <<< "$lease_output"',
15930
16607
  "",
16608
+ " # \u2500\u2500 phase-label \u2192 type:<bundle> invariant (MUTATING) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",
16609
+ " # Run the label-invariant sweep in --fix mode and surface its",
16610
+ " # per-issue lines for log visibility. cmd_label_invariant applies",
16611
+ " # the label edits itself (a single atomic remove+add per issue, so",
16612
+ " # an issue is never observable carrying two type:* labels) and",
16613
+ " # flags the cases it must not guess at. Its terminal",
16614
+ " # LABEL_INVARIANT_DONE line is captured and re-emitted alongside",
16615
+ " # MAINTENANCE_DONE so the orchestrator reads every summary from",
16616
+ " # one maintenance invocation.",
16617
+ " local label_output",
16618
+ " label_output=$(cmd_label_invariant --fix)",
16619
+ ' local label_summary="LABEL_INVARIANT_DONE mode=fix checked=0 ok=0 violations=0 corrected=0 flagged=0"',
16620
+ "",
16621
+ " while IFS= read -r line; do",
16622
+ ' [[ -z "$line" ]] && continue',
16623
+ ' case "$line" in',
16624
+ " 'LABEL_INVARIANT_DONE '*)",
16625
+ ' label_summary="$line"',
16626
+ " ;;",
16627
+ " *)",
16628
+ ' echo "$line"',
16629
+ " ;;",
16630
+ " esac",
16631
+ ' done <<< "$label_output"',
16632
+ "",
15931
16633
  " # \u2500\u2500 needs-attention total \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",
15932
16634
  " local needs_attention_total",
15933
16635
  ' needs_attention_total=$(gh issue list --label "status:needs-attention" --state open \\',
15934
16636
  " --json number --limit 100 2>/dev/null | jq 'length' 2>/dev/null || echo 0)",
15935
16637
  " needs_attention_total=${needs_attention_total:-0}",
15936
16638
  "",
15937
- " # Two summary lines consumed by the orchestrator: the issue/orphan",
15938
- " # MAINTENANCE_DONE line and the PR-lease LEASE_RECONCILE line.",
16639
+ " # Three summary lines consumed by the orchestrator: the",
16640
+ " # issue/orphan MAINTENANCE_DONE line, the PR-lease LEASE_RECONCILE",
16641
+ " # line, and the LABEL_INVARIANT_DONE line.",
15939
16642
  ' echo "MAINTENANCE_DONE flagged_stale=${flagged_stale_count} flagged_blocked=${flagged_blocked_count} orphan_branches=${orphan_branches_count} orphan_prs=${orphan_prs_count} needs_attention_total=${needs_attention_total}"',
15940
16643
  ' echo "$lease_summary"',
16644
+ ' echo "$label_summary"',
15941
16645
  "}",
15942
16646
  "",
15943
16647
  "cmd_prs() {",
@@ -16003,6 +16707,196 @@ function buildCheckBlockedScript(tiers, scopeGate, _runRatio) {
16003
16707
  ' done <<< "$eligible"',
16004
16708
  "}",
16005
16709
  "",
16710
+ "cmd_label_invariant() {",
16711
+ " # Phase-label \u2192 type:<bundle> invariant sweep.",
16712
+ " #",
16713
+ " # Every phased-pipeline bundle pairs its <bundle>:<phase> labels",
16714
+ " # with exactly one type:<bundle> label. An agent that reconstructs",
16715
+ " # a gh issue create call from prose can stamp a conventional-commit",
16716
+ " # type label derived from the title prefix instead, producing an",
16717
+ " # issue that carries the phase label but the WRONG type label \u2014",
16718
+ " # invisible to the --label type:<bundle> duplicate-check idiom and",
16719
+ " # mis-tiered by the funnel-tier sort in cmd_eligible.",
16720
+ " #",
16721
+ " # Default mode is REPORT-ONLY (the consumer-runnable audit); pass",
16722
+ " # --fix to apply corrections. cmd_maintenance runs the --fix mode",
16723
+ " # as part of the Phase D sweep.",
16724
+ " #",
16725
+ " # CORRECTION POLICY. An issue must carry EXACTLY ONE type:* label",
16726
+ " # (cmd_eligible derives its funnel-tier sort key from the FIRST",
16727
+ " # one, and the label conventions mandate exactly one), so the",
16728
+ " # correction REPLACES rather than merely adds:",
16729
+ " #",
16730
+ " # no type:* at all \u2192 add the implied type label",
16731
+ " # only conventional-commit \u2192 remove them, add the implied",
16732
+ " # type labels present label (single atomic edit)",
16733
+ " # implied label already there \u2192 remove the stray conventional",
16734
+ " # alongside a conventional one label, leaving exactly one",
16735
+ " # a type:* owned by ANOTHER \u2192 FLAG status:needs-attention;",
16736
+ " # bundle never guess which to drop",
16737
+ " # phase labels imply 2+ types \u2192 FLAG status:needs-attention",
16738
+ " #",
16739
+ " # Only a conventional-commit type label is ever removed \u2014 the set",
16740
+ " # is_conventional_type_label() recognises. A type:* label owned by",
16741
+ " # a different bundle is a genuine conflict a human must resolve.",
16742
+ " # status:needs-attention is applied ADDITIVELY; the base status:*",
16743
+ " # label always stays (see the additive-flag rule).",
16744
+ " local apply=0",
16745
+ ' if [[ "${1:-}" == "--fix" ]]; then',
16746
+ " apply=1",
16747
+ " fi",
16748
+ ' local mode="report"',
16749
+ ' [[ "$apply" -eq 1 ]] && mode="fix"',
16750
+ "",
16751
+ " local issues",
16752
+ " issues=$(gh issue list --state open --json number,labels \\",
16753
+ ' --limit 1000 2>/dev/null || echo "[]")',
16754
+ "",
16755
+ " # Filter jq-side and emit a TWO-field record. The label list is",
16756
+ " # last AND guaranteed non-empty by the select, so no field can",
16757
+ " # collapse under IFS=tab and shift the record left (#884). The",
16758
+ " # title is deliberately not threaded through \u2014 every output line",
16759
+ " # keys off the issue number.",
16760
+ " local issue_data",
16761
+ ` issue_data=$(echo "$issues" | jq -r '`,
16762
+ " .[] |",
16763
+ " (.labels | map(.name)) as $names |",
16764
+ " select($names | length > 0) |",
16765
+ ' "\\(.number)\\t\\($names | join(","))"',
16766
+ " ' 2>/dev/null)",
16767
+ "",
16768
+ " local checked_count=0",
16769
+ " local ok_count=0",
16770
+ " local corrected_count=0",
16771
+ " local flagged_count=0",
16772
+ "",
16773
+ " while IFS=$'\\t' read -r num labels_csv; do",
16774
+ ' [[ -z "$num" ]] && continue',
16775
+ "",
16776
+ " local labels_nl",
16777
+ ` labels_nl=$(printf '%s' "$labels_csv" | tr ',' '\\n')`,
16778
+ "",
16779
+ " local resolution assignment",
16780
+ " local outcome='' type_label='' phase_labels='' candidates=''",
16781
+ ` resolution=$(printf '%s\\n' "$labels_nl" | phase_type_of)`,
16782
+ " while IFS= read -r assignment; do",
16783
+ ' case "$assignment" in',
16784
+ " OUTCOME=*) outcome=${assignment#OUTCOME=} ;;",
16785
+ " TYPE_LABEL=*) type_label=${assignment#TYPE_LABEL=} ;;",
16786
+ " CANDIDATE_TYPE_LABELS=*) candidates=${assignment#CANDIDATE_TYPE_LABELS=} ;;",
16787
+ " PHASE_LABELS=*) phase_labels=${assignment#PHASE_LABELS=} ;;",
16788
+ " esac",
16789
+ ' done <<< "$resolution"',
16790
+ "",
16791
+ " # No recognised phase label \u2014 the invariant does not apply.",
16792
+ " # Consumer-specific `foo:bar` labels are deliberately not policed.",
16793
+ ' [[ "$outcome" == "none" ]] && continue',
16794
+ " checked_count=$((checked_count + 1))",
16795
+ "",
16796
+ " # Idempotent flagging: read the existing flag off the labels we",
16797
+ " # already fetched rather than spending another API call.",
16798
+ " local already_flagged=0",
16799
+ ' case ",${labels_csv}," in',
16800
+ ' *",status:needs-attention,"*) already_flagged=1 ;;',
16801
+ " esac",
16802
+ "",
16803
+ ' if [[ "$outcome" == "ambiguous" ]]; then',
16804
+ ' echo "LABEL_AMBIGUOUS #${num} phase=\\"${phase_labels}\\" candidates=\\"${candidates}\\""',
16805
+ " flagged_count=$((flagged_count + 1))",
16806
+ ' if [[ "$apply" -eq 1 && "$already_flagged" -eq 0 ]]; then',
16807
+ ' if gh issue edit "$num" --add-label "status:needs-attention" >/dev/null 2>&1; then',
16808
+ ' gh issue comment "$num" \\',
16809
+ ' --body "Label invariant: phase label(s) ${phase_labels} imply more than one bundle type label (${candidates}). Flagged for human triage \u2014 an ambiguous pairing is never auto-corrected." >/dev/null 2>&1 || true',
16810
+ ' echo "LABEL_FLAGGED #${num} \u2014 added status:needs-attention (ambiguous)"',
16811
+ " else",
16812
+ ' echo "LABEL_FLAG_FAILED #${num} \u2014 could not add status:needs-attention (ambiguous)"',
16813
+ " fi",
16814
+ " fi",
16815
+ " continue",
16816
+ " fi",
16817
+ "",
16818
+ " # Partition the issue's existing type:* labels against the",
16819
+ " # implied one.",
16820
+ " local label",
16821
+ " local has_expected=0",
16822
+ " local conv_types=''",
16823
+ " local foreign_types=''",
16824
+ " while IFS= read -r label; do",
16825
+ ' [ -z "$label" ] && continue',
16826
+ ' case "$label" in',
16827
+ " type:*) ;;",
16828
+ " *) continue ;;",
16829
+ " esac",
16830
+ ' if [ "$label" = "$type_label" ]; then',
16831
+ " has_expected=1",
16832
+ " continue",
16833
+ " fi",
16834
+ ' if is_conventional_type_label "$label"; then',
16835
+ ' conv_types="${conv_types}${label} "',
16836
+ " else",
16837
+ ' foreign_types="${foreign_types}${label} "',
16838
+ " fi",
16839
+ ' done <<< "$labels_nl"',
16840
+ "",
16841
+ ' if [[ "$has_expected" -eq 1 && -z "${conv_types}${foreign_types}" ]]; then',
16842
+ ' echo "LABEL_OK #${num} type=${type_label}"',
16843
+ " ok_count=$((ok_count + 1))",
16844
+ " continue",
16845
+ " fi",
16846
+ "",
16847
+ " # A type:* label owned by a DIFFERENT bundle is a conflict the",
16848
+ " # sweep must not guess at: removing it would destroy routing",
16849
+ " # information, and adding alongside it would leave two bundle",
16850
+ " # type labels and a non-deterministic funnel tier.",
16851
+ ' if [[ -n "$foreign_types" ]]; then',
16852
+ ' echo "LABEL_CONFLICT #${num} phase=\\"${phase_labels}\\" expected=${type_label} foreign=\\"${foreign_types% }\\""',
16853
+ " flagged_count=$((flagged_count + 1))",
16854
+ ' if [[ "$apply" -eq 1 && "$already_flagged" -eq 0 ]]; then',
16855
+ ' if gh issue edit "$num" --add-label "status:needs-attention" >/dev/null 2>&1; then',
16856
+ ' gh issue comment "$num" \\',
16857
+ ' --body "Label invariant: phase label(s) ${phase_labels} require ${type_label}, but this issue carries ${foreign_types% }, which is owned by another bundle. Flagged for human triage \u2014 the sweep only removes conventional-commit type labels." >/dev/null 2>&1 || true',
16858
+ ' echo "LABEL_FLAGGED #${num} \u2014 added status:needs-attention (conflicting bundle type)"',
16859
+ " else",
16860
+ ' echo "LABEL_FLAG_FAILED #${num} \u2014 could not add status:needs-attention (conflict)"',
16861
+ " fi",
16862
+ " fi",
16863
+ " continue",
16864
+ " fi",
16865
+ "",
16866
+ " # Correctable: add the implied label and/or drop the",
16867
+ " # conventional-commit label(s) shadowing it, in ONE edit so the",
16868
+ " # issue is never observable carrying two type:* labels.",
16869
+ ' local removing="${conv_types% }"',
16870
+ " local adding=''",
16871
+ ' [[ "$has_expected" -eq 0 ]] && adding="$type_label"',
16872
+ ' echo "LABEL_VIOLATION #${num} phase=\\"${phase_labels}\\" expected=${type_label} add=\\"${adding}\\" remove=\\"${removing}\\""',
16873
+ ' if [[ "$apply" -eq 0 ]]; then',
16874
+ " continue",
16875
+ " fi",
16876
+ "",
16877
+ " local -a edit_args=()",
16878
+ " local stray",
16879
+ " for stray in $removing; do",
16880
+ ' edit_args+=(--remove-label "$stray")',
16881
+ " done",
16882
+ ' [[ -n "$adding" ]] && edit_args+=(--add-label "$adding")',
16883
+ ' if [[ "${#edit_args[@]}" -eq 0 ]]; then',
16884
+ " continue",
16885
+ " fi",
16886
+ ' if gh issue edit "$num" "${edit_args[@]}" >/dev/null 2>&1; then',
16887
+ ' gh issue comment "$num" \\',
16888
+ ' --body "Label invariant: phase label(s) ${phase_labels} require ${type_label}. Corrected \u2014 added: ${adding:-(none)}; removed: ${removing:-(none)}." >/dev/null 2>&1 || true',
16889
+ ' echo "LABEL_CORRECTED #${num} added=\\"${adding}\\" removed=\\"${removing}\\""',
16890
+ " corrected_count=$((corrected_count + 1))",
16891
+ " else",
16892
+ ' echo "LABEL_CORRECT_FAILED #${num} \u2014 label edit failed"',
16893
+ " fi",
16894
+ ' done <<< "$issue_data"',
16895
+ "",
16896
+ " local violations_count=$((checked_count - ok_count))",
16897
+ ' echo "LABEL_INVARIANT_DONE mode=${mode} checked=${checked_count} ok=${ok_count} violations=${violations_count} corrected=${corrected_count} flagged=${flagged_count}"',
16898
+ "}",
16899
+ "",
16006
16900
  "cmd_scope() {",
16007
16901
  ' local issue_num="${1:-}"',
16008
16902
  ' if [[ -z "$issue_num" ]]; then',
@@ -16089,8 +16983,9 @@ function buildCheckBlockedScript(tiers, scopeGate, _runRatio) {
16089
16983
  ' maintenance) shift; cmd_maintenance "$@" ;;',
16090
16984
  ' prs) shift; cmd_prs "$@" ;;',
16091
16985
  ' scope) shift; cmd_scope "$@" ;;',
16986
+ ' label-invariant) shift; cmd_label_invariant "$@" ;;',
16092
16987
  " help|*)",
16093
- ' echo "Usage: check-blocked.sh <unblock|eligible|stale|orphaned|lease-reconcile|maintenance|prs|scope>"',
16988
+ ' echo "Usage: check-blocked.sh <unblock|eligible|stale|orphaned|lease-reconcile|maintenance|prs|scope|label-invariant>"',
16094
16989
  " exit 1",
16095
16990
  " ;;",
16096
16991
  "esac"
@@ -16099,7 +16994,7 @@ function buildCheckBlockedScript(tiers, scopeGate, _runRatio) {
16099
16994
  function buildCheckBlockedProcedure(tiers, scopeGate = resolveScopeGate(), runRatio = resolveRunRatio()) {
16100
16995
  return {
16101
16996
  name: "check-blocked.sh",
16102
- description: "Token-efficient issue triage script with subcommands: eligible, unblock, stale, orphaned, lease-reconcile, maintenance, prs, scope. Sorts eligible issues by priority desc \u2192 funnel tier asc \u2192 issue number asc, excluding issues carrying `status:needs-attention` or `status:deferred`; the scope subcommand classifies a single issue against the scope-gate thresholds; the unblock subcommand applies the `status:blocked` \u2192 `status:ready` label flip itself, posts the canned unblock comment, skips human-parked `status:deferred` candidates with a `SKIP_DEFERRED` line, and emits a single `TRIAGE_DONE unblocked=N still_blocked=M deferred_skipped=K` summary line; the lease-reconcile subcommand auto-reconciles stuck `review:fixing` PR leases \u2014 re-applying `review:needs-worker` on an orphaned lease (fix-list stale, no worker report) so the Phase B1 drain retries, and removing `review:needs-worker` on a consumed-but-uncleared wedge (branch HEAD advanced past the fix-list, marker still set, no worker report) so the reviewer confirm pass can merge, always posting an audit-trail note comment and emitting a single `LEASE_RECONCILE orphaned=N consumed_uncleared=M` summary line; the maintenance subcommand flags stale issues with `status:needs-attention` (never auto-resets to `status:ready`), counts orphan branches/PRs, folds in the lease-reconcile sweep, and emits a `MAINTENANCE_DONE flagged_stale=N flagged_blocked=M orphan_branches=A orphan_prs=B needs_attention_total=T` summary line followed by the `LEASE_RECONCILE` line.",
16997
+ description: "Token-efficient issue triage script with subcommands: eligible, unblock, stale, orphaned, lease-reconcile, maintenance, prs, scope, label-invariant. Sorts eligible issues by priority desc \u2192 funnel tier asc \u2192 issue number asc, excluding issues carrying `status:needs-attention` or `status:deferred`; the scope subcommand classifies a single issue against the scope-gate thresholds; the unblock subcommand applies the `status:blocked` \u2192 `status:ready` label flip itself, posts the canned unblock comment, skips human-parked `status:deferred` candidates with a `SKIP_DEFERRED` line, and emits a single `TRIAGE_DONE unblocked=N still_blocked=M deferred_skipped=K` summary line; the lease-reconcile subcommand auto-reconciles stuck `review:fixing` PR leases \u2014 re-applying `review:needs-worker` on an orphaned lease (fix-list stale, no worker report) so the Phase B1 drain retries, and removing `review:needs-worker` on a consumed-but-uncleared wedge (branch HEAD advanced past the fix-list, marker still set, no worker report) so the reviewer confirm pass can merge, always posting an audit-trail note comment and emitting a single `LEASE_RECONCILE orphaned=N consumed_uncleared=M` summary line; the maintenance subcommand flags stale issues with `status:needs-attention` (never auto-resets to `status:ready`), counts orphan branches/PRs, folds in the lease-reconcile sweep and the label-invariant auto-correction, and emits a `MAINTENANCE_DONE flagged_stale=N flagged_blocked=M orphan_branches=A orphan_prs=B needs_attention_total=T` summary line followed by the `LEASE_RECONCILE` and `LABEL_INVARIANT_DONE` lines; the label-invariant subcommand enforces the phase-label \u2192 `type:<bundle>` pairing derived from the canonical `BUNDLE_OWNERSHIP` map \u2014 report-only by default, auto-correcting with `--fix` (replacing a shadowing conventional-commit `type:*` rather than merely adding, so the issue keeps exactly one `type:*`) and flagging `status:needs-attention` when the pairing is ambiguous or collides with another bundle's type label, emitting a single `LABEL_INVARIANT_DONE mode=M checked=N ok=O violations=V corrected=C flagged=F` summary line.",
16103
16998
  content: buildCheckBlockedScript(tiers, scopeGate, runRatio)
16104
16999
  };
16105
17000
  }
@@ -16815,32 +17710,36 @@ var orchestratorSubAgent = {
16815
17710
  "## Phase D: Maintenance",
16816
17711
  "",
16817
17712
  "Run the bundled `check-blocked.sh maintenance` procedure and read",
16818
- "**only** the two summary lines it emits \u2014 `MAINTENANCE_DONE` and",
16819
- "`LEASE_RECONCILE`. The procedure folds the stale-detection,",
16820
- "orphan-detection, needs-attention summary, and PR-lease",
16821
- "auto-reconcile that earlier revisions split across D1, D2, and D3",
16822
- "into a single sweep \u2014 applying the `status:needs-attention` label",
16823
- "and posting the canned flag comment for each stale / stale-blocked",
16824
- "issue itself, and reconciling stuck `review:fixing` PR leases",
16825
- "itself, mirroring the discipline of Phase B (`pr-sweep.sh`) and",
16826
- "Phase C (`check-blocked.sh unblock`).",
17713
+ "**only** the three summary lines it emits \u2014 `MAINTENANCE_DONE`,",
17714
+ "`LEASE_RECONCILE`, and `LABEL_INVARIANT_DONE`. The procedure folds",
17715
+ "the stale-detection, orphan-detection, needs-attention summary,",
17716
+ "PR-lease auto-reconcile, and phase-label invariant sweep that",
17717
+ "earlier revisions split across D1, D2, and D3 into a single sweep \u2014",
17718
+ "applying the `status:needs-attention` label and posting the canned",
17719
+ "flag comment for each stale / stale-blocked issue itself,",
17720
+ "reconciling stuck `review:fixing` PR leases itself, and correcting",
17721
+ "mislabeled pipeline issues itself, mirroring the discipline of",
17722
+ "Phase B (`pr-sweep.sh`) and Phase C (`check-blocked.sh unblock`).",
16827
17723
  "",
16828
17724
  "```bash",
16829
17725
  ".claude/procedures/check-blocked.sh maintenance",
16830
17726
  "```",
16831
17727
  "",
16832
- "The script emits two summary lines in this shape:",
17728
+ "The script emits three summary lines in this shape:",
16833
17729
  "",
16834
17730
  "```",
16835
17731
  "MAINTENANCE_DONE flagged_stale=<N> flagged_blocked=<M> orphan_branches=<A> orphan_prs=<B> needs_attention_total=<T>",
16836
17732
  "LEASE_RECONCILE orphaned=<N> consumed_uncleared=<M>",
17733
+ "LABEL_INVARIANT_DONE mode=fix checked=<N> ok=<O> violations=<V> corrected=<C> flagged=<F>",
16837
17734
  "```",
16838
17735
  "",
16839
17736
  "Per-issue / per-orphan / per-PR informational lines (`FLAGGED_STALE",
16840
17737
  "#N`, `FLAGGED_BLOCKED #N`, `STALE #N \u2014 \u2026`, `STALE_BLOCKED #N \u2014 \u2026`,",
16841
17738
  "`ORPHAN_BRANCH \u2026`, `ORPHAN_PR #N \u2014 \u2026`, `FLAG_FAILED #N \u2014 \u2026`,",
16842
17739
  "`LEASE_ORPHANED PR #N \u2014 \u2026`, `LEASE_CONSUMED_UNCLEARED PR #N \u2014 \u2026`,",
16843
- "`LEASE_RECONCILE_FAILED PR #N \u2014 \u2026`) are emitted for log visibility",
17740
+ "`LEASE_RECONCILE_FAILED PR #N \u2014 \u2026`, `LABEL_VIOLATION #N \u2014 \u2026`,",
17741
+ "`LABEL_CORRECTED #N \u2014 \u2026`, `LABEL_AMBIGUOUS #N \u2014 \u2026`,",
17742
+ "`LABEL_CONFLICT #N \u2014 \u2026`) are emitted for log visibility",
16844
17743
  "but are **not** load-bearing for the orchestrator \u2014 partial failures",
16845
17744
  "(one bad `gh` call) do not abort the sweep, they are simply omitted",
16846
17745
  "from the counters.",
@@ -16880,9 +17779,24 @@ var orchestratorSubAgent = {
16880
17779
  "is never silently force-released. The `review:fixing` lease itself",
16881
17780
  "is always left for the reviewer confirm pass to release.",
16882
17781
  "",
16883
- "Log both summary lines and continue to Phase E regardless of",
16884
- "outcomes \u2014 a non-zero `flagged_*`, `orphan_*`, `orphaned`, or",
16885
- "`consumed_uncleared` count is informational, not a failure.",
17782
+ "**Phase-label invariant (`LABEL_INVARIANT_DONE`).** The sweep also",
17783
+ "enforces the phase-label \u2192 `type:<bundle>` pairing on every open",
17784
+ "issue, so a pipeline issue filed with a conventional-commit",
17785
+ "`type:*` (derived from its title prefix) cannot stay invisible to",
17786
+ 'the `--label "type:<bundle>"` duplicate-check idiom or mis-tier in',
17787
+ "Phase E's funnel-tier sort. The script mutates the labels itself \u2014",
17788
+ "the orchestrator only reads the summary line. See the **Phase-label",
17789
+ "\u2192 `type:<bundle>` invariant** section in `CLAUDE.md` for the full",
17790
+ "correction policy; in short, a shadowing conventional-commit type",
17791
+ "label is **replaced** (never merely supplemented, so the issue",
17792
+ "keeps exactly one `type:*`), and an ambiguous or cross-bundle",
17793
+ "collision is **flagged** `status:needs-attention` rather than",
17794
+ "guessed at.",
17795
+ "",
17796
+ "Log all three summary lines and continue to Phase E regardless of",
17797
+ "outcomes \u2014 a non-zero `flagged_*`, `orphan_*`, `orphaned`,",
17798
+ "`consumed_uncleared`, `corrected`, or `flagged` count is",
17799
+ "informational, not a failure.",
16886
17800
  "",
16887
17801
  "## Phase E: Queue Scan",
16888
17802
  "",
@@ -17884,6 +18798,7 @@ var ORCHESTRATOR_CONVENTIONS_PREAMBLE = [
17884
18798
  "- Stale thresholds: 72h for in-progress, 168h for blocked",
17885
18799
  "- Flagged issues get `status:needs-attention` \u2014 they are not auto-reset",
17886
18800
  "- **Phase D auto-reconciles stuck PR leases.** The maintenance sweep's `check-blocked.sh maintenance` invocation folds in a PR-lease reconcile that unwedges `review:fixing` PRs the Phase B1 drain and the worker hand-off left stuck, emitting a `LEASE_RECONCILE orphaned=<N> consumed_uncleared=<M>` line alongside `MAINTENANCE_DONE`. An **orphaned lease** (`review:fixing` without `review:needs-worker`, fix-list older than the 72h stale threshold, no worker-report newer than the fix-list) is **re-armed** \u2014 the sweep re-applies `review:needs-worker` so the Phase B1 drain retries the delegation, leaving the lease untouched. A **consumed-but-uncleared wedge** (both labels present, branch HEAD newer than the fix-list, no worker-report \u2014 the worker pushed but skipped the hand-off) is **auto-reconciled** \u2014 the sweep removes `review:needs-worker` so the reviewer confirm pass can merge. Both paths post an audit-trail note comment; a lease is never silently force-released, and the `review:fixing` lease itself is always left for the reviewer confirm pass to release.",
18801
+ "- **Phase D enforces the phase-label \u2192 `type:<bundle>` invariant.** The same maintenance sweep folds in a label-invariant pass that auto-corrects open issues carrying a pipeline phase label without the matching `type:<bundle>` label, emitting a `LABEL_INVARIANT_DONE mode=fix checked=<N> ok=<O> violations=<V> corrected=<C> flagged=<F>` line alongside `MAINTENANCE_DONE`. The correction **replaces** a shadowing conventional-commit `type:*` rather than merely adding the bundle type, so the issue keeps exactly one `type:*` and Phase E's funnel-tier sort key stays deterministic. Ambiguous pairings and collisions with another bundle's `type:*` label are **flagged** `status:needs-attention` (additively) instead of guessed at. See the **Phase-label \u2192 `type:<bundle>` invariant** section below for the matcher table and the full correction policy.",
17887
18802
  "",
17888
18803
  "## Depth-0 invocation requirement",
17889
18804
  "",
@@ -17899,6 +18814,8 @@ function buildOrchestratorConventionsContent(tiers, scopeGate = resolveScopeGate
17899
18814
  "",
17900
18815
  renderScopeGateSection(scopeGate, excludeBundles),
17901
18816
  "",
18817
+ renderPhaseTypeInvariantSection(excludeBundles),
18818
+ "",
17902
18819
  renderScheduledTasksSection(scheduledTasks),
17903
18820
  "",
17904
18821
  renderUnblockDependentsSection(unblockDependents)
@@ -18986,7 +19903,7 @@ var peopleProfileBundle = buildPeopleProfileBundle();
18986
19903
 
18987
19904
  // src/pnpm/pnpm-workspace.ts
18988
19905
  import { relative } from "path";
18989
- import { Component, YamlFile } from "projen";
19906
+ import { Component as Component3, YamlFile } from "projen";
18990
19907
  var MINIMUM_RELEASE_AGE = {
18991
19908
  ZERO_DAYS: 0,
18992
19909
  ONE_HOUR: 60,
@@ -19000,7 +19917,7 @@ var MINIMUM_RELEASE_AGE = {
19000
19917
  SIX_DAYS: 8640,
19001
19918
  ONE_WEEK: 10080
19002
19919
  };
19003
- var PnpmWorkspace = class _PnpmWorkspace extends Component {
19920
+ var PnpmWorkspace = class _PnpmWorkspace extends Component3 {
19004
19921
  /**
19005
19922
  * Get the pnpm workspace component of a project. If it does not exist,
19006
19923
  * return undefined.
@@ -28565,7 +29482,7 @@ function buildResearchPipelineBundle(paths = DEFAULT_AGENT_PATHS, issueDefaults
28565
29482
  var researchPipelineBundle = buildResearchPipelineBundle();
28566
29483
 
28567
29484
  // src/projects/project-metadata.ts
28568
- import { Component as Component2 } from "projen";
29485
+ import { Component as Component4 } from "projen";
28569
29486
  import { NodeProject } from "projen/lib/javascript";
28570
29487
  var GITHUB_HTTPS_RE = /(?:https?:\/\/|git\+https:\/\/)github\.com\/([^/]+)\/([^/.]+)(?:\.git)?/;
28571
29488
  var GITHUB_SSH_RE = /git@github\.com:([^/]+)\/([^/.]+)(?:\.git)?/;
@@ -28580,7 +29497,7 @@ function parseGitHubUrl(url) {
28580
29497
  }
28581
29498
  return { owner: void 0, name: void 0 };
28582
29499
  }
28583
- var ProjectMetadata = class _ProjectMetadata extends Component2 {
29500
+ var ProjectMetadata = class _ProjectMetadata extends Component4 {
28584
29501
  /**
28585
29502
  * Returns the ProjectMetadata instance for a project. Walks up the parent
28586
29503
  * chain so sub-projects resolve the metadata declared on a root
@@ -31177,435 +32094,56 @@ function buildStandardsResearchBundle(paths = DEFAULT_AGENT_PATHS, issueDefaults
31177
32094
  }
31178
32095
  var standardsResearchBundle = buildStandardsResearchBundle();
31179
32096
 
31180
- // src/turbo/turbo-repo.ts
31181
- import {
31182
- Component as Component4,
31183
- FileBase,
31184
- JsonFile,
31185
- SampleDir,
31186
- SampleFile
31187
- } from "projen/lib";
31188
- import { JobPermission } from "projen/lib/github/workflows-model";
31189
-
31190
- // src/turbo/turbo-repo-task.ts
31191
- import { Component as Component3 } from "projen/lib";
31192
- var TurboRepoTask = class extends Component3 {
31193
- constructor(project, options) {
31194
- super(project);
31195
- this.project = project;
31196
- this.name = options.name;
31197
- this.dependsOn = options.dependsOn ?? [];
31198
- this.env = options.env ?? [];
31199
- this.passThroughEnv = options.passThroughEnv ?? [];
31200
- this.outputs = options.outputs ?? [];
31201
- this.cache = options.cache ?? true;
31202
- this.inputs = [
31203
- ...options.inputs ?? [],
31204
- // rerun if projen config changes
31205
- ".projen/**",
31206
- // ignore mac files
31207
- "!.DS_Store",
31208
- "!**/.DS_Store"
31209
- ];
31210
- this.outputLogs = options.outputLogs ?? "new-only";
31211
- this.persistent = options.persistent ?? false;
31212
- this.interactive = options.interactive ?? false;
31213
- this.isActive = true;
31214
- }
31215
- taskConfig() {
31216
- return {
31217
- dependsOn: this.dependsOn,
31218
- env: this.env,
31219
- passThroughEnv: this.passThroughEnv,
31220
- outputs: this.outputs,
31221
- cache: this.cache,
31222
- inputs: this.inputs,
31223
- outputLogs: this.outputLogs,
31224
- persistent: this.persistent,
31225
- interactive: this.interactive
31226
- };
31227
- }
31228
- };
31229
-
31230
- // src/turbo/turbo-repo.ts
31231
- var ROOT_TURBO_TASK_NAME = "turbo:build";
31232
- var ROOT_CI_TASK_NAME = "build:all";
31233
- var _TurboRepo = class _TurboRepo extends Component4 {
31234
- constructor(project, options = {}) {
31235
- super(project);
31236
- this.project = project;
31237
- /**
31238
- * Sub-Tasks to run
31239
- */
31240
- this.tasks = [];
31241
- this.turboVersion = options.turboVersion ?? "catalog:";
31242
- this.isRootProject = project === project.root;
31243
- if (this.isRootProject) {
31244
- project.addDevDeps(`turbo@${this.turboVersion}`);
31245
- }
31246
- project.gitignore.addPatterns("/.turbo");
31247
- project.npmignore?.addPatterns("/.turbo/");
31248
- this.extends = options.extends ?? (this.isRootProject ? [] : ["//"]);
31249
- this.globalDependencies = options.globalDependencies ?? [];
31250
- this.globalEnv = options.globalEnv ?? [];
31251
- this.globalPassThroughEnv = options.globalPassThroughEnv ?? [];
31252
- this.ui = options.ui ?? "stream";
31253
- this.dangerouslyDisablePackageManagerCheck = options.dangerouslyDisablePackageManagerCheck ?? false;
31254
- this.cacheDir = options.cacheDir ?? ".turbo/cache";
31255
- this.daemon = options.daemon ?? true;
31256
- this.envMode = options.envMode ?? "strict";
31257
- this.runOptions = {
31258
- ...options.runOptions,
31259
- summarize: options.runOptions?.summarize ?? true,
31260
- concurrency: options.runOptions?.concurrency ?? 10
31261
- };
31262
- this.remoteCacheOptions = options.remoteCacheOptions;
31263
- this.buildAllTaskEnvVars = options.buildAllTaskEnvVars ?? {};
31264
- this.buildTask = new TurboRepoTask(this.project, {
31265
- name: ROOT_TURBO_TASK_NAME,
31266
- dependsOn: this.isRootProject ? [`^${ROOT_TURBO_TASK_NAME}`] : []
31267
- });
31268
- if (this.isRootProject) {
31269
- this.buildAllTask = this.project.tasks.addTask(ROOT_CI_TASK_NAME, {
31270
- description: "Root build followed by sub-project builds. Mimics the CI build process in one step."
31271
- });
31272
- this.buildAllTask.exec("turbo telemetry disable");
31273
- if (this.buildAllTaskEnvVars) {
31274
- Object.entries(this.buildAllTaskEnvVars).forEach(([name, value]) => {
31275
- this.addGlobalEnvVar(name, value);
31276
- });
31277
- }
31278
- if (!this.remoteCacheOptions) {
31279
- this.buildAllTask.exec(
31280
- `turbo ${ROOT_TURBO_TASK_NAME} ${this.renderRunArgs(false)}`
31281
- );
31282
- } else {
31283
- this.buildAllTask.exec(
31284
- `turbo ${ROOT_TURBO_TASK_NAME} ${this.renderRunArgs(true)}`,
31285
- {
31286
- condition: '[ ! -n "$CI" ]',
31287
- env: {
31288
- TURBO_ENDPOINT: `$(aws ssm get-parameter --name ${this.remoteCacheOptions.endpointParamName} --query Parameter.Value --output text --profile ${this.remoteCacheOptions.profileName})`,
31289
- TURBO_TOKEN: `$(aws ssm get-parameter --name ${this.remoteCacheOptions.tokenParamName} --query Parameter.Value --output text --profile ${this.remoteCacheOptions.profileName})`
31290
- }
31291
- }
31292
- );
31293
- this.buildAllTask.exec(
31294
- `turbo ${ROOT_TURBO_TASK_NAME} ${this.renderRunArgs(true)}`,
31295
- {
31296
- condition: '[ -n "$CI" ]',
31297
- env: {
31298
- TURBO_ENDPOINT: `$(aws ssm get-parameter --name ${this.remoteCacheOptions.endpointParamName} --query Parameter.Value --output text)`,
31299
- TURBO_TOKEN: `$(aws ssm get-parameter --name ${this.remoteCacheOptions.tokenParamName} --query Parameter.Value --output text)`
31300
- }
31301
- }
31302
- );
31303
- }
31304
- }
31305
- if (!this.isRootProject) {
31306
- this.preCompileTask = new TurboRepoTask(project, {
31307
- name: options.preCompileTask?.name ?? "pre-compile",
31308
- inputs: ["src/**"]
31309
- });
31310
- this.compileTask = new TurboRepoTask(project, {
31311
- name: options.compileTask?.name ?? "compile",
31312
- inputs: ["src/**"]
31313
- });
31314
- this.postCompileTask = new TurboRepoTask(project, {
31315
- name: options.postCompileTask?.name ?? "post-compile",
31316
- inputs: ["src/**"]
31317
- });
31318
- this.testTask = new TurboRepoTask(project, {
31319
- name: options.testTask?.name ?? "test"
31320
- });
31321
- this.packageTask = new TurboRepoTask(project, {
31322
- name: options.packageTask?.name ?? "package",
31323
- inputs: [".npmignore"]
31324
- });
31325
- this.tasks.push(
31326
- this.preCompileTask,
31327
- this.compileTask,
31328
- this.postCompileTask,
31329
- this.testTask,
31330
- this.packageTask
31331
- );
31332
- }
31333
- }
31334
- /**
31335
- * Static method to discovert turbo in a project.
31336
- */
31337
- static of(project) {
31338
- const isDefined = (c) => c instanceof _TurboRepo;
31339
- return project.components.find(isDefined);
31340
- }
31341
- /**
31342
- * Render the `turbo run` CLI flag string for the `build:all` / `reset:all`
31343
- * task commands from {@link runOptions}. With no `runOptions` configured the
31344
- * output matches the historically hard-coded flags exactly.
31345
- *
31346
- * @param remote - when `true`, also emit the remote-cache flags
31347
- * (`--cache=remote:rw` plus `--api` / `--token` / `--team` derived from
31348
- * {@link remoteCacheOptions}). The remote-cache `build:all` variant passes
31349
- * `true`; `reset:all` and the local `build:all` variant pass `false`.
31350
- */
31351
- renderRunArgs(remote) {
31352
- const run = this.runOptions;
31353
- const args = [];
31354
- if (run.summarize) {
31355
- args.push("--summarize");
31356
- }
31357
- args.push(`--concurrency=${run.concurrency}`);
31358
- if (run.force) {
31359
- args.push("--force");
31360
- }
31361
- if (run.noCache) {
31362
- args.push("--no-cache");
31363
- }
31364
- if (run.only) {
31365
- args.push("--only");
31366
- }
31367
- if (run.affected) {
31368
- args.push("--affected");
31369
- }
31370
- if (run.cacheWorkers !== void 0) {
31371
- args.push(`--cache-workers=${run.cacheWorkers}`);
31372
- }
31373
- if (run.continueOn !== void 0) {
31374
- args.push(`--continue=${run.continueOn}`);
31375
- }
31376
- if (run.frameworkInference !== void 0) {
31377
- args.push(`--framework-inference=${run.frameworkInference}`);
31378
- }
31379
- for (const filter of run.filter ?? []) {
31380
- args.push(`--filter=${filter}`);
31381
- }
31382
- if (run.outputLogs !== void 0) {
31383
- args.push(`--output-logs=${run.outputLogs}`);
31384
- }
31385
- if (run.logOrder !== void 0) {
31386
- args.push(`--log-order=${run.logOrder}`);
31387
- }
31388
- if (run.logPrefix !== void 0) {
31389
- args.push(`--log-prefix=${run.logPrefix}`);
31390
- }
31391
- if (run.dryRun !== void 0) {
31392
- args.push(`--dry-run=${run.dryRun}`);
31393
- }
31394
- const cache = run.cache ?? (remote ? "remote:rw" : void 0);
31395
- if (cache !== void 0) {
31396
- args.push(`--cache=${cache}`);
31397
- }
31398
- if (remote && this.remoteCacheOptions) {
31399
- args.push(
31400
- "--api=$TURBO_ENDPOINT",
31401
- "--token=$TURBO_TOKEN",
31402
- `--team=${this.remoteCacheOptions.teamName}`
31403
- );
31404
- }
31405
- if (run.additionalArgs) {
31406
- args.push(...run.additionalArgs);
31407
- }
31408
- return args.join(" ");
31409
- }
31410
- /**
31411
- * Add an env var to the global env vars for all tasks.
31412
- * This will also become an input for the build:all task cache at the root.
31413
- */
31414
- addGlobalEnvVar(name, value) {
31415
- this.buildAllTask?.env(name, value);
31416
- if (this.isRootProject) {
31417
- this.globalEnv.push(name);
31418
- }
31419
- }
31420
- activateBranchNameEnvVar(options) {
31421
- const value = '$([ -n "$GIT_BRANCH_NAME" ] && echo "$GIT_BRANCH_NAME" || git rev-parse --abbrev-ref HEAD)';
31422
- if (options === void 0) {
31423
- this.project.logger.warn(
31424
- "TurboRepo.activateBranchNameEnvVar() with no arguments is deprecated. It writes GIT_BRANCH_NAME to the root `globalEnv`, which forces every task in the monorepo to miss cache on every branch switch. Pass `{ tasks: [...] }` and name only the tasks that actually consume the branch (e.g. CDK synth/package) to preserve cross-branch cache hits for everything else."
31425
- );
31426
- this.addGlobalEnvVar("GIT_BRANCH_NAME", value);
31427
- return;
31428
- }
31429
- const knownTaskNames = this.tasks.map((task) => task.name);
31430
- const unknown = options.tasks.filter(
31431
- (name) => !knownTaskNames.includes(name)
31432
- );
31433
- if (unknown.length > 0) {
31434
- throw new Error(
31435
- `TurboRepo.activateBranchNameEnvVar: unknown task name(s) ${JSON.stringify(
31436
- unknown
31437
- )}. Known tasks on this TurboRepo: ${JSON.stringify(knownTaskNames)}.`
31438
- );
31439
- }
31440
- for (const name of options.tasks) {
31441
- const task = this.tasks.find((t) => t.name === name);
31442
- if (task && !task.env.includes("GIT_BRANCH_NAME")) {
31443
- task.env.push("GIT_BRANCH_NAME");
31444
- }
31445
- }
31446
- }
31447
- /**
31448
- * Paths of all generated files in the project, deduped, for use as task
31449
- * inputs so the compile cache invalidates when they change. Includes
31450
- * projen-managed `FileBase` files plus generated-once `SampleFile` /
31451
- * `SampleDir` — whose paths projen keeps private, so they are read defensively
31452
- * and skipped if that internal shape ever changes. Computed at synth time so
31453
- * files added after this component (e.g. a subclass's SampleFiles) are seen.
31454
- */
31455
- generatedFileInputs() {
31456
- const inputs = /* @__PURE__ */ new Set();
31457
- for (const component of this.project.components) {
31458
- if (component instanceof FileBase) {
31459
- inputs.add(component.path);
31460
- } else if (component instanceof SampleFile) {
31461
- const filePath = component.filePath;
31462
- if (typeof filePath === "string") {
31463
- inputs.add(filePath);
31464
- }
31465
- } else if (component instanceof SampleDir) {
31466
- const dir = component.dir;
31467
- if (typeof dir === "string") {
31468
- inputs.add(`${dir}/**`);
31469
- }
31470
- }
31471
- }
31472
- return Array.from(inputs);
31473
- }
31474
- preSynthesize() {
31475
- let nextDependsOn = this.project.deps.all.filter((d) => d.version === "workspace:*").map((d) => [d.name, ROOT_TURBO_TASK_NAME].join("#"));
31476
- if (!this.isRootProject) {
31477
- [
31478
- [this.project.preCompileTask, this.preCompileTask],
31479
- [this.project.compileTask, this.compileTask],
31480
- [this.project.postCompileTask, this.postCompileTask],
31481
- [this.project.testTask, this.testTask],
31482
- [this.project.packageTask, this.packageTask]
31483
- ].forEach(([pjTask, turboTask]) => {
31484
- if (pjTask && turboTask && pjTask.steps.length > 0) {
31485
- if (nextDependsOn.length > 0) {
31486
- turboTask.dependsOn.push(...nextDependsOn);
31487
- }
31488
- nextDependsOn = [turboTask.name];
31489
- } else {
31490
- turboTask.isActive = false;
31491
- }
31492
- });
31493
- this.buildTask.dependsOn.push(...nextDependsOn);
31494
- }
31495
- const generatedInputs = this.generatedFileInputs();
31496
- const appendGeneratedInputs = (task) => {
31497
- if (!task) {
31498
- return;
31499
- }
31500
- for (const input of generatedInputs) {
31501
- if (!task.inputs.includes(input)) {
31502
- task.inputs.push(input);
31503
- }
31504
- }
31505
- };
31506
- if (this.isRootProject) {
31507
- appendGeneratedInputs(this.buildTask);
31508
- } else {
31509
- appendGeneratedInputs(this.preCompileTask);
31510
- appendGeneratedInputs(this.compileTask);
31511
- appendGeneratedInputs(this.postCompileTask);
31512
- }
31513
- const fileName = "turbo.json";
31514
- this.project.addPackageIgnore(fileName);
31515
- new JsonFile(this.project, fileName, {
31516
- obj: {
31517
- extends: this.extends.length ? this.extends : void 0,
31518
- globalDependencies: this.isRootProject && this.globalDependencies.length ? this.globalDependencies : void 0,
31519
- globalEnv: this.isRootProject && this.globalEnv.length ? this.globalEnv : void 0,
31520
- globalPassThroughEnv: this.isRootProject && this.globalPassThroughEnv.length ? this.globalPassThroughEnv : void 0,
31521
- ui: this.isRootProject ? this.ui : void 0,
31522
- dangerouslyDisablePackageManagerCheck: this.isRootProject ? this.dangerouslyDisablePackageManagerCheck : void 0,
31523
- cacheDir: this.isRootProject ? this.cacheDir : void 0,
31524
- envMode: this.isRootProject ? this.envMode : void 0,
31525
- /**
31526
- * All tasks
31527
- */
31528
- tasks: this.tasks.filter((task) => task.isActive).reduce(
31529
- (acc, task) => {
31530
- acc[task.name] = {
31531
- ...task.taskConfig()
31532
- };
31533
- return acc;
31534
- },
31535
- {
31536
- [this.buildTask.name]: { ...this.buildTask.taskConfig() }
31537
- }
31538
- )
31539
- }
31540
- });
31541
- super.preSynthesize();
32097
+ // src/agent/bundles/turborepo.ts
32098
+ function renderCachingBullet(policy) {
32099
+ if (policy.remoteCacheEnabled && policy.awsProfileName) {
32100
+ return `- Uses remote caching (requires AWS credentials on the \`${policy.awsProfileName}\` profile)`;
31542
32101
  }
31543
- };
31544
- _TurboRepo.buildWorkflowOptions = (remoteCacheOptions) => {
32102
+ return "- Local caching only \u2014 no remote cache is configured, so no AWS credentials are required";
32103
+ }
32104
+ function buildTurborepoBundle(buildPolicy = DEFAULT_BUILD_POLICY) {
31545
32105
  return {
31546
- env: {
31547
- GIT_BRANCH_NAME: "${{ github.head_ref || github.ref_name }}"
31548
- },
31549
- permissions: {
31550
- contents: JobPermission.WRITE,
31551
- idToken: JobPermission.WRITE
31552
- },
31553
- preBuildSteps: [
32106
+ name: "turborepo",
32107
+ description: "Turborepo workspace rules and task pipeline conventions",
32108
+ appliesWhen: (project) => hasComponent(project, TurboRepo),
32109
+ rules: [
31554
32110
  {
31555
- name: "AWS Creds for SSM",
31556
- uses: "aws-actions/configure-aws-credentials@v6",
31557
- with: {
31558
- ["role-to-assume"]: remoteCacheOptions.oidcRole,
31559
- ["aws-region"]: "us-east-1",
31560
- ["role-duration-seconds"]: "900"
31561
- }
32111
+ name: "turborepo-conventions",
32112
+ description: "Turborepo build system and task pipeline conventions",
32113
+ scope: AGENT_RULE_SCOPE.FILE_PATTERN,
32114
+ filePatterns: ["turbo.json", "package.json"],
32115
+ content: [
32116
+ "# Turborepo Conventions",
32117
+ "",
32118
+ "## Build System",
32119
+ "",
32120
+ "- **Build**: `pnpm build:all` (uses Turborepo)",
32121
+ "- **Test**: `pnpm test` or `pnpm test:watch`",
32122
+ "- **Lint**: `pnpm eslint`",
32123
+ "",
32124
+ "## Task Pipeline",
32125
+ "",
32126
+ renderCachingBullet(buildPolicy),
32127
+ "- Only rebuilds changed packages",
32128
+ "- Cache key based on file hashes and dependency graph",
32129
+ "- Configured in `turbo.json`",
32130
+ "",
32131
+ "## Workspace Rules",
32132
+ "",
32133
+ "- Source files: `src/` directory",
32134
+ "- Tests: Co-located with source files (`.spec.ts` or `.test.ts`)",
32135
+ "- Exports: Use `index.ts` files for clean public APIs",
32136
+ "- Configuration: Managed by Projen (edit `.projenrc.ts` or `projenrc/*.ts`)"
32137
+ ].join("\n"),
32138
+ tags: ["workflow"]
31562
32139
  }
31563
- ]
31564
- };
31565
- };
31566
- var TurboRepo = _TurboRepo;
31567
-
31568
- // src/agent/bundles/turborepo.ts
31569
- var turborepoBundle = {
31570
- name: "turborepo",
31571
- description: "Turborepo workspace rules and task pipeline conventions",
31572
- appliesWhen: (project) => hasComponent(project, TurboRepo),
31573
- rules: [
31574
- {
31575
- name: "turborepo-conventions",
31576
- description: "Turborepo build system and task pipeline conventions",
31577
- scope: AGENT_RULE_SCOPE.FILE_PATTERN,
31578
- filePatterns: ["turbo.json", "package.json"],
31579
- content: [
31580
- "# Turborepo Conventions",
31581
- "",
31582
- "## Build System",
31583
- "",
31584
- "- **Build**: `pnpm build:all` (uses Turborepo)",
31585
- "- **Test**: `pnpm test` or `pnpm test:watch`",
31586
- "- **Lint**: `pnpm eslint`",
31587
- "",
31588
- "## Task Pipeline",
31589
- "",
31590
- "- Uses remote caching (requires AWS credentials)",
31591
- "- Only rebuilds changed packages",
31592
- "- Cache key based on file hashes and dependency graph",
31593
- "- Configured in `turbo.json`",
31594
- "",
31595
- "## Workspace Rules",
31596
- "",
31597
- "- Source files: `src/` directory",
31598
- "- Tests: Co-located with source files (`.spec.ts` or `.test.ts`)",
31599
- "- Exports: Use `index.ts` files for clean public APIs",
31600
- "- Configuration: Managed by Projen (edit `.projenrc.ts` or `projenrc/*.ts`)"
31601
- ].join("\n"),
31602
- tags: ["workflow"]
32140
+ ],
32141
+ claudePermissions: {
32142
+ allow: ["Bash(npx turbo:*)"]
31603
32143
  }
31604
- ],
31605
- claudePermissions: {
31606
- allow: ["Bash(npx turbo:*)"]
31607
- }
31608
- };
32144
+ };
32145
+ }
32146
+ var turborepoBundle = buildTurborepoBundle();
31609
32147
 
31610
32148
  // src/agent/bundles/typescript.ts
31611
32149
  var typescriptBundle = {
@@ -32820,7 +33358,7 @@ function renderPriorityRulesSection(rules) {
32820
33358
  }
32821
33359
 
32822
33360
  // src/agent/bundles/index.ts
32823
- function buildBuiltInBundles(paths = DEFAULT_AGENT_PATHS, issueDefaults = DEFAULT_RESOLVED_ISSUE_DEFAULTS, defaultAgentTier = AGENT_MODEL.BALANCED, bundleAgentTiers = /* @__PURE__ */ new Map(), prReviewPolicy = resolvePrReviewPolicy()) {
33361
+ function buildBuiltInBundles(paths = DEFAULT_AGENT_PATHS, issueDefaults = DEFAULT_RESOLVED_ISSUE_DEFAULTS, defaultAgentTier = AGENT_MODEL.BALANCED, bundleAgentTiers = /* @__PURE__ */ new Map(), prReviewPolicy = resolvePrReviewPolicy(), buildPolicy = DEFAULT_BUILD_POLICY) {
32824
33362
  const tierFor = (bundle) => bundleAgentTiers.get(bundle) ?? defaultAgentTier;
32825
33363
  return [
32826
33364
  buildBaseBundle(paths),
@@ -32828,11 +33366,11 @@ function buildBuiltInBundles(paths = DEFAULT_AGENT_PATHS, issueDefaults = DEFAUL
32828
33366
  typescriptBundle,
32829
33367
  vitestBundle,
32830
33368
  jestBundle,
32831
- turborepoBundle,
33369
+ buildTurborepoBundle(buildPolicy),
32832
33370
  pnpmBundle,
32833
33371
  awsCdkBundle,
32834
33372
  projenBundle,
32835
- githubWorkflowBundle,
33373
+ buildGithubWorkflowBundle(buildPolicy),
32836
33374
  slackBundle,
32837
33375
  buildMeetingAnalysisBundle(tierFor("meeting-analysis")),
32838
33376
  agendaBundle,
@@ -33917,6 +34455,13 @@ var AgentConfig = class _AgentConfig extends Component8 {
33917
34455
  * their rendered rule content reflects any consumer override.
33918
34456
  * Bundles that do not read agent paths are passed through as-is
33919
34457
  * from their default const exports.
34458
+ *
34459
+ * The build policy is auto-detected from the project's `TurboRepo`
34460
+ * component here rather than configured, so build guidance in the
34461
+ * `github-workflow` and `turborepo` rules only claims an AWS
34462
+ * credential requirement when a remote cache actually exists. The
34463
+ * getter is lazy by design — `TurboRepo` must already be attached
34464
+ * to the project when the bundles are first read.
33920
34465
  */
33921
34466
  get pathAwareBundles() {
33922
34467
  if (!this.cachedBundles) {
@@ -33925,7 +34470,8 @@ var AgentConfig = class _AgentConfig extends Component8 {
33925
34470
  resolveIssueDefaults(this.options.issueDefaults),
33926
34471
  resolveDefaultAgentTier(this.options),
33927
34472
  resolveBundleAgentTiers(this.options),
33928
- resolvePrReviewPolicy(this.options.prReviewPolicy)
34473
+ resolvePrReviewPolicy(this.options.prReviewPolicy),
34474
+ resolveBuildPolicy(this.project)
33929
34475
  );
33930
34476
  }
33931
34477
  return this.cachedBundles;
@@ -40634,6 +41180,7 @@ export {
40634
41180
  CDK_WATCH_DEFAULTS_BY_STAGE,
40635
41181
  CLAUDE_RULE_TARGET,
40636
41182
  COMPLETE_JOB_ID,
41183
+ CONVENTIONAL_COMMIT_TYPE_LABELS,
40637
41184
  CdkCli,
40638
41185
  DEFAULT_AC_THRESHOLDS,
40639
41186
  DEFAULT_AGENT_PATHS,
@@ -40643,6 +41190,7 @@ export {
40643
41190
  DEFAULT_API_EXTRACTOR_REPORT_FILENAME,
40644
41191
  DEFAULT_API_EXTRACTOR_REPORT_FOLDER,
40645
41192
  DEFAULT_AUDIT_REPORT_DIR,
41193
+ DEFAULT_BUILD_POLICY,
40646
41194
  DEFAULT_BUNDLE_OVERRIDES,
40647
41195
  DEFAULT_DECOMPOSITION_TEMPLATE,
40648
41196
  DEFAULT_DISPATCH_MODEL,
@@ -40704,6 +41252,7 @@ export {
40704
41252
  MONOREPO_LAYOUT,
40705
41253
  MonorepoProject,
40706
41254
  Nvmrc,
41255
+ PHASE_LABEL_TYPE_MAP,
40707
41256
  PROD_DEPLOY_NAME,
40708
41257
  PROGRESS_FILES_FORMAT_VALUES,
40709
41258
  PnpmWorkspace,
@@ -40763,6 +41312,7 @@ export {
40763
41312
  buildCompanyProfileBundle,
40764
41313
  buildCustomerProfileBundle,
40765
41314
  buildDocsSyncBundle,
41315
+ buildGithubWorkflowBundle,
40766
41316
  buildIndustryDiscoveryBundle,
40767
41317
  buildMaintenanceAuditBundle,
40768
41318
  buildMeetingAnalysisBundle,
@@ -40777,6 +41327,7 @@ export {
40777
41327
  buildResearchPipelineBundle,
40778
41328
  buildSoftwareProfileBundle,
40779
41329
  buildStandardsResearchBundle,
41330
+ buildTurborepoBundle,
40780
41331
  buildUnblockDependentsProcedure,
40781
41332
  bundleNameForWorkflowRule,
40782
41333
  businessModelsBundle,
@@ -40862,6 +41413,8 @@ export {
40862
41413
  renderIssueTemplatesStarterPage,
40863
41414
  renderMeetingTypesSection,
40864
41415
  renderNextRequirementIdProcedure,
41416
+ renderPhaseTypeInvariantSection,
41417
+ renderPhaseTypeInvariantShellHelpers,
40865
41418
  renderPriorityRulesSection,
40866
41419
  renderProgressFileName,
40867
41420
  renderProgressFilePath,
@@ -40894,6 +41447,7 @@ export {
40894
41447
  resolveAgentTiers,
40895
41448
  resolveAstroProjectOutdir,
40896
41449
  resolveAwsCdkProjectOutdir,
41450
+ resolveBuildPolicy,
40897
41451
  resolveBundleAgentTiers,
40898
41452
  resolveDefaultAgentTier,
40899
41453
  resolveIssueDefaults,
@@ -40912,6 +41466,7 @@ export {
40912
41466
  resolveSkillEvals,
40913
41467
  resolveTemplateVariables,
40914
41468
  resolveTemporalFraming,
41469
+ resolveTypeLabelForLabels,
40915
41470
  resolveTypeScriptProjectOutdir,
40916
41471
  resolveUnblockDependents,
40917
41472
  runScan,
@@ -40921,6 +41476,7 @@ export {
40921
41476
  stripToolArtifactTagsProcedure,
40922
41477
  tsdocRecordToFindings,
40923
41478
  turborepoBundle,
41479
+ typeLabelForPhaseLabel,
40924
41480
  typescriptBundle,
40925
41481
  upstreamConfigulatorDocsBundle,
40926
41482
  validateAgentTierConfig,