@installagent/sdk 0.9.1 → 0.11.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,558 @@
1
+ // `ia client-drift` — does a client repo still agree with the live systems?
2
+ //
3
+ // One client engagement is written down in several places: the `## Builds`
4
+ // block of CLIENT.md (the source of the portal cards), the n8n exports in
5
+ // workflows/, onboarding.html, the delivery log, git. Each check below reads
6
+ // two of them and reports where they disagree. Drift found by hand in a client
7
+ // repo on 2026-11-04 is the reason each check exists (the "fixtures" in the
8
+ // tests): a build written up as "shadow" while it ran live, an n8n workflow
9
+ // still named "(SHADOW)" weeks after go-live.
10
+ //
11
+ // Two levels, so the exit code means one thing:
12
+ // drift — two sources disagree; one of them is wrong and must be fixed.
13
+ // check — a person should look (an export older than the instance, an open
14
+ // PR, a failed last run); it is not proof that anything is wrong.
15
+ //
16
+ // STRICTLY READ-ONLY. It GETs /workflows and /executions (status only, never
17
+ // run data), runs `git status/log/remote`, `gh pr list` and the repo's own
18
+ // `ci/repo-lint.mjs`. It never writes a file, never runs a workflow, and never
19
+ // changes anything on n8n, GitHub or Slack. `postClientDriftReport` is the one
20
+ // write in this module, and only the CLI's `--post` calls it.
21
+ import { existsSync, readFileSync } from "node:fs";
22
+ import { join, resolve } from "node:path";
23
+ import { checkAgentMirror, fetchLiveWorkflows } from "./agent-mirror.js";
24
+ import { parseLinearProjectSlugId } from "./client-linear.js";
25
+ import { readManifestKey } from "./client-manifest.js";
26
+ import { execFailureDetail, execFileAsync } from "./exec.js";
27
+ import { gitStatus } from "./git.js";
28
+ import { findProjectBySlugId, LINEAR_API_TOKEN_ENV, LinearAuthError, linearProjectIssueStates, } from "./linear-project.js";
29
+ import { listN8nExecutions } from "./n8n-executions.js";
30
+ import { parseBuildsManifest } from "./portal-sync-builds.js";
31
+ import { selectClientSlugs } from "./template-sync.js";
32
+ /** An active scheduled workflow with no run in this many days is silent. */
33
+ export const CLIENT_DRIFT_SILENCE_DAYS = 7;
34
+ const DAY_MS = 86_400_000;
35
+ /** "(SHADOW)", "TEST run", "[test]" — but not "cardfee-test", a keyword inside a word. */
36
+ const STALE_NAME = /(?:^|[\s([])(shadow|test)(?=$|[\s)\]:,.!-])/i;
37
+ /** A repo-lint drift warning: `⚠ rule 16 — <message>`. Rules 12+ are the drift rules. */
38
+ const LINT_DRIFT = /⚠\s+rule (\d+) — (.*)$/;
39
+ const FIRST_DRIFT_RULE = 12;
40
+ /** Enough pages to reach the oldest run n8n keeps (it prunes at ~10,000). */
41
+ const WINDOW_SCAN_LIMIT = 20_000;
42
+ const SLACK_LINES_PER_CLIENT = 12;
43
+ const message = (error) => (error instanceof Error ? error.message : String(error));
44
+ const short = (text, max) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
45
+ const days = (ms) => ms / DAY_MS;
46
+ /** owner/repo of a GitHub remote URL (https or ssh), or null. */
47
+ function githubRepo(remote) {
48
+ const match = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(remote.trim());
49
+ return match ? `${match[1]}/${match[2]}` : null;
50
+ }
51
+ /**
52
+ * Reads n8n runs lazily and remembers them: the newest run per workflow, and
53
+ * (only when a scheduled workflow has no run kept at all) how far back the
54
+ * instance keeps runs. The first refusal stops every later call.
55
+ */
56
+ function runReader(opts, now) {
57
+ let unread = null;
58
+ let windowDays;
59
+ return {
60
+ get unread() {
61
+ return unread;
62
+ },
63
+ get windowDays() {
64
+ return windowDays ?? null;
65
+ },
66
+ async newest(workflowId) {
67
+ if (unread)
68
+ return undefined;
69
+ try {
70
+ const { executions } = await listN8nExecutions({ workflowId, limit: 1 }, opts);
71
+ return executions[0] ?? null;
72
+ }
73
+ catch (error) {
74
+ unread = message(error);
75
+ return undefined;
76
+ }
77
+ },
78
+ /** Days of runs the instance keeps; null with no runs at all; undefined when unread. */
79
+ async window() {
80
+ if (unread)
81
+ return undefined;
82
+ if (windowDays !== undefined)
83
+ return windowDays;
84
+ try {
85
+ const { executions } = await listN8nExecutions({ limit: WINDOW_SCAN_LIMIT }, opts);
86
+ const oldest = executions.at(-1)?.startedAt;
87
+ windowDays = oldest ? days(now.getTime() - Date.parse(oldest)) : null;
88
+ }
89
+ catch (error) {
90
+ unread = message(error);
91
+ return undefined;
92
+ }
93
+ return windowDays;
94
+ },
95
+ };
96
+ }
97
+ async function checkRuns(row, wf, runs, now, silenceDays, add) {
98
+ const newest = await runs.newest(wf.id);
99
+ if (newest === undefined)
100
+ return;
101
+ if (newest && (newest.status === "error" || newest.status === "crashed")) {
102
+ add("last-error", "check", row.build, "n8n: newest run", `${newest.status} at ${newest.startedAt ?? "unknown time"} (execution ${newest.id})`, "Open that execution in n8n. Only its status was read here, never its data.");
103
+ }
104
+ if (!wf.scheduled)
105
+ return;
106
+ if (newest?.startedAt) {
107
+ const age = days(now.getTime() - Date.parse(newest.startedAt));
108
+ if (age > silenceDays) {
109
+ add("silence", "drift", row.build, "CLIENT.md Builds: active, n8n: active + scheduled", `last run ${age.toFixed(1)} days ago`, "The schedule may be broken or the trigger may have lost its credential. Check the workflow in n8n.");
110
+ }
111
+ return;
112
+ }
113
+ const window = await runs.window();
114
+ if (window === undefined)
115
+ return;
116
+ if (window !== null && window >= silenceDays) {
117
+ add("silence", "drift", row.build, "CLIENT.md Builds: active, n8n: active + scheduled", `no run in the ${window.toFixed(1)} days n8n keeps`, "The schedule may be broken or the trigger may have lost its credential. Check the workflow in n8n.");
118
+ }
119
+ else {
120
+ add("silence", "check", row.build, "CLIENT.md Builds: active, n8n: active + scheduled", "no run kept on the instance", `n8n keeps only ${window === null ? "an unknown number of" : window.toFixed(1)} days of runs, so ${silenceDays} days of silence cannot be proven. Check that the schedule ran (a weekly job can be quiet this long).`);
121
+ }
122
+ }
123
+ async function checkBuildsAgainstN8n(slug, workspaceDir, rows, live, runs, ctx, add, skipped) {
124
+ const byId = new Map(live.map((w) => [w.id, w]));
125
+ const mirror = await checkAgentMirror({
126
+ workspaceDir,
127
+ client: slug,
128
+ liveWorkflows: live,
129
+ execFileImpl: ctx.execFileImpl,
130
+ });
131
+ const exported = new Set(mirror.rows.map((r) => r.workflowId).filter((id) => Boolean(id)));
132
+ for (const row of rows) {
133
+ if (row.type !== "agent" || !row.workflowId)
134
+ continue;
135
+ const wf = byId.get(row.workflowId);
136
+ if (!wf) {
137
+ if (row.status !== "retired") {
138
+ add("missing-workflow", "drift", row.build, `CLIENT.md Builds: ${row.status}, workflow ${row.workflowId}`, "n8n: no such workflow (archived ones included)", "Fix the workflow_id in CLIENT.md, or set the row to retired. Never delete a row the portal has.");
139
+ }
140
+ continue;
141
+ }
142
+ const liveState = wf.archived ? "archived" : wf.active ? "active" : "inactive";
143
+ if (row.status === "active" && liveState !== "active") {
144
+ add("active-flag", "drift", row.build, "CLIENT.md Builds: active", `n8n: ${liveState} (${wf.id})`, "Publish the workflow in n8n, or set the row to paused (CADENCE.md § surface matrix: a build goes live, is renamed, or retires).");
145
+ }
146
+ else if (row.status !== "active" && liveState === "active") {
147
+ add("active-flag", "drift", row.build, `CLIENT.md Builds: ${row.status}`, `n8n: active (${wf.id})`, "Set the row to active, or deactivate the workflow in n8n.");
148
+ }
149
+ if (row.status === "active") {
150
+ const stale = STALE_NAME.test(wf.name)
151
+ ? `n8n name: "${wf.name}"`
152
+ : wf.description && STALE_NAME.test(wf.description)
153
+ ? `n8n description: "${short(wf.description, 90)}"`
154
+ : null;
155
+ if (stale) {
156
+ add("name", "drift", row.build, "CLIENT.md Builds: active", stale, "Rename the workflow or fix its description in n8n (a write on the instance: the account owner does it), then re-export.");
157
+ }
158
+ if (!exported.has(wf.id) && !wf.archived) {
159
+ add("missing-export", "drift", row.build, `CLIENT.md Builds: ${row.status}, workflow ${wf.id}`, `workflows/: no export records this id or has the live name "${wf.name}"`, "Export it to workflows/<name>.json (credential ids scrubbed) and record its id in the file. If an export exists under an old name, re-export it: the instance moved on.");
160
+ }
161
+ if (liveState === "active")
162
+ await checkRuns(row, wf, runs, ctx.now, ctx.silenceDays, add);
163
+ }
164
+ }
165
+ for (const m of mirror.rows) {
166
+ const file = m.file?.replace(`clients/client-${slug}/`, "") ?? m.workflowName;
167
+ if (m.state === "needs-diff") {
168
+ add("stale-export", "check", file, `export committed ${m.exportedAt}`, `n8n updated ${m.liveUpdatedAt}`, "Open both and compare; re-export if the definition changed. A newer n8n time alone is not drift: deactivating a workflow bumps it.");
169
+ }
170
+ else if (m.state === "no-live-match") {
171
+ add("orphan-export", "check", file, `export: "${m.workflowName}"`, "n8n: no live workflow (archived ones included)", "Deleted on the instance, or the export records a wrong id. Confirm in n8n before you remove the file.");
172
+ }
173
+ }
174
+ if (mirror.rows.length > 0 && !mirror.commitTimesAvailable) {
175
+ skipped.push("stale-export: no commit time for any export (not a git checkout)");
176
+ }
177
+ }
178
+ async function checkGit(dir, statusFn, execFileImpl, add, skipped) {
179
+ if (!existsSync(join(dir, ".git"))) {
180
+ skipped.push("git: not a git checkout");
181
+ return;
182
+ }
183
+ try {
184
+ const s = await statusFn(dir);
185
+ const branch = s.branch ?? "(detached)";
186
+ const clean = "git: committed and pushed";
187
+ const hint = "Commit it as one slice with its surfaces (CADENCE.md), or discard it. Then push.";
188
+ if (s.dirty)
189
+ add("git", "drift", branch, clean, "uncommitted changes to tracked files", hint);
190
+ if (s.untracked > 0)
191
+ add("git", "drift", branch, clean, `${s.untracked} untracked path(s)`, hint);
192
+ if (s.ahead > 0)
193
+ add("git", "drift", branch, clean, `${s.ahead} unpushed commit(s)`, "Push them (this repo's AGENT.md says how: a PR or straight to main).");
194
+ if (!s.upstream) {
195
+ add("git", "check", branch, "git: a branch with an upstream", "no upstream branch", "Push with -u, or check out the default branch.");
196
+ }
197
+ }
198
+ catch (error) {
199
+ skipped.push(`git status: ${message(error).split("\n")[0]}`);
200
+ }
201
+ try {
202
+ const { stdout: remote } = await execFileImpl("git", [
203
+ "-C",
204
+ dir,
205
+ "remote",
206
+ "get-url",
207
+ "origin",
208
+ ]);
209
+ const repo = githubRepo(remote);
210
+ if (!repo) {
211
+ skipped.push("open PRs: origin is not a GitHub remote");
212
+ return;
213
+ }
214
+ const { stdout } = await execFileImpl("gh", [
215
+ "pr",
216
+ "list",
217
+ "--repo",
218
+ repo,
219
+ "--state",
220
+ "open",
221
+ "--json",
222
+ "number,title,url",
223
+ "--limit",
224
+ "50",
225
+ ]);
226
+ const prs = JSON.parse(stdout || "[]");
227
+ for (const pr of prs) {
228
+ add("open-pr", "check", `#${pr.number}`, "GitHub: no open PRs", `open PR: "${short(pr.title, 70)}"`, `Review, merge or close it: ${pr.url}`);
229
+ }
230
+ }
231
+ catch (error) {
232
+ skipped.push(`open PRs: ${execFailureDetail(error).detail.split("\n")[0]}`);
233
+ }
234
+ }
235
+ async function checkLint(dir, execFileImpl, add, skipped) {
236
+ const script = join(dir, "ci", "repo-lint.mjs");
237
+ if (!existsSync(script)) {
238
+ skipped.push("repo-lint: no ci/repo-lint.mjs");
239
+ return;
240
+ }
241
+ let stderr = "";
242
+ let failed = false;
243
+ try {
244
+ ({ stderr } = await execFileImpl(process.execPath, [script, dir]));
245
+ }
246
+ catch (error) {
247
+ failed = true;
248
+ const err = error;
249
+ stderr = typeof err.stderr === "string" ? err.stderr : message(error);
250
+ }
251
+ for (const line of stderr.split("\n")) {
252
+ const match = LINT_DRIFT.exec(line.trim());
253
+ if (!match || Number(match[1]) < FIRST_DRIFT_RULE)
254
+ continue;
255
+ add("lint", "drift", `rule ${match[1]}`, "repo-lint drift rule", short(match[2], 220), "Fix the surface that lost (CADENCE.md § Precedence) in one commit.");
256
+ }
257
+ if (failed) {
258
+ const first = stderr
259
+ .split("\n")
260
+ .map((l) => l.trim())
261
+ .find((l) => l.startsWith("✗"));
262
+ add("lint", "drift", "repo-lint", "repo-lint passes", short(first?.replace(/^✗\s*/, "") ?? "exit 1", 220), "Run `node ci/repo-lint.mjs` in the repo and fix the errors.");
263
+ }
264
+ }
265
+ // ── Linear: a mirror of the delivery log, never a source ─────────────────────
266
+ /** Done issues older than this are history; open ones untouched this long are stale. */
267
+ const LINEAR_RECENT_DAYS = 30;
268
+ // A heading that says the work shipped. Bare "live" is not enough ("Live sheet
269
+ // check"), and a negation cancels it ("no automation shipped yet").
270
+ const SHIPPED_WORDS = /\b(shipped|published|deployed|go-live|went live|goes live|is live|now live|live since|live on)\b/i;
271
+ const NOT_SHIPPED = /\b(no|not|never|nothing)\b[^.;:()]{0,30}\b(shipped|published|deployed|live)\b/i;
272
+ const saysShipped = (heading) => SHIPPED_WORDS.test(heading) && !NOT_SHIPPED.test(heading);
273
+ const LOG_HEADING = /^##\s+(\d{4}-\d{2}-\d{2})\b\s*(.*)$/;
274
+ const ISSUE_TOKEN = /\b[A-Z][A-Z0-9]{1,9}-\d+\b/g;
275
+ const CLOSED_STATES = new Set(["completed", "canceled", "duplicate"]);
276
+ const FOLLOW_UPS_FIELD = /^-\s+\*\*Follow-ups?:\*\*/i;
277
+ const INDENTED = /^[ \t]+\S/;
278
+ /**
279
+ * The day client-template's repo-lint rule 20 starts: from then on, a log
280
+ * entry's Follow-ups is `none` or INS ids only (owed work, never shipped work).
281
+ * Mirrors FOLLOWUPS_INS_FROM in client-template/ci/repo-lint.mjs.
282
+ */
283
+ export const FOLLOWUPS_INS_FROM = "2026-11-08";
284
+ /** Dated delivery-log entries. Fenced examples are skipped. */
285
+ function logEntries(log) {
286
+ const entries = [];
287
+ let current = null;
288
+ let fenced = false;
289
+ let inFollowUps = false;
290
+ for (const line of log.split("\n")) {
291
+ if (/^\s*```/.test(line)) {
292
+ fenced = !fenced;
293
+ continue;
294
+ }
295
+ if (fenced)
296
+ continue;
297
+ const heading = LOG_HEADING.exec(line);
298
+ if (heading) {
299
+ const text = heading[2].replace(/^[—–-]\s*/, "").trim();
300
+ current = { date: heading[1], heading: text, tokens: new Set(), followUps: new Set() };
301
+ entries.push(current);
302
+ }
303
+ else if (/^##\s/.test(line)) {
304
+ current = null;
305
+ }
306
+ inFollowUps = FOLLOW_UPS_FIELD.test(line) || (inFollowUps && INDENTED.test(line));
307
+ if (!current)
308
+ continue;
309
+ // A rule-20 follow-up is owed work: it must not count as the entry naming the issue.
310
+ const into = inFollowUps && current.date >= FOLLOWUPS_INS_FROM ? current.followUps : current.tokens;
311
+ for (const match of line.matchAll(ISSUE_TOKEN))
312
+ into.add(match[0]);
313
+ }
314
+ return entries;
315
+ }
316
+ function linearRows(issues, entries, now, add) {
317
+ const age = (iso) => days(now.getTime() - Date.parse(iso));
318
+ const known = new Set(issues.map((i) => i.identifier));
319
+ // Only ids of THIS project count: a log names other teams' ids too (BM-4, INS-860).
320
+ const namedBy = new Map();
321
+ for (const entry of entries) {
322
+ for (const token of entry.tokens) {
323
+ if (known.has(token))
324
+ namedBy.set(token, [...(namedBy.get(token) ?? []), entry]);
325
+ }
326
+ for (const id of entry.followUps) {
327
+ if (known.has(id) || !id.startsWith("INS-"))
328
+ continue;
329
+ add("linear", "check", id, `delivery log ${entry.date}: Follow-ups names ${id}`, "Linear: not in this client's Linear project", "Fix the id in the entry, or move the issue into this client's project (a Linear write: the account owner does it).");
330
+ }
331
+ }
332
+ for (const issue of issues) {
333
+ const naming = namedBy.get(issue.identifier) ?? [];
334
+ if (issue.stateType === "completed") {
335
+ if (!issue.completedAt || age(issue.completedAt) > LINEAR_RECENT_DAYS)
336
+ continue;
337
+ if (naming.length > 0 || (issue.parent && namedBy.has(issue.parent)))
338
+ continue;
339
+ add("linear", "drift", issue.identifier, `Linear: Done ${issue.completedAt.slice(0, 10)}`, "delivery log: no entry names it (or its parent)", "Append the delivery-log entry for what shipped, or name the id in the entry that covers it (CADENCE.md § surface matrix: Something shipped).");
340
+ continue;
341
+ }
342
+ if (CLOSED_STATES.has(issue.stateType) || naming.length === 0)
343
+ continue;
344
+ const newest = [...naming].sort((a, b) => b.date.localeCompare(a.date))[0];
345
+ if (age(issue.updatedAt) > LINEAR_RECENT_DAYS && saysShipped(newest.heading)) {
346
+ add("linear", "drift", issue.identifier, `Linear: still ${issue.stateType}, no change in ${Math.floor(age(issue.updatedAt))} days`, `delivery log ${newest.date}: "${short(newest.heading, 90)}"`, "If it shipped, close the issue from the commit or PR that names its id (a PR title with the id closes it). If not, fix the log entry.");
347
+ }
348
+ else if (age(`${newest.date}T00:00:00Z`) <= LINEAR_RECENT_DAYS) {
349
+ add("linear", "check", issue.identifier, `Linear: still ${issue.stateType}`, `delivery log ${newest.date} names it: "${short(newest.heading, 70)}"`, "Close it if that entry finished it; leave it open if the entry was one slice of it.");
350
+ }
351
+ }
352
+ }
353
+ /** Reads Linear per client. The first auth failure stops every later read. */
354
+ function linearReader(options) {
355
+ const env = options.env ?? process.env;
356
+ const token = options.linearToken ?? env[LINEAR_API_TOKEN_ENV];
357
+ const fetchImpl = options.fetchImpl ?? fetch;
358
+ let unread = null;
359
+ return {
360
+ get unread() {
361
+ return unread;
362
+ },
363
+ async check(dir, clientMd, now, add, skipped) {
364
+ const backlog = readManifestKey(clientMd, "backlog")?.split(/\s+/)[0];
365
+ const url = readManifestKey(clientMd, "linear_project")?.split(/\s+/)[0];
366
+ if (!url?.startsWith("http")) {
367
+ skipped.push(backlog
368
+ ? `Linear: no Linear project for this client (its tracker is ${backlog})`
369
+ : "Linear: no linear_project in CLIENT.md");
370
+ return;
371
+ }
372
+ if (unread)
373
+ return;
374
+ if (!token) {
375
+ unread = `$${LINEAR_API_TOKEN_ENV} not set`;
376
+ return;
377
+ }
378
+ const slugId = parseLinearProjectSlugId(url);
379
+ if (!slugId) {
380
+ skipped.push(`Linear: no project id in ${url}`);
381
+ return;
382
+ }
383
+ try {
384
+ const project = await findProjectBySlugId(fetchImpl, token, slugId);
385
+ const issues = await linearProjectIssueStates(fetchImpl, token, project);
386
+ const logPath = join(dir, "docs", "00-delivery-log.md");
387
+ const log = existsSync(logPath) ? readFileSync(logPath, "utf8") : "";
388
+ linearRows(issues, logEntries(log), now, add);
389
+ }
390
+ catch (error) {
391
+ if (error instanceof LinearAuthError)
392
+ unread = message(error);
393
+ else
394
+ skipped.push(`Linear: ${message(error).split("\n")[0]}`);
395
+ }
396
+ },
397
+ };
398
+ }
399
+ /**
400
+ * Compare one client repo (or every one) with n8n, git, Linear and its own lint.
401
+ * Never throws for a source it cannot read: the source goes into
402
+ * `unreadSources` (whole run) or the client's `skipped` list, and the other
403
+ * checks still run.
404
+ */
405
+ export async function clientDrift(options) {
406
+ const workspaceDir = resolve(options.workspaceDir ?? ".");
407
+ const { slugs, adhoc } = selectClientSlugs(workspaceDir, options, "client-drift");
408
+ const now = (options.now ?? (() => new Date()))();
409
+ const silenceDays = options.silenceDays ?? CLIENT_DRIFT_SILENCE_DAYS;
410
+ const execFileImpl = options.execFileImpl ?? execFileAsync;
411
+ const statusFn = options.statusFn ?? gitStatus;
412
+ const n8nOpts = {
413
+ baseUrl: options.baseUrl,
414
+ apiKey: options.apiKey,
415
+ env: options.env,
416
+ fetchImpl: options.fetchImpl,
417
+ };
418
+ const unreadSources = [];
419
+ let live = null;
420
+ try {
421
+ live = await fetchLiveWorkflows(n8nOpts);
422
+ }
423
+ catch (error) {
424
+ unreadSources.push(`n8n workflows: ${message(error)}`);
425
+ }
426
+ const runs = runReader(n8nOpts, now);
427
+ const linear = linearReader(options);
428
+ const clients = [];
429
+ for (const slug of slugs) {
430
+ const dir = join(workspaceDir, "clients", `client-${slug}`);
431
+ const findings = [];
432
+ const skipped = [];
433
+ const add = (check, level, subject, sourceA, sourceB, hint) => findings.push({ client: slug, check, level, subject, sourceA, sourceB, hint });
434
+ let rows = [];
435
+ const clientMdPath = join(dir, "CLIENT.md");
436
+ const clientMd = existsSync(clientMdPath) ? readFileSync(clientMdPath, "utf8") : null;
437
+ if (clientMd === null) {
438
+ skipped.push("Builds checks: no CLIENT.md");
439
+ }
440
+ else {
441
+ const manifest = parseBuildsManifest(clientMd);
442
+ if (manifest.state === "ok")
443
+ rows = manifest.rows;
444
+ else {
445
+ const why = manifest.state === "invalid" ? `invalid (${manifest.errors[0]})` : manifest.state;
446
+ skipped.push(`Builds checks: the CLIENT.md ## Builds block is ${why}`);
447
+ }
448
+ }
449
+ if (live) {
450
+ await checkBuildsAgainstN8n(slug, workspaceDir, rows, live, runs, { now, silenceDays, execFileImpl }, add, skipped);
451
+ }
452
+ if (options.git ?? true)
453
+ await checkGit(dir, statusFn, execFileImpl, add, skipped);
454
+ await checkLint(dir, execFileImpl, add, skipped);
455
+ if (clientMd !== null && (options.linear ?? true)) {
456
+ await linear.check(dir, clientMd, now, add, skipped);
457
+ }
458
+ findings.sort((a, b) => (a.level === b.level ? 0 : a.level === "drift" ? -1 : 1));
459
+ clients.push({ slug, dir, findings, skipped });
460
+ }
461
+ if (runs.unread)
462
+ unreadSources.push(`n8n executions: ${runs.unread}`);
463
+ if (linear.unread)
464
+ unreadSources.push(`Linear: ${linear.unread}`);
465
+ const all = clients.flatMap((c) => c.findings);
466
+ return {
467
+ workspaceDir,
468
+ generatedAt: now.toISOString(),
469
+ clients,
470
+ driftCount: all.filter((f) => f.level === "drift").length,
471
+ checkCount: all.filter((f) => f.level === "check").length,
472
+ unreadSources,
473
+ executionWindowDays: runs.windowDays,
474
+ notes: [
475
+ "Read-only: GET /workflows and GET /executions (status only, never run data); Linear GraphQL queries (never a mutation); git status/log/remote; gh pr list; the repo's own ci/repo-lint.mjs. Nothing was written.",
476
+ `Silence: an active scheduled workflow with no run in ${silenceDays} days. n8n keeps only its newest ~10,000 runs, so "no run kept" is drift only when the kept window is at least that long.`,
477
+ "`check` rows are prompts for a person; only `drift` rows (and unread sources) fail the run.",
478
+ ...(adhoc.length > 0
479
+ ? [
480
+ `Skipped ad hoc repos (not official Install Agent projects; name one to check it): ${adhoc.join(", ")}.`,
481
+ ]
482
+ : []),
483
+ ],
484
+ };
485
+ }
486
+ // ── The weekly report ────────────────────────────────────────────────────────
487
+ /** Slack mrkdwn escapes the three control characters; everything else is text. */
488
+ const slackText = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
489
+ /**
490
+ * The Slack text for a drift result, or null when there is nothing to say (no
491
+ * finding and no unread source). Internal channel only: it names clients and
492
+ * builds, never PII, never money.
493
+ */
494
+ export function formatClientDriftSlack(result) {
495
+ const withFindings = result.clients.filter((c) => c.findings.length > 0);
496
+ if (withFindings.length === 0 && result.unreadSources.length === 0)
497
+ return null;
498
+ const lines = [
499
+ `*Client drift* · ${result.generatedAt.slice(0, 10)} · ${result.driftCount} drift, ${result.checkCount} to check · ${result.clients.length} repo(s)`,
500
+ ];
501
+ for (const client of withFindings) {
502
+ // Drift rows in full; check rows only as counts — a weekly post a person
503
+ // reads, not the table (`ia client-drift --all` has every row and hint).
504
+ const drift = client.findings.filter((f) => f.level === "drift");
505
+ const checks = new Map();
506
+ for (const f of client.findings) {
507
+ if (f.level === "check")
508
+ checks.set(f.check, (checks.get(f.check) ?? 0) + 1);
509
+ }
510
+ const toCheck = [...checks].map(([check, n]) => `${n} ${check}`).join(", ");
511
+ const heading = `*${slackText(client.slug)}*`;
512
+ if (drift.length === 0) {
513
+ lines.push("", `${heading} — to check: ${toCheck}`);
514
+ continue;
515
+ }
516
+ lines.push("", heading);
517
+ for (const f of drift.slice(0, SLACK_LINES_PER_CLIENT)) {
518
+ lines.push(`• DRIFT · ${f.check} · ${slackText(f.subject)} — ${slackText(f.sourceA)} ≠ ${slackText(f.sourceB)}`);
519
+ }
520
+ const more = drift.length - SLACK_LINES_PER_CLIENT;
521
+ if (more > 0)
522
+ lines.push(`• …and ${more} more drift row(s)`);
523
+ if (toCheck)
524
+ lines.push(`• to check: ${toCheck}`);
525
+ }
526
+ if (result.unreadSources.length > 0) {
527
+ lines.push("", `_Not read, so this report is partial: ${slackText(result.unreadSources.join("; "))}_`);
528
+ }
529
+ lines.push("", "Full table and hints: `ia client-drift --all`");
530
+ return lines.join("\n");
531
+ }
532
+ /**
533
+ * Post the weekly drift report — only when `formatClientDriftSlack` has
534
+ * something to say. Throws when Slack refuses, so a scheduled run fails loudly.
535
+ */
536
+ export async function postClientDriftReport(result, opts) {
537
+ if (!opts.token)
538
+ throw new Error("posting the drift report needs a Slack bot token ($SLACK_BOT_TOKEN)");
539
+ if (!opts.channel)
540
+ throw new Error("posting the drift report needs a Slack channel id");
541
+ const text = formatClientDriftSlack(result);
542
+ if (text === null)
543
+ return { status: "empty" };
544
+ const fetchImpl = opts.fetchImpl ?? fetch;
545
+ const response = await fetchImpl("https://slack.com/api/chat.postMessage", {
546
+ method: "POST",
547
+ headers: {
548
+ authorization: `Bearer ${opts.token}`,
549
+ "content-type": "application/json; charset=utf-8",
550
+ },
551
+ body: JSON.stringify({ channel: opts.channel, text, unfurl_links: false, unfurl_media: false }),
552
+ });
553
+ const body = (await response.json().catch(() => ({})));
554
+ if (!response.ok || !body.ok) {
555
+ throw new Error(`Slack refused the drift report: ${body.error ?? `HTTP ${response.status}`}`);
556
+ }
557
+ return { status: "posted", ts: String(body.ts) };
558
+ }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  export { type AccessCheckItem, type AccessCheckOptions, type AccessCheckResult, type AccessService, type AccessStatus, accessCheck, classifyKey, clientVaultFor, } from "./access-check.js";
2
- export { type AgentMirrorOptions, type AgentMirrorResult, checkAgentMirror, type MirrorRow, type MirrorState, type MirrorSummary, } from "./agent-mirror.js";
2
+ export { type AgentMirrorOptions, type AgentMirrorResult, checkAgentMirror, type FetchLiveWorkflowsOptions, fetchLiveWorkflows, type LiveWorkflow, type MirrorRow, type MirrorState, type MirrorSummary, } from "./agent-mirror.js";
3
3
  export { type AgentBankOptions, type AgentTemplateInfo, type AgentTemplateMatch, type CreateFromTemplateInput, type CreateFromTemplateResult, createFromAgentTemplate, type ListAgentTemplatesResult, listAgentTemplates, N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError, type SanitizedWorkflow, type SaveAgentTemplateInput, type SaveAgentTemplateOptions, type SaveAgentTemplateResult, type SearchAgentTemplatesOptions, type SearchAgentTemplatesResult, type SopState, type StrippedCredential, sanitizeN8nWorkflow, saveAgentTemplate, searchAgentTemplates, } from "./agent-templates.js";
