@catalyst-cloud/cli 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +26 -29
  3. package/dist/args.js +16 -0
  4. package/dist/ask.js +30 -18
  5. package/dist/capabilities.js +5 -0
  6. package/dist/cli.js +18 -5
  7. package/dist/environment.js +1 -1
  8. package/dist/legacy.js +224 -0
  9. package/dist/project.js +129 -0
  10. package/dist/release.js +1 -1
  11. package/dist/repo.js +297 -0
  12. package/dist/runtime-verb.js +1 -1
  13. package/dist/secret.js +1 -1
  14. package/dist/skill-shape.js +21 -13
  15. package/dist/skills.js +44 -4
  16. package/dist/transport.js +26 -1
  17. package/package.json +5 -4
  18. package/skills/catalyst-github/SKILL.md +7 -7
  19. package/skills/catalyst-github/references/is-it-mergeable.md +8 -2
  20. package/skills/catalyst-github/references/what-a-pr-accumulates.md +3 -3
  21. package/skills/catalyst-github/scripts/is-it-mergeable.mjs +3 -3
  22. package/skills/catalyst-github/scripts/lib/cli.mjs +9 -7
  23. package/skills/catalyst-github/scripts/lib/credential.mjs +2 -2
  24. package/skills/catalyst-github/scripts/read-pr.mjs +2 -2
  25. package/skills/catalyst-linear/SKILL.md +17 -19
  26. package/skills/catalyst-linear/agents/openai.yaml +1 -1
  27. package/skills/catalyst-linear/agents/portability.yaml +1 -1
  28. package/skills/catalyst-linear/references/reading-a-ticket.md +9 -26
  29. package/skills/catalyst-linear/references/what-a-ticket-accumulates.md +2 -2
  30. package/skills/catalyst-linear/references/writing-to-linear.md +7 -9
  31. package/skills/catalyst-linear/scripts/comment.mjs +1 -1
  32. package/skills/catalyst-linear/scripts/create-ticket.mjs +1 -1
  33. package/skills/catalyst-linear/scripts/label.mjs +1 -1
  34. package/skills/catalyst-linear/scripts/lib/cli.mjs +9 -7
  35. package/skills/catalyst-linear/scripts/lib/credential.mjs +2 -2
  36. package/skills/catalyst-linear/scripts/move.mjs +1 -1
  37. package/skills/catalyst-linear/scripts/read-ticket.mjs +1 -1
  38. package/skills/catalyst-linear/scripts/search.mjs +1 -1
  39. package/skills/catalyst-onboard/SKILL.md +37 -57
  40. package/skills/catalyst-onboard/agents/openai.yaml +2 -2
  41. package/skills/catalyst-onboard/agents/portability.yaml +1 -1
  42. package/skills/catalyst-onboard/references/connecting-this-machine.md +35 -0
  43. package/skills/catalyst-onboard/references/declaring-a-repository.md +7 -17
  44. package/skills/catalyst-onboard/references/local-sync.md +19 -7
  45. package/skills/catalyst-onboard/references/reading-ready.md +79 -0
  46. package/skills/catalyst-onboard/references/replacing-a-credential.md +8 -33
  47. package/skills/catalyst-onboard/references/repository-agent-setup.md +23 -0
  48. package/skills/catalyst-onboard/references/skill-sources.md +13 -19
  49. package/skills/catalyst-onboard/references/the-one-path.md +18 -74
  50. package/skills/catalyst-onboard/references/what-a-phase-needs.md +21 -28
  51. package/skills/catalyst-onboard/references/what-the-browser-owns.md +20 -37
  52. package/skills/{catalyst-setup → catalyst-onboard}/scripts/check.mjs +10 -9
  53. package/skills/catalyst-onboard/scripts/lib/cli.mjs +6 -4
  54. package/skills/catalyst-onboard/scripts/lib/credential.mjs +2 -2
  55. package/skills/catalyst-onboard/scripts/where-am-i.mjs +60 -4
  56. package/skills/run-this-project/SKILL.md +23 -25
  57. package/skills/run-this-project/agents/openai.yaml +1 -1
  58. package/skills/run-this-project/agents/portability.yaml +1 -1
  59. package/skills/run-this-project/references/making-work-ready.md +20 -37
  60. package/skills/run-this-project/references/reacting-to-events.md +25 -48
  61. package/skills/run-this-project/references/stalls-and-escalation.md +20 -42
  62. package/skills/run-this-project/scripts/lib/cli.mjs +7 -5
  63. package/skills/run-this-project/scripts/lib/credential.mjs +2 -2
  64. package/skills/run-this-project/scripts/scope-status.mjs +0 -0
  65. package/skills/run-this-project/scripts/watch-scope.mjs +1 -1
  66. package/skills/unstick/SKILL.md +12 -12
  67. package/skills/unstick/agents/openai.yaml +1 -1
  68. package/skills/unstick/agents/portability.yaml +1 -1
  69. package/skills/unstick/references/playbook.md +13 -13
  70. package/skills/unstick/scripts/lib/cli.mjs +6 -4
  71. package/skills/unstick/scripts/lib/credential.mjs +2 -2
  72. package/skills/unstick/scripts/unstick.mjs +1 -1
  73. package/skills/what-needs-me/SKILL.md +12 -14
  74. package/skills/what-needs-me/agents/openai.yaml +2 -2
  75. package/skills/what-needs-me/agents/portability.yaml +1 -1
  76. package/skills/what-needs-me/references/raising-a-decision.md +8 -16
  77. package/skills/what-needs-me/references/reading-the-inbox.md +6 -13
  78. package/skills/what-needs-me/references/settling-an-answer.md +6 -12
  79. package/skills/what-needs-me/scripts/inbox.mjs +14 -13
  80. package/skills/what-needs-me/scripts/lib/cli.mjs +6 -4
  81. package/skills/what-needs-me/scripts/lib/credential.mjs +2 -2
  82. package/skills/what-needs-me/scripts/raise.mjs +1 -1
  83. package/skills/what-needs-me/scripts/settle.mjs +1 -1
  84. package/skills/what-this-repo-needs/SKILL.md +10 -19
  85. package/skills/what-this-repo-needs/references/what-each-group-means.md +14 -44
  86. package/skills/what-this-repo-needs/scripts/check.mjs +2 -2
  87. package/skills/what-this-repo-needs/scripts/inventory.mjs +2 -2
  88. package/skills/what-this-repo-needs/scripts/lib/cli.mjs +11 -9
  89. package/skills/what-this-repo-needs/scripts/lib/credential.mjs +2 -2
  90. package/skills/whats-happening/SKILL.md +27 -21
  91. package/skills/whats-happening/agents/openai.yaml +1 -1
  92. package/skills/whats-happening/references/coding-accounts.md +24 -0
  93. package/skills/whats-happening/references/routing-work.md +11 -29
  94. package/skills/whats-happening/references/settings-and-where-they-live.md +20 -0
  95. package/skills/whats-happening/references/stages-and-mapping.md +25 -0
  96. package/skills/whats-happening/references/status-reply.md +21 -23
  97. package/skills/whats-happening/references/the-ladder.md +30 -0
  98. package/skills/whats-happening/references/what-runs-next.md +32 -0
  99. package/skills/whats-happening/references/when-a-phase-fails.md +27 -0
  100. package/skills/whats-happening/references/why-is-it-stuck.md +30 -44
  101. package/skills/whats-happening/scripts/explain.mjs +1 -1
  102. package/skills/whats-happening/scripts/lib/cli.mjs +7 -5
  103. package/skills/whats-happening/scripts/lib/credential.mjs +2 -2
  104. package/skills/{how-catalyst-works → whats-happening}/scripts/show-my-map.mjs +18 -32
  105. package/skills/whats-happening/scripts/snapshot.mjs +10 -6
  106. package/skills/catalyst-onboard/references/choosing-a-coding-account.md +0 -52
  107. package/skills/catalyst-onboard/references/who-fixes-what.md +0 -64
  108. package/skills/catalyst-setup/SKILL.md +0 -36
  109. package/skills/catalyst-setup/agents/openai.yaml +0 -6
  110. package/skills/catalyst-setup/agents/portability.yaml +0 -4
  111. package/skills/catalyst-setup/references/what-each-check-means.md +0 -88
  112. package/skills/catalyst-setup/scripts/lib/cli.mjs +0 -103
  113. package/skills/catalyst-setup/scripts/lib/credential.mjs +0 -29
  114. package/skills/catalyst-setup/scripts/replica-status.mjs +0 -46
  115. package/skills/connect-me/SKILL.md +0 -63
  116. package/skills/connect-me/agents/openai.yaml +0 -6
  117. package/skills/connect-me/agents/portability.yaml +0 -5
  118. package/skills/connect-me/references/keeping-the-replica-running.md +0 -88
  119. package/skills/connect-me/scripts/lib/cli.mjs +0 -185
  120. package/skills/connect-me/scripts/lib/credential.mjs +0 -29
  121. package/skills/connect-me/scripts/verify-connection.mjs +0 -68
  122. package/skills/how-catalyst-works/SKILL.md +0 -45
  123. package/skills/how-catalyst-works/agents/openai.yaml +0 -6
  124. package/skills/how-catalyst-works/agents/portability.yaml +0 -4
  125. package/skills/how-catalyst-works/references/coding-accounts.md +0 -51
  126. package/skills/how-catalyst-works/references/settings-and-where-they-live.md +0 -20
  127. package/skills/how-catalyst-works/references/stages-and-mapping.md +0 -56
  128. package/skills/how-catalyst-works/references/the-ladder.md +0 -41
  129. package/skills/how-catalyst-works/references/what-catalyst-is.md +0 -30
  130. package/skills/how-catalyst-works/references/what-runs-next.md +0 -95
  131. package/skills/how-catalyst-works/references/when-a-phase-fails.md +0 -57
  132. package/skills/how-catalyst-works/scripts/explain-ticket.mjs +0 -41
  133. package/skills/how-catalyst-works/scripts/lib/cli.mjs +0 -164
  134. package/skills/how-catalyst-works/scripts/lib/credential.mjs +0 -29
  135. package/skills/how-catalyst-works/scripts/whats-running.mjs +0 -65
  136. package/skills/whats-happening/references/reading-the-board.md +0 -43
  137. package/skills/whats-happening/references/reprioritising.md +0 -37
