@installagent/sdk 0.10.0 → 0.12.0

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.
@@ -0,0 +1,328 @@
1
+ // `ia roadmap-migrate` — move each client's docs/06-roadmap.md into Linear, once.
2
+ //
3
+ // The roadmap file is retired (2026-11-08): Linear owns the order of work, and
4
+ // the client portal reads Now / Next / Later from it. This operation reads the
5
+ // file's "## Ranked list" table and, per row, says what Linear needs so it
6
+ // holds the same facts:
7
+ //
8
+ // Status this week / next / later → state type started / unstarted / backlog
9
+ // Status parked → label `parked` (any state; never shown)
10
+ // Status done → Done (checked only, never written)
11
+ // Tag VALUE / CLIENT ASK / BOTH → labels `value` / `client-ask` / both
12
+ // Client line → one `Client line: …` line in the description
13
+ //
14
+ // The dry run (the default) only reads. `apply` writes ONLY labels (it creates
15
+ // a missing `value` / `client-ask` / `parked` label once, then adds labels to
16
+ // issues) and descriptions (it appends a Client line when the issue has none).
17
+ // It never changes a state, a title, a priority or an assignee: a state that
18
+ // does not match the row is a report line for a person. It refuses a Client
19
+ // line with `$` (Linear is shared by all staff: no dollar amounts), a ticket
20
+ // id, or more than 140 characters. Angello runs `--apply`.
21
+ import { existsSync, readFileSync } from "node:fs";
22
+ import { join, resolve } from "node:path";
23
+ import { parseLinearProjectSlugId } from "./client-linear.js";
24
+ import { readManifestKey } from "./client-manifest.js";
25
+ import { findProjectBySlugId, LINEAR_API_TOKEN_ENV, linearRequest } from "./linear-project.js";
26
+ import { adhocReason, selectClientSlugs } from "./template-sync.js";
27
+ export const ROADMAP_SOURCES = ["docs/06-roadmap.md", "docs/archive/06-roadmap.md"];
28
+ export const CLIENT_LINE_MAX = 140;
29
+ export const ROADMAP_LABELS = ["value", "client-ask", "parked"];
30
+ const ISSUE_ID = /\bINS-\d+\b/g;
31
+ const TICKET_ID = /\b[A-Z][A-Z0-9]{1,9}-\d+\b/;
32
+ const HAS_CLIENT_LINE = /^\s*(?:[-*]\s+)?\**Client line:?\**\s*:?/im;
33
+ const PAGE_SIZE = 250;
34
+ const LABEL_COLORS = {
35
+ value: "#4CB782",
36
+ "client-ask": "#F2994A",
37
+ parked: "#9CA3AF",
38
+ };
39
+ /** The state types a row's status expects; parked accepts any state. */
40
+ const EXPECTED_STATE = {
41
+ done: ["completed"],
42
+ "this week": ["started"],
43
+ next: ["unstarted"],
44
+ later: ["backlog"],
45
+ parked: null,
46
+ };
47
+ const TAG_LABELS = {
48
+ VALUE: ["value"],
49
+ "CLIENT ASK": ["client-ask"],
50
+ BOTH: ["value", "client-ask"],
51
+ };
52
+ /** Split one markdown table row into trimmed cells (outer pipes dropped, `\|` kept as a pipe). */
53
+ function splitRow(line) {
54
+ const cells = [];
55
+ let cell = "";
56
+ for (let i = 0; i < line.length; i++) {
57
+ if (line[i] === "\\" && line[i + 1] === "|") {
58
+ cell += "|";
59
+ i += 1;
60
+ }
61
+ else if (line[i] === "|") {
62
+ cells.push(cell.trim());
63
+ cell = "";
64
+ }
65
+ else
66
+ cell += line[i];
67
+ }
68
+ cells.push(cell.trim());
69
+ if (cells[0] === "")
70
+ cells.shift();
71
+ if (cells[cells.length - 1] === "")
72
+ cells.pop();
73
+ return cells;
74
+ }
75
+ /** The rows of the roadmap's "## Ranked list" table. Fenced examples are skipped. */
76
+ export function parseRoadmapRows(md) {
77
+ const rows = [];
78
+ let inList = false;
79
+ let header = null;
80
+ let fenced = false;
81
+ for (const raw of md.split("\n")) {
82
+ const line = raw.trimEnd();
83
+ if (/^\s*```/.test(line))
84
+ fenced = !fenced;
85
+ if (fenced)
86
+ continue;
87
+ if (/^##\s/.test(line)) {
88
+ inList = /^##\s+Ranked list\b/i.test(line);
89
+ header = null;
90
+ continue;
91
+ }
92
+ if (!inList || !line.startsWith("|"))
93
+ continue;
94
+ const cells = splitRow(line);
95
+ if (!header) {
96
+ header = cells.map((c) => c.toLowerCase());
97
+ continue;
98
+ }
99
+ if (cells.every((c) => /^:?-{2,}:?$/.test(c)))
100
+ continue;
101
+ const col = (name) => header?.includes(name) ? (cells[header.indexOf(name)] ?? "") : "";
102
+ const work = col("work");
103
+ const ids = [...new Set([...work.matchAll(ISSUE_ID)].map((m) => m[0]))];
104
+ const others = [...new Set(cells.join(" ").match(ISSUE_ID) ?? [])].filter((id) => id !== ids[0]);
105
+ rows.push({
106
+ rank: col("#"),
107
+ work,
108
+ tag: col("tag").toUpperCase(),
109
+ status: col("status").toLowerCase(),
110
+ clientLine: col("client line"),
111
+ id: ids[0] ?? null,
112
+ alsoNamed: others,
113
+ });
114
+ }
115
+ return rows;
116
+ }
117
+ /** Why a row's Client line may not go into Linear, or null when it may. */
118
+ function refusal(line) {
119
+ if (line.includes("$"))
120
+ return "has a $ — no dollar amounts in Linear (shared by all staff)";
121
+ if (TICKET_ID.test(line))
122
+ return "names a ticket id — the client never sees ticket numbers";
123
+ if (line.length > CLIENT_LINE_MAX)
124
+ return `is ${line.length} characters; the limit is ${CLIENT_LINE_MAX}`;
125
+ return null;
126
+ }
127
+ const ISSUES_QUERY = `
128
+ query RoadmapMigrateIssues($project: String!, $projectId: ID!, $first: Int!, $after: String) {
129
+ project(id: $project) { teams { nodes { id key } } }
130
+ issues(filter: { project: { id: { eq: $projectId } } }, first: $first, after: $after) {
131
+ nodes { id identifier description state { type name } labels { nodes { id name } } }
132
+ pageInfo { hasNextPage endCursor }
133
+ }
134
+ }
135
+ `;
136
+ const LABELS_QUERY = `
137
+ query RoadmapMigrateLabels($filter: IssueLabelFilter!) {
138
+ issueLabels(filter: $filter, first: 250) { nodes { id name team { id } } }
139
+ }
140
+ `;
141
+ const LABEL_CREATE = `
142
+ mutation RoadmapMigrateLabelCreate($input: IssueLabelCreateInput!) {
143
+ issueLabelCreate(input: $input) { success issueLabel { id name } }
144
+ }
145
+ `;
146
+ const ISSUE_UPDATE = `
147
+ mutation RoadmapMigrateIssueUpdate($id: String!, $input: IssueUpdateInput!) {
148
+ issueUpdate(id: $id, input: $input) { success }
149
+ }
150
+ `;
151
+ async function projectIssues(request, projectId) {
152
+ const issues = [];
153
+ let teamIds = [];
154
+ let after = null;
155
+ for (let page = 0; page < 20; page++) {
156
+ const data = await request(ISSUES_QUERY, { project: projectId, projectId, first: PAGE_SIZE, after });
157
+ if (page === 0)
158
+ teamIds = data.project?.teams.nodes.map((t) => t.id) ?? [];
159
+ issues.push(...data.issues.nodes);
160
+ if (!data.issues.pageInfo.hasNextPage || !data.issues.pageInfo.endCursor)
161
+ break;
162
+ after = data.issues.pageInfo.endCursor;
163
+ }
164
+ return { issues, teamIds };
165
+ }
166
+ function planRow(row, issue) {
167
+ const plan = {
168
+ ...row,
169
+ linearState: null,
170
+ stateMatches: null,
171
+ labelsToAdd: [],
172
+ clientLineToAdd: null,
173
+ refused: null,
174
+ problem: null,
175
+ };
176
+ if (!row.id) {
177
+ plan.problem =
178
+ "no INS id in Work — create the issue (with its Client line), or drop a done / parked row";
179
+ return plan;
180
+ }
181
+ if (!issue) {
182
+ plan.problem = `${row.id} is not in this client's Linear project — move it there, or fix the row`;
183
+ return plan;
184
+ }
185
+ plan.linearState = issue.state.type;
186
+ const expected = EXPECTED_STATE[row.status];
187
+ plan.stateMatches =
188
+ expected === undefined ? false : expected === null || expected.includes(issue.state.type);
189
+ if (expected === undefined)
190
+ plan.problem = `status "${row.status}" is not done / this week / next / later / parked`;
191
+ if (row.status === "done")
192
+ return plan; // Done issues never reach the portal: nothing to write.
193
+ const has = new Set(issue.labels.nodes.map((l) => l.name.toLowerCase()));
194
+ const wanted = [...(TAG_LABELS[row.tag] ?? []), ...(row.status === "parked" ? ["parked"] : [])];
195
+ plan.labelsToAdd = wanted.filter((name) => !has.has(name));
196
+ const line = row.clientLine.trim();
197
+ if (line && line.toLowerCase() !== "none" && !HAS_CLIENT_LINE.test(issue.description ?? "")) {
198
+ plan.refused = refusal(line);
199
+ if (!plan.refused)
200
+ plan.clientLineToAdd = line;
201
+ }
202
+ return plan;
203
+ }
204
+ /**
205
+ * Plan (and, with `apply`, write) the move of each client's roadmap rows into
206
+ * Linear. See the header of this file for what is read and what is written.
207
+ */
208
+ export async function roadmapMigrate(options) {
209
+ const workspaceDir = resolve(options.workspaceDir ?? ".");
210
+ const { slugs, adhoc } = selectClientSlugs(workspaceDir, options, "roadmap-migrate");
211
+ const env = options.env ?? process.env;
212
+ const token = options.token ?? env[LINEAR_API_TOKEN_ENV];
213
+ if (!token)
214
+ throw new Error(`roadmap-migrate reads Linear: set ${LINEAR_API_TOKEN_ENV} (a personal API key)`);
215
+ const fetchImpl = options.fetchImpl ?? fetch;
216
+ const request = (query, variables) => linearRequest(fetchImpl, token, query, variables);
217
+ const apply = options.apply ?? false;
218
+ const clients = [];
219
+ const issuesBySlug = new Map();
220
+ const teamIds = new Set();
221
+ for (const slug of slugs) {
222
+ const dir = join(workspaceDir, "clients", `client-${slug}`);
223
+ const client = {
224
+ slug,
225
+ dir,
226
+ source: null,
227
+ project: null,
228
+ rows: [],
229
+ skipped: null,
230
+ };
231
+ clients.push(client);
232
+ const adhoc = adhocReason(dir);
233
+ if (adhoc) {
234
+ client.skipped = adhoc;
235
+ continue;
236
+ }
237
+ const clientMd = existsSync(join(dir, "CLIENT.md"))
238
+ ? readFileSync(join(dir, "CLIENT.md"), "utf8")
239
+ : "";
240
+ const url = readManifestKey(clientMd, "linear_project")?.split(/\s+/)[0];
241
+ const slugId = url?.startsWith("http") ? parseLinearProjectSlugId(url) : null;
242
+ if (!slugId) {
243
+ client.skipped =
244
+ "no Linear project in CLIENT.md (linear_project is none, missing or not a project link)";
245
+ continue;
246
+ }
247
+ client.source = ROADMAP_SOURCES.find((rel) => existsSync(join(dir, rel))) ?? null;
248
+ if (!client.source) {
249
+ client.skipped = "no docs/06-roadmap.md (nor one in docs/archive/)";
250
+ continue;
251
+ }
252
+ const project = await findProjectBySlugId(fetchImpl, token, slugId);
253
+ client.project = { name: project.name, url: project.url };
254
+ const read = await projectIssues(request, project.id);
255
+ for (const id of read.teamIds)
256
+ teamIds.add(id);
257
+ const byId = new Map(read.issues.map((i) => [i.identifier, i]));
258
+ issuesBySlug.set(slug, byId);
259
+ const rows = parseRoadmapRows(readFileSync(join(dir, client.source), "utf8"));
260
+ client.rows = rows.map((row) => planRow(row, row.id ? byId.get(row.id) : undefined));
261
+ }
262
+ // Labels: which ones the planned writes need, and which Linear already has.
263
+ const needed = [...new Set(clients.flatMap((c) => c.rows.flatMap((r) => r.labelsToAdd)))].sort();
264
+ const labelIds = new Map();
265
+ if (needed.length > 0) {
266
+ const { issueLabels } = await request(LABELS_QUERY, { filter: { or: needed.map((name) => ({ name: { eqIgnoreCase: name } })) } });
267
+ for (const label of issueLabels.nodes) {
268
+ const usable = !label.team || teamIds.has(label.team.id);
269
+ if (usable && !labelIds.has(label.name.toLowerCase()))
270
+ labelIds.set(label.name.toLowerCase(), label.id);
271
+ }
272
+ }
273
+ const labelsToCreate = needed.filter((name) => !labelIds.has(name));
274
+ const result = {
275
+ workspaceDir,
276
+ clients,
277
+ adhocSkipped: adhoc,
278
+ labelsToCreate,
279
+ createdLabels: [],
280
+ applied: apply,
281
+ writes: 0,
282
+ notes: [
283
+ apply
284
+ ? "Applied: labels and descriptions only. No state, title, priority or assignee was changed."
285
+ : "Dry run: Linear GraphQL queries only. Nothing was written. Angello runs --apply.",
286
+ "A state that does not match the row is for a person to fix in Linear; --apply never moves a state.",
287
+ ],
288
+ };
289
+ if (!apply)
290
+ return result;
291
+ const [teamId] = [...teamIds];
292
+ for (const name of labelsToCreate) {
293
+ if (!teamId)
294
+ throw new Error(`cannot create label "${name}": the project has no team`);
295
+ const { issueLabelCreate } = await request(LABEL_CREATE, { input: { name, teamId, color: LABEL_COLORS[name] } });
296
+ result.writes += 1;
297
+ if (!issueLabelCreate.success || !issueLabelCreate.issueLabel) {
298
+ throw new Error(`Linear did not create the label "${name}"`);
299
+ }
300
+ labelIds.set(name, issueLabelCreate.issueLabel.id);
301
+ result.createdLabels.push(name);
302
+ }
303
+ for (const client of clients) {
304
+ const byId = issuesBySlug.get(client.slug);
305
+ for (const row of client.rows) {
306
+ const issue = row.id ? byId?.get(row.id) : undefined;
307
+ if (!issue || (row.labelsToAdd.length === 0 && !row.clientLineToAdd))
308
+ continue;
309
+ const input = {};
310
+ if (row.labelsToAdd.length > 0) {
311
+ input.addedLabelIds = row.labelsToAdd.map((name) => labelIds.get(name));
312
+ }
313
+ if (row.clientLineToAdd) {
314
+ const current = (issue.description ?? "").trimEnd();
315
+ input.description = `${current ? `${current}\n\n` : ""}Client line: ${row.clientLineToAdd}`;
316
+ }
317
+ const { issueUpdate } = await request(ISSUE_UPDATE, {
318
+ id: issue.id,
319
+ input,
320
+ });
321
+ result.writes += 1;
322
+ if (!issueUpdate.success)
323
+ throw new Error(`Linear did not update ${row.id}`);
324
+ row.applied = true;
325
+ }
326
+ }
327
+ return result;
328
+ }
@@ -0,0 +1,61 @@
1
+ import { type ExecFileFn } from "./exec.js";
2
+ export declare const ROADMAP_FILE = "docs/06-roadmap.md";
3
+ export declare const ROADMAP_ARCHIVE = "docs/archive/06-roadmap.md";
4
+ export interface OnboardingChange {
5
+ label: string;
6
+ /** 1-based lines of the original page. */
7
+ startLine: number;
8
+ endLine: number;
9
+ removed: string[];
10
+ added: string[];
11
+ }
12
+ export interface OnboardingRetirePlan {
13
+ html: string;
14
+ changes: OnboardingChange[];
15
+ /** Lines of the original page with another link to #roadmap (hand content: listed, not edited). */
16
+ otherLinks: number[];
17
+ /**
18
+ * h2/h3 headings in the Roadmap section that the template never had: hand
19
+ * content (history, "read before you touch X" notes). `roadmapRetire --apply`
20
+ * refuses the repo until the owner moves what is still true.
21
+ */
22
+ handHeadings: string[];
23
+ }
24
+ /** What retiring the roadmap removes from one onboarding.html. Pure: reads nothing, writes nothing. */
25
+ export declare function planOnboardingRetire(html: string): OnboardingRetirePlan;
26
+ export interface RoadmapRetireClient {
27
+ slug: string;
28
+ dir: string;
29
+ /** The planned `git mv`, or null when the repo has no docs/06-roadmap.md. */
30
+ move: {
31
+ from: string;
32
+ to: string;
33
+ } | null;
34
+ changes: OnboardingChange[];
35
+ /** Hand-kept lines that still point at the roadmap, for the owner to fix. */
36
+ handFix: string[];
37
+ /** Set when nothing was planned for this repo, with the reason. */
38
+ skipped: string | null;
39
+ /** apply only: why this repo was not changed. */
40
+ refused: string | null;
41
+ applied: boolean;
42
+ }
43
+ export interface RoadmapRetireResult {
44
+ workspaceDir: string;
45
+ clients: RoadmapRetireClient[];
46
+ /** --all only: the ad hoc repos left out (they keep their roadmap). */
47
+ adhocSkipped: string[];
48
+ applied: boolean;
49
+ notes: string[];
50
+ }
51
+ export interface RoadmapRetireOptions {
52
+ workspaceDir?: string;
53
+ slug?: string;
54
+ all?: boolean;
55
+ /** git mv + write onboarding.html. Default false: report only. */
56
+ apply?: boolean;
57
+ /** git status / git mv. Injectable for tests. */
58
+ execFileImpl?: ExecFileFn;
59
+ }
60
+ /** Plan (and, with `apply`, do) the one-time roadmap cleanup in one client repo or every one. */
61
+ export declare function roadmapRetire(options: RoadmapRetireOptions): Promise<RoadmapRetireResult>;