4
4
  export { CLAUDE_CONFIG_DIR_ENV, type ClaudeHoursExportOptions, type ClaudeHoursExportResult, type ClaudeHoursSummaryRow, compactClaudeHoursExport, type DeliverClaudeHoursExportOptions, type DeliverClaudeHoursExportResult, deliverClaudeHoursExport, exportClaudeHours, HOURS_EXPORT_DIR, HOURS_EXPORT_SCHEMA, HOURS_EXPORT_SECRET_ENV, HOURS_EXPORT_SECRET_HEADER, HOURS_EXPORT_WEBHOOK_URL, PROMPT_WINDOW_MINUTES, parseLedgerDate, parseMinuteIso, type SaveClaudeHoursExportOptions, type SendClaudeHoursExportOptions, saveClaudeHoursExport, sendClaudeHoursExport, TOOL_INPUT_PATH_KEYS, UNATTRIBUTED_SLUG, } from "./claude-hours.js";
5
5
  export { ClientBuildAuthError, type ClientBuildDoc, type ClientBuildOptions, type ClientBuildResult, clientBuild, GITHUB_API_TOKEN_ENV, } from "./client-build.js";
6
6
  export { type ClientCall, type ClientContextOptions, type ClientContextResult, clientContext, } from "./client-context.js";
