dev-loops 0.2.5 → 0.2.7

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 (70) hide show
  1. package/.claude/.claude-plugin/plugin.json +9 -2
  2. package/.claude/agents/dev-loop.md +2 -1
  3. package/.claude/hooks/_bash-command-classify.mjs +164 -0
  4. package/.claude/hooks/_hook-decisions.mjs +130 -0
  5. package/.claude/hooks/_hook-io.mjs +1 -1
  6. package/.claude/hooks/_run-context.mjs +179 -0
  7. package/.claude/hooks/post-tool-use-merge.mjs +1 -1
  8. package/.claude/hooks/pre-tool-use-bash-gate.mjs +2 -2
  9. package/.claude/hooks/pre-tool-use-write-guard.mjs +1 -1
  10. package/.claude/skills/dev-loop/SKILL.md +5 -5
  11. package/.claude/skills/docs/merge-preconditions.md +15 -0
  12. package/.claude/skills/docs/pr-lifecycle-contract.md +1 -0
  13. package/CHANGELOG.md +52 -0
  14. package/agents/dev-loop.agent.md +5 -1
  15. package/cli/index.mjs +3 -1
  16. package/package.json +2 -2
  17. package/scripts/_cli-primitives.mjs +2 -0
  18. package/scripts/claude/generate-claude-assets.mjs +71 -3
  19. package/scripts/docs/validate-links.mjs +20 -11
  20. package/scripts/github/capture-review-threads.mjs +32 -14
  21. package/scripts/github/detect-checkpoint-evidence.mjs +28 -11
  22. package/scripts/github/detect-linked-issue-pr.mjs +22 -10
  23. package/scripts/github/manage-sub-issues.mjs +37 -16
  24. package/scripts/github/probe-copilot-review.mjs +24 -12
  25. package/scripts/github/ready-for-review.mjs +22 -10
  26. package/scripts/github/reconcile-draft-gate.mjs +22 -10
  27. package/scripts/github/reply-resolve-review-threads.mjs +34 -15
  28. package/scripts/github/request-copilot-review.mjs +28 -11
  29. package/scripts/github/resolve-tracker-local-spec.mjs +29 -12
  30. package/scripts/github/stage-reviewer-draft.mjs +32 -14
  31. package/scripts/github/upsert-checkpoint-verdict.mjs +49 -26
  32. package/scripts/github/write-gate-findings-log.mjs +41 -20
  33. package/scripts/loop/_loop-pr-aggregation.mjs +45 -0
  34. package/scripts/loop/build-handoff-envelope.mjs +32 -14
  35. package/scripts/loop/conductor-monitor.mjs +26 -47
  36. package/scripts/loop/conductor.mjs +31 -12
  37. package/scripts/loop/copilot-pr-handoff.mjs +31 -14
  38. package/scripts/loop/debt-remediate.mjs +28 -11
  39. package/scripts/loop/detect-copilot-loop-state.mjs +29 -12
  40. package/scripts/loop/detect-copilot-session-activity.mjs +29 -12
  41. package/scripts/loop/detect-initial-copilot-pr-state.mjs +26 -10
  42. package/scripts/loop/detect-internal-only-pr.mjs +31 -13
  43. package/scripts/loop/detect-issue-refinement-artifact.mjs +29 -12
  44. package/scripts/loop/detect-pr-gate-coordination-state.mjs +28 -11
  45. package/scripts/loop/detect-reviewer-loop-state.mjs +35 -16
  46. package/scripts/loop/detect-stale-runner.mjs +32 -14
  47. package/scripts/loop/detect-tracker-pr-state.mjs +23 -8
  48. package/scripts/loop/info.mjs +28 -10
  49. package/scripts/loop/inspect-run-viewer/cli.mjs +44 -21
  50. package/scripts/loop/inspect-run.mjs +35 -16
  51. package/scripts/loop/outer-loop.mjs +35 -16
  52. package/scripts/loop/pr-runner-coordination.mjs +31 -12
  53. package/scripts/loop/pre-commit-branch-guard.mjs +26 -9
  54. package/scripts/loop/pre-flight-gate.mjs +25 -9
  55. package/scripts/loop/pre-pr-ready-gate.mjs +24 -8
  56. package/scripts/loop/pre-push-main-guard.mjs +19 -5
  57. package/scripts/loop/pre-write-remote-freshness-guard.mjs +23 -7
  58. package/scripts/loop/resolve-dev-loop-startup.mjs +29 -12
  59. package/scripts/loop/run-conductor-cycle.mjs +25 -47
  60. package/scripts/loop/run-refinement-audit.mjs +44 -22
  61. package/scripts/loop/run-watch-cycle.mjs +28 -12
  62. package/scripts/loop/steer-loop.mjs +122 -62
  63. package/scripts/loop/watch-initial-copilot-pr.mjs +28 -12
  64. package/scripts/projects/archive-done-items.mjs +410 -0
  65. package/scripts/projects/reorder-queue-item.mjs +334 -76
  66. package/scripts/refine/_refine-helpers.mjs +21 -9
  67. package/scripts/refine/verify.mjs +31 -13
  68. package/skills/dev-loop/SKILL.md +9 -5
  69. package/skills/docs/merge-preconditions.md +15 -0
  70. package/skills/docs/pr-lifecycle-contract.md +1 -0
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { setTimeout as delay } from "node:timers/promises";
3
3
  import { spawn } from "node:child_process";