package/dist/legacy.js ADDED
@@ -0,0 +1,224 @@
1
+ // legacy.ts — `catalyst legacy`: leftovers of the old LOCAL Catalyst runtime (the archived repository
2
+ // whose plugin, daemons, scheduled jobs and state folders a machine may still carry), found from a
3
+ // FIXED list and removed only on a yes, through the tools that own each piece. The cloud runtime
4
+ // replaced all of it; what is left can start old jobs or shadow current commands, so removal is
5
+ // recommended, and never automatic: a run with no terminal and no --yes only reports.
6
+ //
7
+ // The list is fixed on purpose. A prefix match would one day catch a current job (the housekeeping
8
+ // job, the sandbox credit guard, jobs a person made); this matches names the old runtime installed,
9
+ // read at the source commit below, and nothing else. Data folders are a separate yes (--data).
10
+ import { existsSync, lstatSync, readFileSync, readdirSync, rmSync, unlinkSync } from "node:fs";
11
+ import { spawnSync } from "node:child_process";
12
+ import { join } from "node:path";
13
+ import { flagBool, positionals } from "./args.js";
14
+ import { UsageError } from "./errors.js";
15
+ import { promptSecret, stdinIsTty } from "./prompt.js";
16
+ /** The archived repository's commit the list below was read at. */
17
+ export const LEGACY_SOURCE_COMMIT = "73bc0645252ce8be38f8c87be6b67b950b3f0b56";
18
+ /** The old runtime's marketplace source, as Claude Code records it in known_marketplaces.json. */
19
+ export const OLD_MARKETPLACE_REPO = "coalesce-labs/catalyst";
20
+ /** launchd labels the old runtime installed under ~/Library/LaunchAgents (macOS). `com.catalyst.role.<name>`
21
+ * is the old role supervisor's per-role instance, matched by that exact prefix. Never `dev.catalystcloud.*`
22
+ * (the current housekeeping job and runner jobs) and never `dev.catalyst.*` (the sandbox credit guard). */
23
+ export const OLD_LAUNCHD_LABELS = [
24
+ "com.catalyst.agent",
25
+ "com.catalyst.reaper-watch",
26
+ "com.catalyst.quiet-fleet",
27
+ "com.catalyst.dead-man",
28
+ "com.catalyst.holding-sentinel",
29
+ "com.catalyst.orch-monitor",
30
+ "com.catalyst.role",
31
+ "ai.coalesce.catalyst-stack",
32
+ "ai.coalesce.catalyst-thoughts-sync",
33
+ "ai.coalesce.catalyst-orphan-sweep",
34
+ "ai.coalesce.catalyst-log-shipper",
35
+ "ai.coalesce.catalyst-cloud-sync",
36
+ "ai.coalesce.catalyst-usage-page",
37
+ "ai.coalesce.catalyst-claude-update",
38
+ "ai.coalesce.catalyst-updater",
39
+ "ai.coalesce.catalyst-replica-sync",
40
+ "ai.coalesce.catalyst-channel-watcher",
41
+ "ai.coalesce.catalyst-event-mirror",
42
+ "ai.coalesce.catalyst-monitor",
43
+ ];
44
+ const OLD_ROLE_PREFIX = "com.catalyst.role.";
45
+ /** systemd user units (~/.config/systemd/user) the old runtime's workstation pieces used on Linux. System
46
+ * units under /etc/systemd/system are a host's, current, and never looked at. */
47
+ export const OLD_USER_UNITS = ["catalyst.service", "catalyst-monitor.service"];
48
+ /** Command files the old runtime put on the person's PATH. `~/.local/bin/catalyst` is NOT one: that
49
+ * name belongs to the current CLI wherever npm put it. */
50
+ export const OLD_BINS = [".catalyst/bin", ".local/bin/catalyst-events", ".local/bin/catalyst-filter", ".local/bin/catalyst-hud", ".local/bin/catalyst-monitor", ".local/bin/catalyst-myown"];
51
+ /** State the old runtime kept. `~/.config/catalyst-cloud` is the current CLI's and never touched. */
52
+ export const OLD_DATA_DIRS = [".catalyst", ".config/catalyst", ".local/state/catalyst", ".local/state/catalyst-fleet-runner", ".local/state/catalyst-ledger"];
53
+ const RECOMMEND = "Remove them: the cloud runtime replaced them, and left in place they can start old jobs or shadow current commands.";
54
+ function readJson(path) {
55
+ try {
56
+ const v = JSON.parse(readFileSync(path, "utf8"));
57
+ return v !== null && typeof v === "object" ? v : null;
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
63
+ /** Marketplaces whose recorded source is the old repository, and the plugins installed from them. */
64
+ function findPlugins(home) {
65
+ const dir = join(home, ".claude", "plugins");
66
+ const marketplaces = readJson(join(dir, "known_marketplaces.json")) ?? {};
67
+ const old = Object.entries(marketplaces)
68
+ .filter(([, v]) => {
69
+ const src = v?.source;
70
+ return typeof src?.repo === "string" && src.repo.toLowerCase() === OLD_MARKETPLACE_REPO;
71
+ })
72
+ .map(([name]) => name);
73
+ if (old.length === 0)
74
+ return [];
75
+ const installed = (readJson(join(dir, "installed_plugins.json")) ?? {}).plugins ?? {};
76
+ const items = [];
77
+ for (const key of Object.keys(installed)) {
78
+ const at = key.lastIndexOf("@");
79
+ if (at > 0 && old.includes(key.slice(at + 1)))
80
+ items.push({ kind: "plugin", name: key, path: join(dir, "installed_plugins.json") });
81
+ }
82
+ for (const name of old)
83
+ items.push({ kind: "marketplace", name, path: join(dir, "known_marketplaces.json") });
84
+ return items;
85
+ }
86
+ function findJobs(home, platform) {
87
+ if (platform === "darwin") {
88
+ const dir = join(home, "Library", "LaunchAgents");
89
+ let files = [];
90
+ try {
91
+ files = readdirSync(dir);
92
+ }
93
+ catch {
94
+ return [];
95
+ }
96
+ return files
97
+ .filter((f) => f.endsWith(".plist"))
98
+ .map((f) => f.slice(0, -".plist".length))
99
+ .filter((label) => OLD_LAUNCHD_LABELS.includes(label) || label.startsWith(OLD_ROLE_PREFIX))
100
+ .sort()
101
+ .map((label) => ({ kind: "job", name: label, path: join(dir, `${label}.plist`) }));
102
+ }
103
+ if (platform === "linux") {
104
+ const dir = join(home, ".config", "systemd", "user");
105
+ return OLD_USER_UNITS.filter((u) => existsSync(join(dir, u))).map((u) => ({ kind: "job", name: u, path: join(dir, u) }));
106
+ }
107
+ return [];
108
+ }
109
+ const tilde = (rel) => `~/${rel}`;
110
+ function findFiles(home) {
111
+ const bins = OLD_BINS.filter((rel) => existsSync(join(home, rel))).map((rel) => ({ kind: "bin", name: tilde(rel), path: join(home, rel) }));
112
+ const data = OLD_DATA_DIRS.filter((rel) => existsSync(join(home, rel))).map((rel) => ({ kind: "data", name: tilde(rel), path: join(home, rel), data: true }));
113
+ return [...bins, ...data];
114
+ }
115
+ /** Every old piece on this machine, in removal order: plugins, their marketplace, jobs, bins, data. Never writes. */
116
+ export function findLegacy(home, platform) {
117
+ return [...findPlugins(home), ...findJobs(home, platform), ...findFiles(home)];
118
+ }
119
+ const defaultRun = (cmd, args) => {
120
+ const r = spawnSync(cmd, args, { encoding: "utf8", timeout: 60_000 });
121
+ return { status: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.error ? r.error.message : (r.stderr ?? "") };
122
+ };
123
+ /** Remove one item through the tool that owns it. Returns null on success, else the reason it is still there. */
124
+ function remove(item, run, platform, uid) {
125
+ const tool = (cmd, args, what) => {
126
+ const r = run(cmd, args);
127
+ return r.status === 0 ? null : `${what} failed: ${(r.stderr || r.stdout).trim().split("\n")[0] || `exit ${r.status}`}`;
128
+ };
129
+ try {
130
+ if (item.kind === "plugin")
131
+ return tool("claude", ["plugin", "uninstall", item.name], "claude plugin uninstall");
132
+ if (item.kind === "marketplace")
133
+ return tool("claude", ["plugin", "marketplace", "remove", item.name], "claude plugin marketplace remove");
134
+ if (item.kind === "job") {
135
+ const why = platform === "darwin" ? tool("launchctl", ["bootout", `gui/${uid}/${item.name}`], "launchctl bootout") : tool("systemctl", ["--user", "disable", "--now", item.name], "systemctl --user disable --now");
136
+ if (why !== null)
137
+ return why;
138
+ unlinkSync(item.path);
139
+ return null;
140
+ }
141
+ // a bin or a data folder: a file goes with unlink, a directory (~/.catalyst/bin, the data) with rm -rf
142
+ if (lstatSync(item.path).isDirectory())
143
+ rmSync(item.path, { recursive: true, force: true });
144
+ else
145
+ unlinkSync(item.path);
146
+ return null;
147
+ }
148
+ catch (err) {
149
+ return `could not remove: ${err instanceof Error ? err.message : String(err)}`;
150
+ }
151
+ }
152
+ export async function cmdLegacy(args, ctx, deps = {}) {
153
+ if (positionals(args).length > 0)
154
+ throw new UsageError("legacy takes no positional argument; flags are --remove, --data, --yes, --json");
155
+ const wantRemove = flagBool(args, "remove");
156
+ const withData = flagBool(args, "data");
157
+ if (withData && !wantRemove)
158
+ throw new UsageError("--data belongs with --remove");
159
+ const platform = deps.platform ?? process.platform;
160
+ const uid = deps.uid ?? (typeof process.getuid === "function" ? process.getuid() : 0);
161
+ const run = deps.run ?? defaultRun;
162
+ const found = findLegacy(ctx.home, platform);
163
+ const emit = (body, lines) => { if (args.json)
164
+ ctx.stdout(JSON.stringify(body));
165
+ else
166
+ for (const l of lines)
167
+ ctx.stdout(l); };
168
+ if (found.length === 0) {
169
+ emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found: [], removed: [], remaining: [] }, ["no leftovers of the old local Catalyst runtime on this machine"]);
170
+ return 0;
171
+ }
172
+ const listLines = [
173
+ `Leftovers of the old local Catalyst runtime on this machine (${found.length}):`,
174
+ ...found.map((f) => ` ${f.kind}: ${f.name}${f.kind === "job" ? ` — ${f.path}` : f.data ? " (kept unless --data)" : ""}`),
175
+ ];
176
+ if (!wantRemove) {
177
+ emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found, removed: [], remaining: found }, [...listLines, RECOMMEND, "Run: catalyst legacy --remove (add --data to delete its data folders too)"]);
178
+ return 1;
179
+ }
180
+ // the one question, only on a terminal; --yes answers it without asking
181
+ let go = flagBool(args, "yes");
182
+ if (!go) {
183
+ const tty = (deps.isTty ?? stdinIsTty)();
184
+ if (!tty) {
185
+ emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found, removed: [], remaining: found, asked: false }, [...listLines, RECOMMEND, "nothing removed: no terminal to ask on; run catalyst legacy --remove --yes to remove these without a question (add --data for the data folders)"]);
186
+ return 1;
187
+ }
188
+ for (const l of listLines)
189
+ ctx.stdout(l);
190
+ ctx.stdout(RECOMMEND);
191
+ const answer = (await (deps.prompt ?? ((q) => promptSecret(q)))(`Remove ${found.length} item${found.length === 1 ? "" : "s"}${withData ? ", data folders included" : ", keeping the data folders"}? [y/N] `)).trim().toLowerCase();
192
+ go = answer === "y" || answer === "yes";
193
+ if (!go) {
194
+ emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found, removed: [], remaining: found, asked: true }, ["nothing removed; run catalyst legacy --remove again when ready"]);
195
+ return 1;
196
+ }
197
+ }
198
+ const removed = [];
199
+ const failed = [];
200
+ const kept = [];
201
+ const lines = [];
202
+ for (const item of found) {
203
+ if (item.data && !withData) {
204
+ kept.push(item);
205
+ lines.push(`kept: ${item.kind} ${item.name} (run with --data to delete it)`);
206
+ continue;
207
+ }
208
+ const why = remove(item, run, platform, uid);
209
+ if (why === null) {
210
+ removed.push(item);
211
+ lines.push(`removed: ${item.kind} ${item.name}`);
212
+ }
213
+ else {
214
+ failed.push({ item, why });
215
+ lines.push(`still present: ${item.kind} ${item.name} (${why})`);
216
+ }
217
+ }
218
+ // re-check from the same list, so the report says what the machine holds now, not what was attempted
219
+ const remaining = findLegacy(ctx.home, platform).filter((f) => !(f.data && !withData));
220
+ const keptNote = kept.length > 0 ? " except the data folders you kept" : "";
221
+ lines.push(remaining.length === 0 ? `re-checked: nothing of the old runtime remains${keptNote}` : `re-checked: ${remaining.length} item${remaining.length === 1 ? "" : "s"} of the old runtime remain${remaining.length === 1 ? "s" : ""}${keptNote}: ${remaining.map((r) => `${r.kind} ${r.name}`).join(", ")}`);
222
+ emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found, removed, remaining: [...remaining, ...kept], kept, failed }, lines);
223
+ return remaining.length === 0 ? 0 : 1;
224
+ }
@@ -0,0 +1,129 @@
1
+ // project.ts — `catalyst project wip-limit get|set`: a project's new-start WIP limit, on the
2
+ // person's own login. Any active member reads it; a workspace owner or admin sets it. The limit is
3
+ // per Catalyst project (one Linear team across all its repositories): the project's stored value,
4
+ // else the workspace value, else the default the cloud reports. It holds only NEW starts, so the
5
+ // reply carries the work in progress beside the limit: that count, not a runner count, is what a
6
+ // person compares. The route is the cloud's own member route; the reply shape is the cloud's, so a
7
+ // field this CLI does not know is passed through under --json untouched.
8
+ import { flagString, positionals } from "./args.js";
9
+ import { requireConfig } from "./config.js";
10
+ import { loadContract } from "./contract.js";
11
+ import { UsageError } from "./errors.js";
12
+ import { apiClient } from "./transport.js";
13
+ /** The limit's bounds, as the cloud clamps them. A value outside is refused here, before any request. */
14
+ export const WIP_LIMIT_MIN = 0;
15
+ export const WIP_LIMIT_MAX = 9999;
16
+ /** The agent twin of the member route: a bearer reads it with `?team=<key or id>` and writes it with a
17
+ * body naming the team, the way the team-workflow verbs do. The contract's route table lists these
18
+ * two strings, so `capabilities` can judge them. */
19
+ export const WIP_LIMIT_ROUTE = "/api/v1/agent/team-wip-limit";
20
+ export const wipLimitPath = (team) => `${WIP_LIMIT_ROUTE}?team=${encodeURIComponent(team)}`;
21
+ const SOURCE_TEXT = { project: "set for this project", flag: "workspace value", default: "default" };
22
+ const sourceText = (source) => SOURCE_TEXT[String(source)] ?? String(source ?? "unknown");
23
+ /** The project `--team` names, or the only mapped project when the flag is absent. Never a guess between two. */
24
+ export function resolveTeam(doc, wanted) {
25
+ const teams = Array.isArray(doc.teams) ? doc.teams : [];
26
+ if (wanted !== undefined) {
27
+ const lower = wanted.toLocaleLowerCase();
28
+ const found = teams.find((t) => (t.key ?? "").toLocaleLowerCase() === lower || t.id === wanted);
29
+ if (!found)
30
+ throw new UsageError(`no mapped project has the team key ${wanted}${teams.length ? ` (mapped: ${teams.map((t) => t.key ?? t.id).join(", ")})` : " (no project is mapped yet)"}`);
31
+ return found;
32
+ }
33
+ if (teams.length === 1)
34
+ return teams[0];
35
+ if (teams.length === 0)
36
+ throw new UsageError("no project is mapped yet; map one first (catalyst team map <KEY>)");
37
+ throw new UsageError(`--team is needed: ${teams.length} projects are mapped (${teams.map((t) => t.key ?? t.id).join(", ")})`);
38
+ }
39
+ /** `set`'s value: an integer inside the cloud's bounds, or the word default. Parsed before any request. */
40
+ export function parseLimit(raw) {
41
+ if (raw === undefined)
42
+ throw new UsageError("project wip-limit set needs a value: an integer, or default");
43
+ if (raw === "default")
44
+ return null;
45
+ if (!/^-?\d+$/.test(raw))
46
+ throw new UsageError(`the limit must be an integer from ${WIP_LIMIT_MIN} to ${WIP_LIMIT_MAX}, or default (got ${raw})`);
47
+ const n = Number(raw);
48
+ if (n < WIP_LIMIT_MIN || n > WIP_LIMIT_MAX)
49
+ throw new UsageError(`the limit must be from ${WIP_LIMIT_MIN} to ${WIP_LIMIT_MAX} (got ${raw}); 0 holds every new start`);
50
+ return n;
51
+ }
52
+ /** The in-progress tickets as identifiers, tolerant of the cloud sending strings or objects; [] when absent. */
53
+ export function ticketIds(value) {
54
+ if (!Array.isArray(value))
55
+ return [];
56
+ return value
57
+ .map((t) => (typeof t === "string" ? t : t && typeof t === "object" ? String(t.identifier ?? t.id ?? "") : ""))
58
+ .filter((t) => t !== "");
59
+ }
60
+ /** One line naming what holds the WIP, capped so a big team does not scroll; null when the cloud sent none. */
61
+ function inProgressLine(view) {
62
+ const ids = ticketIds(view.inProgressTickets);
63
+ if (ids.length === 0)
64
+ return null;
65
+ const shown = ids.slice(0, 12);
66
+ return `in progress: ${shown.join(", ")}${ids.length > shown.length ? ` and ${ids.length - shown.length} more` : ""} — these are what a new ticket waits on; unstick them, not the queue`;
67
+ }
68
+ function line(key, view) {
69
+ const limit = view.limit;
70
+ const inProgress = view.inProgress;
71
+ const at = typeof limit === "number" && typeof inProgress === "number" && inProgress >= limit ? " — at the limit: a new ticket waits until one in progress finishes" : "";
72
+ return `${key}: ${typeof inProgress === "number" ? inProgress : "?"} in progress, limit ${typeof limit === "number" ? limit : "?"} (${sourceText(view.source)})${at}`;
73
+ }
74
+ export async function cmdProject(args, ctx) {
75
+ const [sub, action, value, ...extra] = positionals(args);
76
+ if (sub !== "wip-limit")
77
+ throw new UsageError("project needs wip-limit <get|set <n>|default>");
78
+ if (action !== "get" && action !== "set")
79
+ throw new UsageError("project wip-limit needs get, or set <n>|default");
80
+ if (action === "get" && value !== undefined)
81
+ throw new UsageError("project wip-limit get takes no value; set does");
82
+ if (extra.length > 0)
83
+ throw new UsageError("project wip-limit takes one value at most");
84
+ const limit = action === "set" ? parseLimit(value) : null;
85
+ const cfg = requireConfig(ctx);
86
+ const { doc } = await loadContract(ctx, cfg);
87
+ const team = resolveTeam(doc, flagString(args, "team"));
88
+ const key = team.key ?? team.id;
89
+ const client = apiClient(cfg, ctx);
90
+ const accept = [400, 403, 404];
91
+ const emit = (body, lines) => { if (args.json)
92
+ ctx.stdout(JSON.stringify(body));
93
+ else
94
+ for (const l of lines)
95
+ ctx.stdout(l); };
96
+ const refuse = (status, reply) => {
97
+ // The cloud's error bodies carry `error` (the code to match on) and a human `message`.
98
+ const body = reply ?? {};
99
+ const detail = body.message || body.reason ? ` (${String(body.message ?? body.reason)})` : "";
100
+ const why = status === 403
101
+ ? `setting the limit needs a workspace owner or admin; any member can read it with catalyst project wip-limit get${detail}`
102
+ : status === 404 && body.error === "team-unknown"
103
+ ? `this cloud does not know a team ${key}; check the key with catalyst team list${detail}`
104
+ : status === 404
105
+ ? "this Catalyst Cloud does not serve the wip-limit route yet (needs a newer cloud)"
106
+ : `${String(body.error ?? body.code ?? "bad request")}${detail}`;
107
+ emit({ status, team: { id: team.id, key }, ...body }, [`refused (${status}): ${why}`]);
108
+ return 1;
109
+ };
110
+ const before = await client.getJson(wipLimitPath(team.id), { accept, parseAccepted: true });
111
+ if (before.status !== 200)
112
+ return refuse(before.status, before.body);
113
+ if (action === "get") {
114
+ emit({ team: { id: team.id, key }, ...before.body }, [
115
+ line(key, before.body),
116
+ ...(inProgressLine(before.body) === null ? [] : [inProgressLine(before.body)]),
117
+ `change it: catalyst project wip-limit set <n> --team ${key} (owner or admin; set default returns to the workspace value)`,
118
+ ]);
119
+ return 0;
120
+ }
121
+ const after = await client.postJson(WIP_LIMIT_ROUTE, { team: team.id, limit }, { accept });
122
+ if (after.status !== 200)
123
+ return refuse(after.status, after.body);
124
+ emit({ team: { id: team.id, key }, ...after.body, previous: { limit: before.body.limit, source: before.body.source } }, [
125
+ `${key}: limit ${String(before.body.limit)} (${sourceText(before.body.source)}) → ${String(after.body.limit)} (${sourceText(after.body.source)})${after.body.limit === 0 ? "; 0 holds every new start" : ""}`,
126
+ line(key, after.body),
127
+ ]);
128
+ return 0;
129
+ }
package/dist/release.js CHANGED
@@ -1,4 +1,4 @@
1
- // release.ts — `catalyst-skills release`: a person's release of a parked or held ticket, or of every
1
+ // release.ts — `catalyst release`: a person's release of a parked or held ticket, or of every
2
2
  // ticket on one team parked under one failure class, through the contract's `ticket-release` and