7
+ export { CLIENT_DRIFT_SILENCE_DAYS, type ClientDriftClient, type ClientDriftOptions, type ClientDriftResult, clientDrift, type DriftCheck, type DriftFinding, type DriftLevel, FOLLOWUPS_INS_FROM, formatClientDriftSlack, type PostClientDriftOptions, type PostClientDriftResult, postClientDriftReport, type RepoStatusInfo, type StatusFn, } from "./client-drift.js";
7
8
  export { AIRTABLE_API_TOKEN_ENV, buildAssertionClaims, ClientDriveAuthError, type ClientDriveDoc, type ClientDriveSearchOptions, type ClientDriveSearchResult, clientDriveSearch, GOOGLE_SERVICE_ACCOUNT_KEY_ENV, parseServiceAccountKey, } from "./client-drive.js";
8
9
  export { ClientIntakeAuthError, type ClientIntakeInput, type ClientIntakeOptions, type ClientIntakeResult, type ClientIntakeStep, clientIntake, LINEAR_CLIENT_TEAM_ID_ENV, } from "./client-intake.js";
9
10
  export { ClientLinearAuthError, type ClientLinearProjectOptions, clientLinearProject, parseLinearProjectSlugId, type ResolvedClientLinearProject, resolveClientLinearProject, } from "./client-linear.js";