4
+ import { parseArgs } from "node:util";
4
5
  import { buildParseError, formatCliError, isDirectCliRun } from "../_core-helpers.mjs";
5
- import { parseIssueNumber, requireOptionValue } from "../_cli-primitives.mjs";
6
+ import { parseIssueNumber, requireTokenValue } from "../_cli-primitives.mjs";
6
7
  import { parseRepoSlug } from "@dev-loops/core/github/repo-slug";
7
8
  import { detectInitialCopilotPrState, LINKED_PR_STATE } from "./detect-initial-copilot-pr-state.mjs";
8
9
  import { enforcePersistentInternalWaitTimeout } from "@dev-loops/core/loop/timeout-policy";
@@ -94,7 +95,6 @@ export async function watchCopilotRunUntilComplete(
94
95
  });
95
96
  }
96
97
  export function parseWatchInitialCopilotPrCliArgs(argv) {
97
- const args = [...argv];
98
98
  const options = {
99
99
  help: false,
100
100
  repo: undefined,
@@ -102,24 +102,40 @@ export function parseWatchInitialCopilotPrCliArgs(argv) {
102
102
  pollIntervalMs: DEFAULT_POLL_INTERVAL_MS,
103
103
  timeoutMs: COPILOT_FIRST_DURABLE_WAIT_TIMEOUT_MS,
104
104
  };
105
- while (args.length > 0) {
106
- const token = args.shift();
107
- if (token === "--help" || token === "-h") {
105
+ const { tokens } = parseArgs({
106
+ args: [...argv],
107
+ options: {
108
+ help: { type: "boolean", short: "h" },
109
+ repo: { type: "string" },
110
+ issue: { type: "string" },
111
+ },
112
+ allowPositionals: true,
113
+ strict: false,
114
+ tokens: true,
115
+ });
116
+ for (const token of tokens) {
117
+ if (token.kind === "positional") {
118
+ throw parseError(`Unknown argument: ${token.value}`);
119
+ }
120
+ if (token.kind !== "option") {
121
+ continue;
122
+ }
123
+ if (token.name === "help") {
108
124
  options.help = true;
109
125
  return options;
110
126
  }
111
- if (REMOVED_FLAGS.has(token)) {
112
- rejectRemovedFlag(token);
127
+ if (REMOVED_FLAGS.has(token.rawName)) {
128
+ rejectRemovedFlag(token.rawName);
113
129
  }
114
- if (token === "--repo") {
115
- options.repo = requireOptionValue(args, "--repo", parseError).trim();
130
+ if (token.name === "repo") {
131
+ options.repo = requireTokenValue(token, parseError).trim();
116
132
  continue;
117
133
  }
118
- if (token === "--issue") {
119
- options.issue = parseIssueNumber(requireOptionValue(args, "--issue", parseError), parseError);
134
+ if (token.name === "issue") {
135
+ options.issue = parseIssueNumber(requireTokenValue(token, parseError), parseError);
120
136
  continue;
121
137
  }
122
- throw parseError(`Unknown argument: ${token}`);
138
+ throw parseError(`Unknown argument: ${token.rawName}`);
123
139
  }
124
140
  if (options.repo === undefined || options.issue === undefined) {
125
141
  throw parseError("watch-initial-copilot-pr requires both --repo <owner/name> and --issue <number>");
@@ -0,0 +1,410 @@
1
+ #!/usr/bin/env node
2
+ import { formatCliError, isDirectCliRun, parseJsonText } from "../_core-helpers.mjs";
3
+ import { runChild as _runChild } from "../_cli-primitives.mjs";
4
+
5
+ const USAGE = `Usage: dev-loops project archive-done --repo <owner/name> --project <number|id> [--older-than <duration>] [--dry-run]
6
+
7
+ Archive GitHub Projects V2 items whose issue/PR has been closed for at least the
8
+ given duration. Operator-triggered (no webhooks). Uses archiveProjectV2Item.
9
+
10
+ Options:
11
+ --repo <owner/name> Required. Repository to scope the project search.
12
+ --project <number|id> Required. Project number (integer) or node ID.
13
+ --older-than <duration> Closed-for threshold. Format: <n><unit> where unit is
14
+ h (hours), d (days), or w (weeks). Default: 30d.
15
+ --dry-run Print the intended archive mutation(s) without executing.
16
+ --help, -h Show this help.
17
+
18
+ Output (stdout):
19
+ JSON: { ok: true, olderThan, scanned, archivable, archived: [{ itemId, issueNumber, prNumber, closedAt }] }
20
+ dry-run: { ok: true, dryRun: true, olderThan, scanned, archivable, mutations: [{ query, variables }] }
21
+ (scanned = all repo board items; archivable = items selected for archival)
22
+
23
+ Exit codes:
24
+ 0 — success
25
+ 1 — usage or argument error
26
+ 2 — GitHub API error
27
+ 3 — project not found
28
+ `.trim();
29
+
30
+ const VALID_ARGS = new Set(["--repo", "--project", "--older-than", "--dry-run", "--help", "-h"]);
31
+
32
+ function parseArgs(argv) {
33
+ const args = {};
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const arg = argv[i];
36
+ if (!VALID_ARGS.has(arg) && arg.startsWith("-")) {
37
+ throw Object.assign(new Error(`Unknown flag: ${arg}`), { code: "INVALID_ARGS", usage: USAGE });
38
+ }
39
+ if (arg === "--repo") {
40
+ if (i + 1 >= argv.length || argv[i + 1].startsWith("-")) {
41
+ throw Object.assign(new Error("--repo requires a value (owner/name)"), { code: "INVALID_REPO" });
42
+ }
43
+ args.repo = argv[++i];
44
+ } else if (arg === "--project") {
45
+ if (i + 1 >= argv.length || argv[i + 1].startsWith("-")) {
46
+ throw Object.assign(new Error("--project requires a value (number or node ID)"), { code: "INVALID_PROJECT" });
47
+ }
48
+ args.project = argv[++i];
49
+ } else if (arg === "--older-than") {
50
+ if (i + 1 >= argv.length || argv[i + 1].startsWith("-")) {
51
+ throw Object.assign(new Error("--older-than requires a value (e.g. 30d)"), { code: "INVALID_DURATION" });
52
+ }
53
+ args.olderThan = argv[++i];
54
+ } else if (arg === "--dry-run") {
55
+ args.dryRun = true;
56
+ } else if (arg === "--help" || arg === "-h") {
57
+ args.help = true;
58
+ } else {
59
+ throw Object.assign(new Error(`Unexpected argument: ${arg}`), { code: "INVALID_ARGS", usage: USAGE });
60
+ }
61
+ }
62
+ return args;
63
+ }
64
+
65
+ // ── Validation ───────────────────────────────────────────────────────────
66
+
67
+ const OWNER_RE = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/;
68
+ const REPO_NAME_RE = /^[a-zA-Z0-9](?:[a-zA-Z0-9_.-]*[a-zA-Z0-9])?$/;
69
+ const GLOBAL_NODE_ID_RE = /^[A-Za-z0-9_]+$/;
70
+
71
+ function validateRepo(repo) {
72
+ if (!repo || typeof repo !== "string") {
73
+ throw Object.assign(new Error("--repo is required"), { code: "INVALID_REPO" });
74
+ }
75
+ const slashIdx = repo.indexOf("/");
76
+ if (slashIdx === -1) {
77
+ throw Object.assign(new Error(`--repo must be exactly owner/name, got "${repo}"`), { code: "INVALID_REPO" });
78
+ }
79
+ const owner = repo.slice(0, slashIdx);
80
+ const name = repo.slice(slashIdx + 1);
81
+ if (!owner || !name || !OWNER_RE.test(owner) || !REPO_NAME_RE.test(name)) {
82
+ throw Object.assign(new Error(`--repo must be exactly owner/name, got "${repo}"`), { code: "INVALID_REPO" });
83
+ }
84
+ return repo;
85
+ }
86
+
87
+ function parseProjectRef(raw) {
88
+ if (!raw || typeof raw !== "string" || raw.trim().length === 0) {
89
+ throw Object.assign(new Error("--project is required"), { code: "INVALID_PROJECT" });
90
+ }
91
+ const trimmed = raw.trim();
92
+ const asNum = Number(trimmed);
93
+ if (Number.isInteger(asNum) && asNum > 0 && String(asNum) === trimmed) {
94
+ return { kind: "number", value: asNum };
95
+ }
96
+ if (GLOBAL_NODE_ID_RE.test(trimmed) && trimmed !== "0") {
97
+ return { kind: "id", value: trimmed };
98
+ }
99
+ throw Object.assign(new Error(`--project must be a positive integer or a node ID, got "${raw}"`), { code: "INVALID_PROJECT" });
100
+ }
101
+
102
+ const DURATION_RE = /^(\d+)(h|d|w)$/;
103
+ const UNIT_MS = {
104
+ h: 60 * 60 * 1000,
105
+ d: 24 * 60 * 60 * 1000,
106
+ w: 7 * 24 * 60 * 60 * 1000,
107
+ };
108
+
109
+ function parseDuration(raw) {
110
+ if (!raw || typeof raw !== "string") {
111
+ throw Object.assign(new Error(`--older-than must be <n>(h|d|w), got "${raw}"`), { code: "INVALID_DURATION" });
112
+ }
113
+ const m = DURATION_RE.exec(raw.trim());
114
+ if (!m) {
115
+ throw Object.assign(new Error(`--older-than must be <n>(h|d|w), got "${raw}"`), { code: "INVALID_DURATION" });
116
+ }
117
+ const n = Number(m[1]);
118
+ if (!Number.isInteger(n) || n <= 0) {
119
+ throw Object.assign(new Error(`--older-than must be a positive amount, got "${raw}"`), { code: "INVALID_DURATION" });
120
+ }
121
+ return n * UNIT_MS[m[2]];
122
+ }
123
+
124
+ // ── API helpers ──────────────────────────────────────────────────────────
125
+
126
+ async function ghGraphql(query, vars, env, runChild = _runChild) {
127
+ const fieldArgs = [];
128
+ for (const [key, value] of Object.entries(vars)) {
129
+ fieldArgs.push("--field", `${key}=${value}`);
130
+ }
131
+ const result = await runChild("gh", ["api", "graphql", "--field", `query=${query}`, ...fieldArgs], env);
132
+ if (result.code !== 0) {
133
+ const detail = result.stderr.trim() || `exit code ${result.code}`;
134
+ throw Object.assign(new Error(`gh api graphql failed: ${detail}`), { code: "GH_API_ERROR" });
135
+ }
136
+ const payload = parseJsonText(result.stdout);
137
+ if (payload.errors && payload.errors.length > 0) {
138
+ throw Object.assign(
139
+ new Error(`GraphQL errors: ${payload.errors.map((e) => e.message).join("; ")}`),
140
+ { code: "GRAPHQL_ERROR" },
141
+ );
142
+ }
143
+ return payload;
144
+ }
145
+
146
+ // ── GraphQL fragments ────────────────────────────────────────────────────
147
+
148
+ const GET_USER_ID = ["query($login:String!) {", " user(login:$login) { id }", "}"].join("\n");
149
+ const GET_ORG_ID = ["query($login:String!) {", " organization(login:$login) { id }", "}"].join("\n");
150
+
151
+ const LIST_USER_PROJECTS = [
152
+ "query($login:String!, $after:String) {",
153
+ " user(login:$login) {",
154
+ " projectsV2(first:50, after:$after) {",
155
+ " pageInfo { hasNextPage endCursor }",
156
+ " nodes { id number title url }",
157
+ " }",
158
+ " }",
159
+ "}",
160
+ ].join("\n");
161
+
162
+ const LIST_ORG_PROJECTS = [
163
+ "query($login:String!, $after:String) {",
164
+ " organization(login:$login) {",
165
+ " projectsV2(first:50, after:$after) {",
166
+ " pageInfo { hasNextPage endCursor }",
167
+ " nodes { id number title url }",
168
+ " }",
169
+ " }",
170
+ "}",
171
+ ].join("\n");
172
+
173
+ const GET_PROJECT_ITEMS = [
174
+ "query($projectId:ID!, $after:String) {",
175
+ " node(id:$projectId) {",
176
+ " ... on ProjectV2 {",
177
+ " items(first:50, after:$after, orderBy:{field:POSITION, direction:ASC}) {",
178
+ " pageInfo { hasNextPage endCursor }",
179
+ " nodes {",
180
+ " id",
181
+ " isArchived",
182
+ " fieldValues(first:20) {",
183
+ " nodes {",
184
+ " ... on ProjectV2ItemFieldSingleSelectValue {",
185
+ " field { ... on ProjectV2SingleSelectField { id name } }",
186
+ " name",
187
+ " }",
188
+ " }",
189
+ " }",
190
+ " content {",
191
+ " ... on Issue { __typename number closed closedAt repository { nameWithOwner } }",
192
+ " ... on PullRequest { __typename number closed closedAt repository { nameWithOwner } }",
193
+ " }",
194
+ " }",
195
+ " }",
196
+ " }",
197
+ " }",
198
+ "}",
199
+ ].join("\n");
200
+
201
+ const ARCHIVE_ITEM = [
202
+ "mutation($projectId:ID!, $itemId:ID!) {",
203
+ " archiveProjectV2Item(input:{projectId:$projectId, itemId:$itemId}) {",
204
+ " item { id }",
205
+ " }",
206
+ "}",
207
+ ].join("\n");
208
+
209
+ // ── Owner / project resolution ─────────────────────────────────────────────
210
+
211
+ async function resolveOwner(login, env, runChild) {
212
+ const userPayload = await ghGraphql(GET_USER_ID, { login }, env, runChild);
213
+ if (userPayload?.data?.user?.id) return { id: userPayload.data.user.id, kind: "user" };
214
+ const orgPayload = await ghGraphql(GET_ORG_ID, { login }, env, runChild);
215
+ if (orgPayload?.data?.organization?.id) return { id: orgPayload.data.organization.id, kind: "org" };
216
+ throw Object.assign(new Error(`Could not resolve owner ID for "${login}"`), { code: "NO_USER_ID" });
217
+ }
218
+
219
+ async function listAllProjects(login, kind, env, runChild) {
220
+ const query = kind === "org" ? LIST_ORG_PROJECTS : LIST_USER_PROJECTS;
221
+ const projects = [];
222
+ let after = null;
223
+ while (true) {
224
+ const vars = { login };
225
+ if (after) vars.after = after;
226
+ const payload = await ghGraphql(query, vars, env, runChild);
227
+ const connection = kind === "org" ? payload?.data?.organization?.projectsV2 : payload?.data?.user?.projectsV2;
228
+ const nodes = connection?.nodes ?? [];
229
+ projects.push(...nodes);
230
+ const pageInfo = connection?.pageInfo ?? {};
231
+ if (!pageInfo.hasNextPage) break;
232
+ if (!pageInfo.endCursor) {
233
+ throw Object.assign(new Error("Invalid projects list payload: hasNextPage true but endCursor missing"), { code: "GH_API_ERROR" });
234
+ }
235
+ after = pageInfo.endCursor;
236
+ }
237
+ return projects;
238
+ }
239
+
240
+ async function fetchAllItems(projectId, env, runChild) {
241
+ const all = [];
242
+ let after = null;
243
+ while (true) {
244
+ const vars = { projectId };
245
+ if (after) vars.after = after;
246
+ const payload = await ghGraphql(GET_PROJECT_ITEMS, vars, env, runChild);
247
+ const connection = payload?.data?.node?.items;
248
+ const nodes = connection?.nodes ?? [];
249
+ all.push(...nodes);
250
+ const pageInfo = connection?.pageInfo ?? {};
251
+ if (!pageInfo.hasNextPage) break;
252
+ if (!pageInfo.endCursor) {
253
+ throw Object.assign(new Error("Invalid items payload: hasNextPage true but endCursor missing"), { code: "GH_API_ERROR" });
254
+ }
255
+ after = pageInfo.endCursor;
256
+ }
257
+ return all;
258
+ }
259
+
260
+ function statusOf(node) {
261
+ const fvs = node?.fieldValues?.nodes ?? [];
262
+ for (const fv of fvs) {
263
+ if (fv && fv.field && fv.field.name === "Status") return fv.name;
264
+ }
265
+ return null;
266
+ }
267
+
268
+ // Normalize a raw GraphQL item node into the shape selectArchivable expects.
269
+ function normalizeItem(node) {
270
+ return {
271
+ id: node.id,
272
+ isArchived: Boolean(node.isArchived),
273
+ status: statusOf(node),
274
+ content: node.content
275
+ ? {
276
+ __typename: node.content.__typename,
277
+ number: node.content.number,
278
+ closed: Boolean(node.content.closed),
279
+ closedAt: node.content.closedAt ?? null,
280
+ repository: node.content.repository,
281
+ }
282
+ : null,
283
+ };
284
+ }
285
+
286
+ // ── Selection logic (pure) ────────────────────────────────────────────────
287
+
288
+ // Select items whose issue/PR is closed and has been closed for >= olderThanMs.
289
+ function selectArchivable(items, { now, olderThanMs }) {
290
+ return items.filter((it) => {
291
+ if (it.isArchived) return false;
292
+ const c = it.content;
293
+ if (!c || !c.closed || !c.closedAt) return false;
294
+ const closedAtMs = Date.parse(c.closedAt);
295
+ if (Number.isNaN(closedAtMs)) return false;
296
+ return now - closedAtMs >= olderThanMs;
297
+ });
298
+ }
299
+
300
+ // ── Exit code classification ────────────────────────────────────────────
301
+
302
+ function classifyExitCode(err) {
303
+ if (err.code === "INVALID_REPO" || err.code === "INVALID_PROJECT" ||
304
+ err.code === "INVALID_DURATION" || err.code === "INVALID_ARGS") return 1;
305
+ if (err.code === "PROJECT_NOT_FOUND") return 3;
306
+ return 2;
307
+ }
308
+
309
+ // ── Main logic ──────────────────────────────────────────────────────────
310
+
311
+ async function main(args, { env = process.env, runChild } = {}) {
312
+ const child = runChild ?? _runChild;
313
+ const repo = validateRepo(args.repo);
314
+ const [owner] = repo.split("/");
315
+ const projectRef = parseProjectRef(args.project);
316
+ const olderThanRaw = args.olderThan ?? "30d";
317
+ const olderThanMs = parseDuration(olderThanRaw);
318
+ const now = args.now ?? Date.now();
319
+
320
+ const { kind: ownerKind } = await resolveOwner(owner, env, child);
321
+ const projects = await listAllProjects(owner, ownerKind, env, child);
322
+ const project = projectRef.kind === "id"
323
+ ? projects.find((p) => p.id === projectRef.value)
324
+ : projects.find((p) => p.number === projectRef.value);
325
+ if (!project) {
326
+ throw Object.assign(
327
+ new Error(`Project ${projectRef.kind === "id" ? `"${projectRef.value}"` : `number ${projectRef.value}`} not found under owner "${owner}"`),
328
+ { code: "PROJECT_NOT_FOUND" },
329
+ );
330
+ }
331
+
332
+ const rawItems = await fetchAllItems(project.id, env, child);
333
+ // Only consider items whose content belongs to the target repo (single-repo scope).
334
+ const repoItems = rawItems
335
+ .filter((n) => n.content && n.content.repository?.nameWithOwner === repo)
336
+ .map(normalizeItem);
337
+
338
+ const archivable = selectArchivable(repoItems, { now, olderThanMs });
339
+
340
+ const mutations = archivable.map((it) => ({
341
+ query: ARCHIVE_ITEM,
342
+ variables: { projectId: project.id, itemId: it.id },
343
+ }));
344
+
345
+ if (args.dryRun) {
346
+ return {
347
+ ok: true,
348
+ dryRun: true,
349
+ olderThan: olderThanRaw,
350
+ scanned: repoItems.length,
351
+ archivable: archivable.length,
352
+ mutations,
353
+ };
354
+ }
355
+
356
+ const archived = [];
357
+ for (const it of archivable) {
358
+ const payload = await ghGraphql(ARCHIVE_ITEM, { projectId: project.id, itemId: it.id }, env, child);
359
+ if (!payload?.data?.archiveProjectV2Item?.item) {
360
+ throw Object.assign(new Error(`Failed to archive item ${it.id}`), { code: "MUTATION_FAILED" });
361
+ }
362
+ archived.push({
363
+ itemId: it.id,
364
+ issueNumber: it.content.__typename === "Issue" ? it.content.number : null,
365
+ prNumber: it.content.__typename === "PullRequest" ? it.content.number : null,
366
+ closedAt: it.content.closedAt,
367
+ });
368
+ }
369
+
370
+ return {
371
+ ok: true,
372
+ olderThan: olderThanRaw,
373
+ scanned: repoItems.length,
374
+ archivable: archivable.length,
375
+ archived,
376
+ };
377
+ }
378
+
379
+ // ── CLI entrypoint ──────────────────────────────────────────────────────
380
+
381
+ async function runCli(argv, { stdout = process.stdout, stderr = process.stderr, env = process.env } = {}) {
382
+ let args;
383
+ try {
384
+ args = parseArgs(argv);
385
+ } catch (err) {
386
+ stderr.write(`${formatCliError(err)}\n`);
387
+ process.exitCode = 1;
388
+ return;
389
+ }
390
+ if (args.help) {
391
+ stdout.write(USAGE);
392
+ return;
393
+ }
394
+ try {
395
+ const result = await main(args, { env });
396
+ stdout.write(JSON.stringify(result) + "\n");
397
+ } catch (err) {
398
+ stderr.write(JSON.stringify({ ok: false, error: err.message, code: err.code ?? "UNKNOWN" }) + "\n");
399
+ process.exitCode = classifyExitCode(err);
400
+ }
401
+ }
402
+
403
+ if (isDirectCliRun(import.meta.url)) {
404
+ runCli(process.argv.slice(2)).catch((error) => {
405
+ process.stderr.write(JSON.stringify({ ok: false, error: error.message, code: error.code ?? "UNKNOWN" }) + "\n");
406
+ process.exitCode = 2;
407
+ });
408
+ }
409
+
410
+ export { main, parseDuration, selectArchivable };