3
3
  // `ticket-release-class` routes. The cloud reads every governor holding the ticket and either releases
4
4
  // all of them or releases nothing and names, per governor, the human action that does fix it; this verb
package/dist/repo.js ADDED
@@ -0,0 +1,297 @@
1
+ // repo.ts — `catalyst repo agents-block` and `catalyst repo agent-setup`: a repository's agent setup,
2
+ // read and changed in a checkout the person names, never through git and never through the cloud.
3
+ //
4
+ // repo agents-block <path> [--write] the one Catalyst block in AGENTS.md, marker-delimited,
5
+ // replaced in place on a rerun (never duplicated)
6
+ // repo agent-setup <path> [--apply] [--with-check]
7
+ // what the repository holds for agents, whether it is
8
+ // portable, the plan that would make it so, and --apply
9
+ //
10
+ // Portable means: AGENTS.md is canonical; CLAUDE.md is a thin file that imports it with a line that
11
+ // is exactly `@AGENTS.md` plus Claude-only notes; `.agents/skills` and `.agents/rules` are canonical
12
+ // and `.claude/skills` and `.claude/rules` are relative symlinks to them. Every write lands in the
13
+ // working tree only: committing, branching and the pull request are the person's, in the open.
14
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, renameSync, statSync, symlinkSync, writeFileSync } from "node:fs";
15
+ import { dirname, join, relative, resolve } from "node:path";
16
+ import { flagBool, positionals } from "./args.js";
17
+ import { UsageError } from "./errors.js";
18
+ export const BLOCK_START = "<!-- catalyst:start -->";
19
+ export const BLOCK_END = "<!-- catalyst:end -->";
20
+ /** The two skills the block names. ONE place each: the packs are being consolidated, and a rename
21
+ * lands here, then `repo agents-block --write` brings every repository's block up to date. */
22
+ export const BLOCK_PROCESS_SKILL = "whats-happening";
23
+ export const BLOCK_DECISION_SKILL = "catalyst-sop";
24
+ /** ⭐ THE block, word for word. Harness-agnostic; names the skills, never the process. */
25
+ export const CATALYST_AGENTS_BLOCK = [
26
+ BLOCK_START,
27
+ "## Catalyst",
28
+ "",
29
+ `This repository is worked through Catalyst: tickets move through a pipeline of agent-run phases, and pull requests merge through its queue. Before you plan, branch, review or merge here, load the skill that explains the process instead of inferring it from this file: \`${BLOCK_PROCESS_SKILL}\` (how a ticket runs, what each phase produces, why work waits), and \`${BLOCK_DECISION_SKILL}\` when it is installed (what to do when work stalls on a decision). Keep this block as it is; onboarding maintains it.`,
30
+ BLOCK_END,
31
+ ].join("\n");
32
+ /** Where the block sits in `text`, or null. Only the FIRST start marker and the first end after it count. */
33
+ function locateBlock(text) {
34
+ const start = text.indexOf(BLOCK_START);
35
+ if (start === -1)
36
+ return null;
37
+ const endAt = text.indexOf(BLOCK_END, start);
38
+ if (endAt === -1)
39
+ return null;
40
+ return { start, end: endAt + BLOCK_END.length };
41
+ }
42
+ /** The block's state in an AGENTS.md text (`null` text = no file). */
43
+ export function blockState(text) {
44
+ if (text === null)
45
+ return "absent";
46
+ const at = locateBlock(text);
47
+ if (at === null)
48
+ return "missing";
49
+ return text.slice(at.start, at.end) === CATALYST_AGENTS_BLOCK ? "current" : "stale";
50
+ }
51
+ /** The text with the block current: replaced in place, appended after one blank line, or the whole
52
+ * file. Pure and idempotent: applying it to its own output changes nothing. */
53
+ export function withBlock(text) {
54
+ if (text === null || text.trim() === "")
55
+ return `${CATALYST_AGENTS_BLOCK}\n`;
56
+ const at = locateBlock(text);
57
+ if (at !== null)
58
+ return `${text.slice(0, at.start)}${CATALYST_AGENTS_BLOCK}${text.slice(at.end)}`;
59
+ const body = text.replace(/\s+$/, "");
60
+ return `${body}\n\n${CATALYST_AGENTS_BLOCK}\n`;
61
+ }
62
+ function linkState(root, rel, canonicalRel) {
63
+ const p = join(root, rel);
64
+ let st;
65
+ try {
66
+ st = lstatSync(p);
67
+ }
68
+ catch {
69
+ return { kind: "absent" };
70
+ }
71
+ if (st.isSymbolicLink()) {
72
+ const target = readlinkSync(p);
73
+ const resolved = resolve(dirname(p), target);
74
+ return { kind: "symlink", target, resolvesToCanonical: resolved === resolve(root, canonicalRel) && existsSync(resolved) };
75
+ }
76
+ return st.isDirectory() ? { kind: "dir" } : { kind: "file" };
77
+ }
78
+ const OTHER_MARKERS = [".codex", ".cursor", ".cursorrules", ".windsurfrules", "GEMINI.md", ".github/copilot-instructions.md"];
79
+ /** Read a checkout's agent setup. Never writes. */
80
+ export function inspectRepo(root) {
81
+ const agentsPath = join(root, "AGENTS.md");
82
+ const claudePath = join(root, "CLAUDE.md");
83
+ const agentsText = existsSync(agentsPath) ? readFileSync(agentsPath, "utf8") : null;
84
+ const claudeText = existsSync(claudePath) ? readFileSync(claudePath, "utf8") : null;
85
+ const claudeLines = claudeText === null ? [] : claudeText.split("\n");
86
+ const importsAgentsMd = claudeLines.some((l) => l.trim() === "@AGENTS.md");
87
+ const otherLines = claudeLines.filter((l) => l.trim() !== "" && l.trim() !== "@AGENTS.md").length;
88
+ const report = {
89
+ path: root,
90
+ agentsMd: { present: agentsText !== null, lines: agentsText === null ? 0 : agentsText.replace(/\n$/, "").split("\n").length, bytes: agentsText === null ? 0 : Buffer.byteLength(agentsText), block: blockState(agentsText) },
91
+ claudeMd: { present: claudeText !== null, importsAgentsMd, otherLines },
92
+ agentsDir: { skills: isDir(join(root, ".agents", "skills")), rules: isDir(join(root, ".agents", "rules")) },
93
+ claudeDir: { skills: linkState(root, ".claude/skills", ".agents/skills"), rules: linkState(root, ".claude/rules", ".agents/rules") },
94
+ others: OTHER_MARKERS.filter((m) => existsSync(join(root, m))),
95
+ verdict: "portable",
96
+ plan: [],
97
+ blockers: [],
98
+ };
99
+ // CLAUDE.md with guidance of its own and no import: its content belongs in AGENTS.md.
100
+ if (report.claudeMd.present && !importsAgentsMd) {
101
+ report.plan.push(report.agentsMd.present
102
+ ? "append CLAUDE.md's content to AGENTS.md and leave CLAUDE.md as the thin importer (`@AGENTS.md` plus Claude-only notes)"
103
+ : "create AGENTS.md from CLAUDE.md's content and leave CLAUDE.md as the thin importer (`@AGENTS.md`)");
104
+ }
105
+ else if (!report.agentsMd.present && !report.claudeMd.present) {
106
+ report.plan.push("create AGENTS.md (the Catalyst block starts it; add the repository's own guidance there)");
107
+ }
108
+ for (const name of ["skills", "rules"]) {
109
+ const c = report.claudeDir[name];
110
+ const canonical = report.agentsDir[name];
111
+ if (c.kind === "dir" && !canonical)
112
+ report.plan.push(`move .claude/${name} to .agents/${name} and leave .claude/${name} as a relative symlink to it`);
113
+ else if (c.kind === "dir" && canonical)
114
+ report.blockers.push(`.claude/${name} and .agents/${name} are both real directories: merge them by hand, then leave .claude/${name} as a relative symlink`);
115
+ else if (c.kind === "symlink" && !c.resolvesToCanonical)
116
+ report.blockers.push(`.claude/${name} is a symlink to ${c.target}, not to .agents/${name}: point it there by hand`);
117
+ else if (c.kind === "absent" && canonical)
118
+ report.plan.push(`add .claude/${name} as a relative symlink to .agents/${name}`);
119
+ else if (c.kind === "file")
120
+ report.blockers.push(`.claude/${name} is a file, not a directory: look at it by hand`);
121
+ }
122
+ if (report.blockers.length > 0)
123
+ report.verdict = "needs_hand_merge";
124
+ else if (report.plan.length > 0)
125
+ report.verdict = "convertible";
126
+ return report;
127
+ }
128
+ function isDir(p) {
129
+ try {
130
+ return statSync(p).isDirectory();
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ }
136
+ const THIN_CLAUDE_MD = "# CLAUDE.md\n\nAll project context for any coding agent is in AGENTS.md, imported below. Only Claude-specific notes belong in this file.\n\n@AGENTS.md\n";
137
+ /** Perform a convertible plan in the working tree. Refuses when anything needs a hand merge. */
138
+ export function applyPlan(root, before) {
139
+ if (before.verdict === "needs_hand_merge")
140
+ throw new UsageError(`nothing applied: ${before.blockers.join("; ")}`);
141
+ const done = [];
142
+ const agentsPath = join(root, "AGENTS.md");
143
+ const claudePath = join(root, "CLAUDE.md");
144
+ if (before.claudeMd.present && !before.claudeMd.importsAgentsMd) {
145
+ const claudeText = readFileSync(claudePath, "utf8");
146
+ const existing = existsSync(agentsPath) ? readFileSync(agentsPath, "utf8").replace(/\s+$/, "") : "";
147
+ const merged = existing === "" ? claudeText.replace(/\s+$/, "") + "\n" : `${existing}\n\n${claudeText.replace(/\s+$/, "")}\n`;
148
+ writeFileSync(agentsPath, merged);
149
+ writeFileSync(claudePath, THIN_CLAUDE_MD);
150
+ done.push(before.agentsMd.present ? "appended CLAUDE.md's content to AGENTS.md; CLAUDE.md now imports it" : "created AGENTS.md from CLAUDE.md; CLAUDE.md now imports it");
151
+ }
152
+ else if (!before.agentsMd.present && !before.claudeMd.present) {
153
+ writeFileSync(agentsPath, withBlock(null));
154
+ done.push("created AGENTS.md holding the Catalyst block");
155
+ }
156
+ for (const name of ["skills", "rules"]) {
157
+ const c = before.claudeDir[name];
158
+ const canonicalPath = join(root, ".agents", name);
159
+ const claudeLink = join(root, ".claude", name);
160
+ if (c.kind === "dir" && !before.agentsDir[name]) {
161
+ mkdirSync(join(root, ".agents"), { recursive: true });
162
+ renameSync(claudeLink, canonicalPath);
163
+ symlinkSync(relative(dirname(claudeLink), canonicalPath), claudeLink, "dir");
164
+ done.push(`moved .claude/${name} to .agents/${name} and left a relative symlink`);
165
+ }
166
+ else if (c.kind === "absent" && before.agentsDir[name]) {
167
+ mkdirSync(join(root, ".claude"), { recursive: true });
168
+ symlinkSync(relative(dirname(claudeLink), canonicalPath), claudeLink, "dir");
169
+ done.push(`added .claude/${name} as a relative symlink to .agents/${name}`);
170
+ }
171
+ }
172
+ return done;
173
+ }
174
+ /** The lightweight check a customer can run in CI: node only, no dependencies, exit 1 on a finding. */
175
+ export const AGENTS_MD_CHECK_SCRIPT = `#!/usr/bin/env node
176
+ // agents-md-check.mjs — keeps this repository's agent setup portable. Run it in CI:
177
+ // node scripts/agents-md-check.mjs
178
+ // It fails when CLAUDE.md stops importing AGENTS.md, when .claude/skills or .claude/rules stops being
179
+ // a relative symlink into .agents/, when AGENTS.md outgrows its budget, or when a repository path
180
+ // AGENTS.md cites no longer exists. Budgets: AGENTS_MD_MAX_LINES and AGENTS_MD_MAX_BYTES (env).
181
+ import { existsSync, lstatSync, readFileSync, readlinkSync } from "node:fs";
182
+ import { dirname, resolve } from "node:path";
183
+
184
+ const root = process.cwd();
185
+ const maxLines = Number(process.env.AGENTS_MD_MAX_LINES ?? 120);
186
+ const maxBytes = Number(process.env.AGENTS_MD_MAX_BYTES ?? 16 * 1024);
187
+ const findings = [];
188
+ const agents = existsSync("AGENTS.md") ? readFileSync("AGENTS.md", "utf8") : null;
189
+ if (agents === null) findings.push("AGENTS.md is missing");
190
+ else {
191
+ const lines = agents.replace(/\\n$/, "").split("\\n");
192
+ if (lines.length > maxLines) findings.push(\`AGENTS.md is \${lines.length} lines (budget \${maxLines})\`);
193
+ if (Buffer.byteLength(agents) > maxBytes) findings.push(\`AGENTS.md is \${Buffer.byteLength(agents)} bytes (budget \${maxBytes})\`);
194
+ for (const m of agents.matchAll(/\`([\\w.-]+(?:\\/[\\w.-]+)+)\`/g)) {
195
+ const p = m[1];
196
+ if (!existsSync(resolve(root, p))) findings.push(\`AGENTS.md cites \${p}, which does not exist\`);
197
+ }
198
+ }
199
+ if (existsSync("CLAUDE.md")) {
200
+ const n = readFileSync("CLAUDE.md", "utf8").split("\\n").filter((l) => l.trim() === "@AGENTS.md").length;
201
+ if (n !== 1) findings.push(\`CLAUDE.md must import AGENTS.md on exactly one line reading @AGENTS.md (found \${n})\`);
202
+ }
203
+ for (const name of ["skills", "rules"]) {
204
+ const link = \`.claude/\${name}\`;
205
+ const canonical = \`.agents/\${name}\`;
206
+ if (!existsSync(canonical) && !existsSync(link)) continue;
207
+ let st;
208
+ try { st = lstatSync(link); } catch { findings.push(\`\${link} is missing; make it a relative symlink to \${canonical}\`); continue; }
209
+ if (!st.isSymbolicLink()) { findings.push(\`\${link} is a real \${st.isDirectory() ? "directory" : "file"}; make \${canonical} canonical and \${link} a relative symlink\`); continue; }
210
+ const target = readlinkSync(link);
211
+ if (target.startsWith("/")) findings.push(\`\${link} is an absolute symlink (\${target}); make it relative\`);
212
+ if (resolve(dirname(link), target) !== resolve(root, canonical)) findings.push(\`\${link} points at \${target}, not \${canonical}\`);
213
+ }
214
+ for (const f of findings) console.error(\`agents-md-check: \${f}\`);
215
+ if (findings.length > 0) process.exit(1);
216
+ console.log("agents-md-check: portable");
217
+ `;
218
+ const describeLink = (s) => (s.kind === "symlink" ? `symlink → ${s.target}${s.resolvesToCanonical ? "" : " (not the canonical directory)"}` : s.kind === "dir" ? "real directory" : s.kind === "file" ? "a file" : "absent");
219
+ export function reportLines(r) {
220
+ const lines = [
221
+ `repository: ${r.path}`,
222
+ `AGENTS.md: ${r.agentsMd.present ? `${r.agentsMd.lines} lines, ${r.agentsMd.bytes} bytes; Catalyst block ${r.agentsMd.block}` : "absent"}`,
223
+ `CLAUDE.md: ${r.claudeMd.present ? (r.claudeMd.importsAgentsMd ? `imports AGENTS.md${r.claudeMd.otherLines ? ` plus ${r.claudeMd.otherLines} lines of Claude-only notes` : ""}` : `${r.claudeMd.otherLines} lines of its own guidance, no @AGENTS.md import`) : "absent"}`,
224
+ `.agents/skills: ${r.agentsDir.skills ? "present" : "absent"}; .claude/skills: ${describeLink(r.claudeDir.skills)}`,
225
+ `.agents/rules: ${r.agentsDir.rules ? "present" : "absent"}; .claude/rules: ${describeLink(r.claudeDir.rules)}`,
226
+ ];
227
+ if (r.others.length > 0)
228
+ lines.push(`also present: ${r.others.join(", ")}`);
229
+ lines.push(`verdict: ${r.verdict === "portable" ? "portable (AGENTS.md canonical, Claude files import or link to it)" : r.verdict === "convertible" ? "convertible; --apply performs this plan in the working tree:" : "needs a hand merge before --apply:"}`);
230
+ for (const p of r.plan)
231
+ lines.push(` - ${p}`);
232
+ for (const b of r.blockers)
233
+ lines.push(` ⛔ ${b}`);
234
+ if (r.agentsMd.block !== "current")
235
+ lines.push(` - the Catalyst block is ${r.agentsMd.block}: catalyst repo agents-block ${r.path} --write`);
236
+ return lines;
237
+ }
238
+ function checkoutRoot(args, sub) {
239
+ const [, path, ...extra] = positionals(args);
240
+ if (!path)
241
+ throw new UsageError(`repo ${sub} needs the checkout's path`);
242
+ if (extra.length > 0)
243
+ throw new UsageError(`repo ${sub} takes one path`);
244
+ const root = resolve(path);
245
+ if (!isDir(root))
246
+ throw new UsageError(`${path} is not a directory on this machine`);
247
+ return root;
248
+ }
249
+ export async function cmdRepo(args, ctx) {
250
+ const [sub] = positionals(args);
251
+ if (sub !== "agents-block" && sub !== "agent-setup")
252
+ throw new UsageError("repo needs agents-block <path> [--write] or agent-setup <path> [--apply] [--with-check]");
253
+ const root = checkoutRoot(args, sub);
254
+ const emit = (body, lines) => { if (args.json)
255
+ ctx.stdout(JSON.stringify(body));
256
+ else
257
+ for (const l of lines)
258
+ ctx.stdout(l); };
259
+ if (sub === "agents-block") {
260
+ if (flagBool(args, "apply") || flagBool(args, "with-check"))
261
+ throw new UsageError("--apply and --with-check belong to repo agent-setup");
262
+ const file = join(root, "AGENTS.md");
263
+ const before = existsSync(file) ? readFileSync(file, "utf8") : null;
264
+ const state = blockState(before);
265
+ if (!flagBool(args, "write")) {
266
+ const hint = state === "current" ? "nothing to do" : `run with --write to ${state === "absent" ? "create AGENTS.md with it" : state === "missing" ? "append it" : "bring it up to date"} (in the working tree; commit it on a branch and open a pull request)`;
267
+ emit({ path: root, agentsMd: before !== null, block: state, changed: false }, [`AGENTS.md: Catalyst block ${state} — ${hint}`]);
268
+ return state === "current" ? 0 : 1;
269
+ }
270
+ const after = withBlock(before);
271
+ const changed = after !== before;
272
+ if (changed)
273
+ writeFileSync(file, after);
274
+ emit({ path: root, agentsMd: true, block: "current", changed, was: state }, [
275
+ changed ? `AGENTS.md: Catalyst block ${state === "absent" ? "written to a new AGENTS.md" : state === "missing" ? "appended" : "updated in place"}; commit it on a branch and open a pull request` : "AGENTS.md: Catalyst block already current; nothing changed",
276
+ ]);
277
+ return 0;
278
+ }
279
+ if (flagBool(args, "write"))
280
+ throw new UsageError("--write belongs to repo agents-block");
281
+ const before = inspectRepo(root);
282
+ const applied = [];
283
+ if (flagBool(args, "apply"))
284
+ applied.push(...applyPlan(root, before));
285
+ if (flagBool(args, "with-check")) {
286
+ const dir = join(root, "scripts");
287
+ mkdirSync(dir, { recursive: true });
288
+ const target = join(dir, "agents-md-check.mjs");
289
+ const same = existsSync(target) && readFileSync(target, "utf8") === AGENTS_MD_CHECK_SCRIPT;
290
+ if (!same)
291
+ writeFileSync(target, AGENTS_MD_CHECK_SCRIPT, { mode: 0o755 });
292
+ applied.push(same ? "scripts/agents-md-check.mjs already current" : "wrote scripts/agents-md-check.mjs (run it in CI: node scripts/agents-md-check.mjs)");
293
+ }
294
+ const after = applied.length > 0 ? inspectRepo(root) : before;
295
+ emit({ ...after, applied }, [...(applied.length ? ["applied:", ...applied.map((a) => ` - ${a}`)] : []), ...reportLines(after)]);
296
+ return after.verdict === "portable" && after.agentsMd.block === "current" ? 0 : 1;
297
+ }