@@ -41,10 +42,12 @@ export { detectPlatform, detectPlatformInfo, detectShell, opNeedsAnotherShell, t
41
42
  export { DEFAULT_PORTAL_URL, PORTAL_ADMIN_SECRET_ENV, PORTAL_BUILD_TYPES, PORTAL_PASSWORD_WARNING, PORTAL_SYNC_MAX_DAYS, PORTAL_URL_ENV, type PortalAddUserInput, type PortalAddUserResult, PortalAdminAuthError, type PortalAdminOptions, type PortalAgent, type PortalAgentSyncRow, type PortalBuild, type PortalBuildType, type PortalCreateAgentInput, type PortalCreateBuildInput, type PortalCreateOrgInput, type PortalCreateOrgResult, type PortalListAgentsResult, type PortalListBuildsResult, type PortalListOrgsResult, type PortalOrg, type PortalOrgUser, PortalRequestError, type PortalSetAgentNameInput, type PortalSetAgentNameResult, type PortalSetAgentStatusInput, type PortalSetAgentStatusResult, type PortalSetAgentTriageResult, type PortalSetAgentWorkflowInput, type PortalSetAgentWorkflowResult, type PortalSetBuildDetailsInput, type PortalSetBuildDetailsResult, type PortalSetBuildStatusInput, type PortalSetDriveFolderResult, type PortalSetPasswordResult, type PortalSetUserInput, type PortalSetUserResult, type PortalSyncRunsResult, type PortalTriageBackfillResult, type PortalTriageProvider, type PortalTriageRecordsPage, portalAddUser, portalBackfillTriageRecords, portalBuildType, portalBuildWorkflowId, portalCreateAgent, portalCreateBuild, portalCreateOrg, portalListAgents, portalListBuilds, portalListOrgs, portalReadTriageRecords, portalSetAgentName, portalSetAgentStatus, portalSetAgentTriage, portalSetAgentWorkflow, portalSetBuildDetails, portalSetBuildName, portalSetBuildStatus, portalSetBuildTriage, portalSetBuildWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSetUser, portalSyncRuns, validatePortalBuildFields, } from "./portal-admin.js";
42
43
  export { BUILD_DESCRIPTION_MAX, BUILD_NAME_MAX, BUILDS_MANIFEST_END, BUILDS_MANIFEST_START, type BuildsManifest, type BuildsManifestSource, type BuildsManifestState, type BuildsSyncAction, type BuildsSyncActionResult, type BuildsSyncOptions, type BuildsSyncOrgResult, type BuildsSyncPlan, type BuildsSyncResult, type ManifestBuild, type ManifestBuildStatus, parseBuildsManifest, planBuildsSync, type RemoteClientMdReader, syncBuilds, } from "./portal-sync-builds.js";
43
44
  export { expectedGithubAccount, type PrOpenOptions, type PrOpenResult, parseGithubRemote, prOpen, } from "./pr-open.js";
45
+ export { CLIENT_LINE_MAX, parseRoadmapRows, ROADMAP_LABELS, ROADMAP_SOURCES, type RoadmapMigrateClient, type RoadmapMigrateOptions, type RoadmapMigrateResult, type RoadmapMigrateRow, type RoadmapRow, roadmapMigrate, } from "./roadmap-migrate.js";
46
+ export { type OnboardingChange, type OnboardingRetirePlan, planOnboardingRetire, ROADMAP_ARCHIVE, ROADMAP_FILE, type RoadmapRetireClient, type RoadmapRetireOptions, type RoadmapRetireResult, roadmapRetire, } from "./roadmap-retire.js";
44
47
  export { type StandupCallPrep, type StandupCallPrepStatus, type StandupGitState, type StandupIssueRef, type StandupLinear, type StandupOptions, type StandupRepo, type StandupRepoLint, type StandupResult, type StandupStaleTodo, standup, } from "./standup.js";
45
48
  export { type SyncRepoResult, type SyncRepoStatus, type SyncReposOptions, type SyncReposResult, syncRepos, workspaceRepoNames, } from "./sync-repos.js";
46
49
  export { type SyncTemplatesFileResult, type SyncTemplatesFileStatus, type SyncTemplatesOptions, type SyncTemplatesResult, syncTemplates, TEMPLATE_CLAUDE_SETTINGS, TEMPLATE_ROOT_DOCS, } from "./sync-templates.js";
47
- export { TEMPLATE_SYNCED_FILES, type TemplateSyncFileResult, type TemplateSyncFileStatus, type TemplateSyncOptions, type TemplateSyncRepoResult, type TemplateSyncResult, templateSync, } from "./template-sync.js";
50
+ export { adhocReason, selectClientSlugs, TEMPLATE_RETIRED_FILES, TEMPLATE_SYNCED_FILES, type TemplateSyncFileResult, type TemplateSyncFileStatus, type TemplateSyncOptions, type TemplateSyncRepoResult, type TemplateSyncResult, templateSync, } from "./template-sync.js";
48
51
  export { TRIAGE_BACKFILL_CHUNK, type TriageBackfillOptions, type TriageBackfillResult, triageBackfill, } from "./triage-backfill.js";
49
52
  export { checkTriageRecordWiring, detectWorkflowProvider, PORTAL_INGEST_CREDENTIAL_NAME, TRIAGE_RECORDS_PATH, type TriageEnableOptions, type TriageEnableResult, type TriageWiringCheck, type TriageWiringCheckId, type TriageWiringReport, triageEnable, } from "./triage-enable.js";
50
53
  export { CRITICAL_PRIORITIES, CRITICAL_URGENCIES, detectProvider, GMAIL_HEADERS, GMAIL_LANE_BY_DISPOSITION, laneFor, OUTLOOK_HEADERS, OUTLOOK_LANE_BY_CATEGORY, parseCsv, parseLaneOverrides, type RecordTable, readRecordSheetTable, resolveRecordSheetId, SHEETS_SCOPE, seededRandom, TRIAGE_GATES, TRIAGE_LANES, TRIAGE_STAGES, type TriageGateSampleOptions, type TriageGateSampleResult, type TriageHealthOptions, type TriageHealthResult, type TriageLane, type TriageProvider, type TriageRecordRow, type TriageSampleRow, type TriageSoakReportOptions, type TriageSoakReportResult, type TriageSourceOptions, type TriageStage, type TriageWindow, triageGateSample, triageHealth, triageSoakReport, } from "./triage-gates.js";
package/dist/index.js CHANGED
@@ -2,11 +2,12 @@
2
2
  // apps/mcp are thin adapters over these exports; every operation here must be
3
3
  // reachable from both. See ../../docs/spec.md.
4
4
  export { accessCheck, classifyKey, clientVaultFor, } from "./access-check.js";
5
- export { checkAgentMirror, } from "./agent-mirror.js";
5
+ export { checkAgentMirror, fetchLiveWorkflows, } from "./agent-mirror.js";
6
6
  export { createFromAgentTemplate, listAgentTemplates, N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError, sanitizeN8nWorkflow, saveAgentTemplate, searchAgentTemplates, } from "./agent-templates.js";
7
7
  export { CLAUDE_CONFIG_DIR_ENV, compactClaudeHoursExport, deliverClaudeHoursExport, exportClaudeHours, HOURS_EXPORT_DIR, HOURS_EXPORT_SCHEMA, HOURS_EXPORT_SECRET_ENV, HOURS_EXPORT_SECRET_HEADER, HOURS_EXPORT_WEBHOOK_URL, PROMPT_WINDOW_MINUTES, parseLedgerDate, parseMinuteIso, saveClaudeHoursExport, sendClaudeHoursExport, TOOL_INPUT_PATH_KEYS, UNATTRIBUTED_SLUG, } from "./claude-hours.js";
8
8
  export { ClientBuildAuthError, clientBuild, GITHUB_API_TOKEN_ENV, } from "./client-build.js";
9
9
  export { clientContext, } from "./client-context.js";
10
+ export { CLIENT_DRIFT_SILENCE_DAYS, clientDrift, FOLLOWUPS_INS_FROM, formatClientDriftSlack, postClientDriftReport, } from "./client-drift.js";
10
11
  export { AIRTABLE_API_TOKEN_ENV, buildAssertionClaims, ClientDriveAuthError, clientDriveSearch, GOOGLE_SERVICE_ACCOUNT_KEY_ENV, parseServiceAccountKey, } from "./client-drive.js";
11
12
  export { ClientIntakeAuthError, clientIntake, LINEAR_CLIENT_TEAM_ID_ENV, } from "./client-intake.js";
12
13
  export { ClientLinearAuthError, clientLinearProject, parseLinearProjectSlugId, resolveClientLinearProject, } from "./client-linear.js";
@@ -44,10 +45,12 @@ export { detectPlatform, detectPlatformInfo, detectShell, opNeedsAnotherShell, }
44
45
  export { DEFAULT_PORTAL_URL, PORTAL_ADMIN_SECRET_ENV, PORTAL_BUILD_TYPES, PORTAL_PASSWORD_WARNING, PORTAL_SYNC_MAX_DAYS, PORTAL_URL_ENV, PortalAdminAuthError, PortalRequestError, portalAddUser, portalBackfillTriageRecords, portalBuildType, portalBuildWorkflowId, portalCreateAgent, portalCreateBuild, portalCreateOrg, portalListAgents, portalListBuilds, portalListOrgs, portalReadTriageRecords, portalSetAgentName, portalSetAgentStatus, portalSetAgentTriage, portalSetAgentWorkflow, portalSetBuildDetails, portalSetBuildName, portalSetBuildStatus, portalSetBuildTriage, portalSetBuildWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSetUser, portalSyncRuns, validatePortalBuildFields, } from "./portal-admin.js";
45
46
  export { BUILD_DESCRIPTION_MAX, BUILD_NAME_MAX, BUILDS_MANIFEST_END, BUILDS_MANIFEST_START, parseBuildsManifest, planBuildsSync, syncBuilds, } from "./portal-sync-builds.js";
46
47
  export { expectedGithubAccount, parseGithubRemote, prOpen, } from "./pr-open.js";
48
+ export { CLIENT_LINE_MAX, parseRoadmapRows, ROADMAP_LABELS, ROADMAP_SOURCES, roadmapMigrate, } from "./roadmap-migrate.js";
49
+ export { planOnboardingRetire, ROADMAP_ARCHIVE, ROADMAP_FILE, roadmapRetire, } from "./roadmap-retire.js";
47
50
  export { standup, } from "./standup.js";
48
51
  export { syncRepos, workspaceRepoNames, } from "./sync-repos.js";
49
52
  export { syncTemplates, TEMPLATE_CLAUDE_SETTINGS, TEMPLATE_ROOT_DOCS, } from "./sync-templates.js";
50
- export { TEMPLATE_SYNCED_FILES, templateSync, } from "./template-sync.js";
53
+ export { adhocReason, selectClientSlugs, TEMPLATE_RETIRED_FILES, TEMPLATE_SYNCED_FILES, templateSync, } from "./template-sync.js";
51
54
  export { TRIAGE_BACKFILL_CHUNK, triageBackfill, } from "./triage-backfill.js";
52
55
  export { checkTriageRecordWiring, detectWorkflowProvider, PORTAL_INGEST_CREDENTIAL_NAME, TRIAGE_RECORDS_PATH, triageEnable, } from "./triage-enable.js";
53
56
  export { CRITICAL_PRIORITIES, CRITICAL_URGENCIES, detectProvider, GMAIL_HEADERS, GMAIL_LANE_BY_DISPOSITION, laneFor, OUTLOOK_HEADERS, OUTLOOK_LANE_BY_CATEGORY, parseCsv, parseLaneOverrides, readRecordSheetTable, resolveRecordSheetId, SHEETS_SCOPE, seededRandom, TRIAGE_GATES, TRIAGE_LANES, TRIAGE_STAGES, triageGateSample, triageHealth, triageSoakReport, } from "./triage-gates.js";
@@ -53,6 +53,24 @@ export declare function linearRequest<T>(fetchImpl: typeof fetch, token: string,
53
53
  * `linear_project` field), never by a name a caller would have to guess.
54
54
  */
55
55
  export declare function findProjectBySlugId(fetchImpl: typeof fetch, token: string, slugId: string): Promise<ProjectNode>;
56
+ /** One issue's state, for comparing Linear with the delivery log. No title, no description. */
57
+ export interface LinearIssueState {
58
+ identifier: string;
59
+ /** triage | backlog | unstarted | started | completed | canceled (| duplicate). */
60
+ stateType: string;
61
+ updatedAt: string;
62
+ completedAt: string | null;
63
+ /** The parent issue's identifier, for a sub-issue. */
64
+ parent: string | null;
65
+ }
66
+ /**
67
+ * Every issue in a project, open AND closed, as identifier + state + dates
68
+ * only (`client-drift`'s Linear mirror check). Strictly read-only: GraphQL
69
+ * queries, never mutations. Pages until done or `maxPages`.
70
+ */
71
+ export declare function linearProjectIssueStates(fetchImpl: typeof fetch, token: string, project: ProjectNode, options?: {
72
+ maxPages?: number;
73
+ }): Promise<LinearIssueState[]>;
56
74
  /**
57
75
  * Open (not completed/canceled/duplicate) issues in an already-resolved
58
76
  * Linear project — "what's left to do" for that project. Either returns the