@installagent/sdk 0.9.0 → 0.10.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.
Files changed (28) hide show
  1. package/dist/agent-mirror.d.ts +28 -0
  2. package/dist/agent-mirror.js +45 -20
  3. package/dist/client-drift.d.ts +120 -0
  4. package/dist/client-drift.js +556 -0
  5. package/dist/index.d.ts +3 -2
  6. package/dist/index.js +3 -2
  7. package/dist/linear-project.d.ts +18 -0
  8. package/dist/linear-project.js +43 -0
  9. package/dist/template-sync.d.ts +14 -0
  10. package/dist/template-sync.js +27 -0
  11. package/package.json +1 -1
  12. package/templates/workspace-root/AGENT.md +2 -0
  13. package/templates/workspace-root/AGENTS.md +10 -8
  14. package/templates/workspace-root/GEMINI.md +9 -21
  15. package/templates/workspace-root/ONBOARDING.md +3 -1
  16. package/templates/workspace-root/skills/CLAUDE.md +2 -2
  17. package/templates/workspace-root/skills/README.md +12 -4
  18. package/templates/workspace-root/skills/client-facing-docs/SKILL.md +3 -0
  19. package/templates/workspace-root/skills/client-latest/SKILL.md +75 -63
  20. package/templates/workspace-root/skills/engagement-spec/SKILL.md +14 -0
  21. package/templates/workspace-root/skills/engagement-spec/references/spec-templates.md +4 -0
  22. package/templates/workspace-root/skills/house-voice/SKILL.md +172 -77
  23. package/templates/workspace-root/skills/ia-cli/SKILL.md +2 -1
  24. package/templates/workspace-root/skills/installagent-brand-kit/SKILL.md +8 -0
  25. package/templates/workspace-root/skills/installagent-brand-kit/references/branded-pdf.md +8 -1
  26. package/templates/workspace-root/skills/installagent-brand-kit/scripts/brand.py +32 -5
  27. package/templates/workspace-root/skills/slack-voice/SKILL.md +2 -2
  28. package/templates/workspace-root/skills/tech-call-prep/SKILL.md +7 -2
@@ -0,0 +1,556 @@
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, readdirSync, 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
+ /** An active scheduled workflow with no run in this many days is silent. */
32
+ export const CLIENT_DRIFT_SILENCE_DAYS = 7;
33
+ const DAY_MS = 86_400_000;
34
+ const SLUG = /^[a-z0-9][a-z0-9-]*$/;
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
+ function clientSlugs(workspaceDir, options) {
47
+ if (Boolean(options.slug) === Boolean(options.all)) {
48
+ throw new Error("client-drift needs a slug or --all (one of them, not both)");
49
+ }
50
+ const clientsDir = join(workspaceDir, "clients");
51
+ if (options.all) {
52
+ if (!existsSync(clientsDir))
53
+ return [];
54
+ return readdirSync(clientsDir, { withFileTypes: true })
55
+ .filter((e) => e.isDirectory() && e.name.startsWith("client-") && e.name !== "client-template")
56
+ .map((e) => e.name.slice("client-".length))
57
+ .sort();
58
+ }
59
+ const slug = String(options.slug).replace(/^client-/, "");
60
+ if (!SLUG.test(slug))
61
+ throw new Error(`"${options.slug}" is not a client slug (kebab-case, e.g. best-materials)`);
62
+ if (!existsSync(join(clientsDir, `client-${slug}`))) {
63
+ throw new Error(`no checkout at clients/client-${slug} under ${workspaceDir}`);
64
+ }
65
+ return [slug];
66
+ }
67
+ /** owner/repo of a GitHub remote URL (https or ssh), or null. */
68
+ function githubRepo(remote) {
69
+ const match = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(remote.trim());
70
+ return match ? `${match[1]}/${match[2]}` : null;
71
+ }
72
+ /**
73
+ * Reads n8n runs lazily and remembers them: the newest run per workflow, and
74
+ * (only when a scheduled workflow has no run kept at all) how far back the
75
+ * instance keeps runs. The first refusal stops every later call.
76
+ */
77
+ function runReader(opts, now) {
78
+ let unread = null;
79
+ let windowDays;
80
+ return {
81
+ get unread() {
82
+ return unread;
83
+ },
84
+ get windowDays() {
85
+ return windowDays ?? null;
86
+ },
87
+ async newest(workflowId) {
88
+ if (unread)
89
+ return undefined;
90
+ try {
91
+ const { executions } = await listN8nExecutions({ workflowId, limit: 1 }, opts);
92
+ return executions[0] ?? null;
93
+ }
94
+ catch (error) {
95
+ unread = message(error);
96
+ return undefined;
97
+ }
98
+ },
99
+ /** Days of runs the instance keeps; null with no runs at all; undefined when unread. */
100
+ async window() {
101
+ if (unread)
102
+ return undefined;
103
+ if (windowDays !== undefined)
104
+ return windowDays;
105
+ try {
106
+ const { executions } = await listN8nExecutions({ limit: WINDOW_SCAN_LIMIT }, opts);
107
+ const oldest = executions.at(-1)?.startedAt;
108
+ windowDays = oldest ? days(now.getTime() - Date.parse(oldest)) : null;
109
+ }
110
+ catch (error) {
111
+ unread = message(error);
112
+ return undefined;
113
+ }
114
+ return windowDays;
115
+ },
116
+ };
117
+ }
118
+ async function checkRuns(row, wf, runs, now, silenceDays, add) {
119
+ const newest = await runs.newest(wf.id);
120
+ if (newest === undefined)
121
+ return;
122
+ if (newest && (newest.status === "error" || newest.status === "crashed")) {
123
+ 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.");
124
+ }
125
+ if (!wf.scheduled)
126
+ return;
127
+ if (newest?.startedAt) {
128
+ const age = days(now.getTime() - Date.parse(newest.startedAt));
129
+ if (age > silenceDays) {
130
+ 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.");
131
+ }
132
+ return;
133
+ }
134
+ const window = await runs.window();
135
+ if (window === undefined)
136
+ return;
137
+ if (window !== null && window >= silenceDays) {
138
+ 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.");
139
+ }
140
+ else {
141
+ 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).`);
142
+ }
143
+ }
144
+ async function checkBuildsAgainstN8n(slug, workspaceDir, rows, live, runs, ctx, add, skipped) {
145
+ const byId = new Map(live.map((w) => [w.id, w]));
146
+ const mirror = await checkAgentMirror({
147
+ workspaceDir,
148
+ client: slug,
149
+ liveWorkflows: live,
150
+ execFileImpl: ctx.execFileImpl,
151
+ });
152
+ const exported = new Set(mirror.rows.map((r) => r.workflowId).filter((id) => Boolean(id)));
153
+ for (const row of rows) {
154
+ if (row.type !== "agent" || !row.workflowId)
155
+ continue;
156
+ const wf = byId.get(row.workflowId);
157
+ if (!wf) {
158
+ if (row.status !== "retired") {
159
+ 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.");
160
+ }
161
+ continue;
162
+ }
163
+ const liveState = wf.archived ? "archived" : wf.active ? "active" : "inactive";
164
+ if (row.status === "active" && liveState !== "active") {
165
+ 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).");
166
+ }
167
+ else if (row.status !== "active" && liveState === "active") {
168
+ 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.");
169
+ }
170
+ if (row.status === "active") {
171
+ const stale = STALE_NAME.test(wf.name)
172
+ ? `n8n name: "${wf.name}"`
173
+ : wf.description && STALE_NAME.test(wf.description)
174
+ ? `n8n description: "${short(wf.description, 90)}"`
175
+ : null;
176
+ if (stale) {
177
+ 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.");
178
+ }
179
+ if (!exported.has(wf.id) && !wf.archived) {
180
+ 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.");
181
+ }
182
+ if (liveState === "active")
183
+ await checkRuns(row, wf, runs, ctx.now, ctx.silenceDays, add);
184
+ }
185
+ }
186
+ for (const m of mirror.rows) {
187
+ const file = m.file?.replace(`clients/client-${slug}/`, "") ?? m.workflowName;
188
+ if (m.state === "needs-diff") {
189
+ 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.");
190
+ }
191
+ else if (m.state === "no-live-match") {
192
+ 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.");
193
+ }
194
+ }
195
+ if (mirror.rows.length > 0 && !mirror.commitTimesAvailable) {
196
+ skipped.push("stale-export: no commit time for any export (not a git checkout)");
197
+ }
198
+ }
199
+ async function checkGit(dir, statusFn, execFileImpl, add, skipped) {
200
+ if (!existsSync(join(dir, ".git"))) {
201
+ skipped.push("git: not a git checkout");
202
+ return;
203
+ }
204
+ try {
205
+ const s = await statusFn(dir);
206
+ const branch = s.branch ?? "(detached)";
207
+ const clean = "git: committed and pushed";
208
+ const hint = "Commit it as one slice with its surfaces (CADENCE.md), or discard it. Then push.";
209
+ if (s.dirty)
210
+ add("git", "drift", branch, clean, "uncommitted changes to tracked files", hint);
211
+ if (s.untracked > 0)
212
+ add("git", "drift", branch, clean, `${s.untracked} untracked path(s)`, hint);
213
+ if (s.ahead > 0)
214
+ 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).");
215
+ if (!s.upstream) {
216
+ add("git", "check", branch, "git: a branch with an upstream", "no upstream branch", "Push with -u, or check out the default branch.");
217
+ }
218
+ }
219
+ catch (error) {
220
+ skipped.push(`git status: ${message(error).split("\n")[0]}`);
221
+ }
222
+ try {
223
+ const { stdout: remote } = await execFileImpl("git", [
224
+ "-C",
225
+ dir,
226
+ "remote",
227
+ "get-url",
228
+ "origin",
229
+ ]);
230
+ const repo = githubRepo(remote);
231
+ if (!repo) {
232
+ skipped.push("open PRs: origin is not a GitHub remote");
233
+ return;
234
+ }
235
+ const { stdout } = await execFileImpl("gh", [
236
+ "pr",
237
+ "list",
238
+ "--repo",
239
+ repo,
240
+ "--state",
241
+ "open",
242
+ "--json",
243
+ "number,title,url",
244
+ "--limit",
245
+ "50",
246
+ ]);
247
+ const prs = JSON.parse(stdout || "[]");
248
+ for (const pr of prs) {
249
+ add("open-pr", "check", `#${pr.number}`, "GitHub: no open PRs", `open PR: "${short(pr.title, 70)}"`, `Review, merge or close it: ${pr.url}`);
250
+ }
251
+ }
252
+ catch (error) {
253
+ skipped.push(`open PRs: ${execFailureDetail(error).detail.split("\n")[0]}`);
254
+ }
255
+ }
256
+ async function checkLint(dir, execFileImpl, add, skipped) {
257
+ const script = join(dir, "ci", "repo-lint.mjs");
258
+ if (!existsSync(script)) {
259
+ skipped.push("repo-lint: no ci/repo-lint.mjs");
260
+ return;
261
+ }
262
+ let stderr = "";
263
+ let failed = false;
264
+ try {
265
+ ({ stderr } = await execFileImpl(process.execPath, [script, dir]));
266
+ }
267
+ catch (error) {
268
+ failed = true;
269
+ const err = error;
270
+ stderr = typeof err.stderr === "string" ? err.stderr : message(error);
271
+ }
272
+ for (const line of stderr.split("\n")) {
273
+ const match = LINT_DRIFT.exec(line.trim());
274
+ if (!match || Number(match[1]) < FIRST_DRIFT_RULE)
275
+ continue;
276
+ 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.");
277
+ }
278
+ if (failed) {
279
+ const first = stderr
280
+ .split("\n")
281
+ .map((l) => l.trim())
282
+ .find((l) => l.startsWith("✗"));
283
+ 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.");
284
+ }
285
+ }
286
+ // ── Linear: a mirror of the delivery log, never a source ─────────────────────
287
+ /** Done issues older than this are history; open ones untouched this long are stale. */
288
+ const LINEAR_RECENT_DAYS = 30;
289
+ // A heading that says the work shipped. Bare "live" is not enough ("Live sheet
290
+ // check"), and a negation cancels it ("no automation shipped yet").
291
+ const SHIPPED_WORDS = /\b(shipped|published|deployed|go-live|went live|goes live|is live|now live|live since|live on)\b/i;
292
+ const NOT_SHIPPED = /\b(no|not|never|nothing)\b[^.;:()]{0,30}\b(shipped|published|deployed|live)\b/i;
293
+ const saysShipped = (heading) => SHIPPED_WORDS.test(heading) && !NOT_SHIPPED.test(heading);
294
+ const LOG_HEADING = /^##\s+(\d{4}-\d{2}-\d{2})\b\s*(.*)$/;
295
+ const ISSUE_TOKEN = /\b[A-Z][A-Z0-9]{1,9}-\d+\b/g;
296
+ const CLOSED_STATES = new Set(["completed", "canceled", "duplicate"]);
297
+ /** Dated delivery-log entries. Fenced examples are skipped. */
298
+ function logEntries(log) {
299
+ const entries = [];
300
+ let current = null;
301
+ let fenced = false;
302
+ for (const line of log.split("\n")) {
303
+ if (/^\s*```/.test(line)) {
304
+ fenced = !fenced;
305
+ continue;
306
+ }
307
+ if (fenced)
308
+ continue;
309
+ const heading = LOG_HEADING.exec(line);
310
+ if (heading) {
311
+ const text = heading[2].replace(/^[—–-]\s*/, "").trim();
312
+ current = { date: heading[1], heading: text, tokens: new Set() };
313
+ entries.push(current);
314
+ }
315
+ else if (/^##\s/.test(line)) {
316
+ current = null;
317
+ }
318
+ if (current)
319
+ for (const match of line.matchAll(ISSUE_TOKEN))
320
+ current.tokens.add(match[0]);
321
+ }
322
+ return entries;
323
+ }
324
+ function linearRows(issues, entries, now, add) {
325
+ const age = (iso) => days(now.getTime() - Date.parse(iso));
326
+ const known = new Set(issues.map((i) => i.identifier));
327
+ // Only ids of THIS project count: a log names other teams' ids too (BM-4, INS-860).
328
+ const namedBy = new Map();
329
+ for (const entry of entries) {
330
+ for (const token of entry.tokens) {
331
+ if (known.has(token))
332
+ namedBy.set(token, [...(namedBy.get(token) ?? []), entry]);
333
+ }
334
+ }
335
+ for (const issue of issues) {
336
+ const naming = namedBy.get(issue.identifier) ?? [];
337
+ if (issue.stateType === "completed") {
338
+ if (!issue.completedAt || age(issue.completedAt) > LINEAR_RECENT_DAYS)
339
+ continue;
340
+ if (naming.length > 0 || (issue.parent && namedBy.has(issue.parent)))
341
+ continue;
342
+ 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).");
343
+ continue;
344
+ }
345
+ if (CLOSED_STATES.has(issue.stateType) || naming.length === 0)
346
+ continue;
347
+ const newest = [...naming].sort((a, b) => b.date.localeCompare(a.date))[0];
348
+ if (age(issue.updatedAt) > LINEAR_RECENT_DAYS && saysShipped(newest.heading)) {
349
+ 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.");
350
+ }
351
+ else if (age(`${newest.date}T00:00:00Z`) <= LINEAR_RECENT_DAYS) {
352
+ 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.");
353
+ }
354
+ }
355
+ }
356
+ /** Reads Linear per client. The first auth failure stops every later read. */
357
+ function linearReader(options) {
358
+ const env = options.env ?? process.env;
359
+ const token = options.linearToken ?? env[LINEAR_API_TOKEN_ENV];
360
+ const fetchImpl = options.fetchImpl ?? fetch;
361
+ let unread = null;
362
+ return {
363
+ get unread() {
364
+ return unread;
365
+ },
366
+ async check(dir, clientMd, now, add, skipped) {
367
+ const backlog = readManifestKey(clientMd, "backlog")?.split(/\s+/)[0];
368
+ const url = readManifestKey(clientMd, "linear_project")?.split(/\s+/)[0];
369
+ if (!url?.startsWith("http")) {
370
+ skipped.push(backlog
371
+ ? `Linear: no Linear project for this client (its tracker is ${backlog})`
372
+ : "Linear: no linear_project in CLIENT.md");
373
+ return;
374
+ }
375
+ if (unread)
376
+ return;
377
+ if (!token) {
378
+ unread = `$${LINEAR_API_TOKEN_ENV} not set`;
379
+ return;
380
+ }
381
+ const slugId = parseLinearProjectSlugId(url);
382
+ if (!slugId) {
383
+ skipped.push(`Linear: no project id in ${url}`);
384
+ return;
385
+ }
386
+ try {
387
+ const project = await findProjectBySlugId(fetchImpl, token, slugId);
388
+ const issues = await linearProjectIssueStates(fetchImpl, token, project);
389
+ const logPath = join(dir, "docs", "00-delivery-log.md");
390
+ const log = existsSync(logPath) ? readFileSync(logPath, "utf8") : "";
391
+ linearRows(issues, logEntries(log), now, add);
392
+ }
393
+ catch (error) {
394
+ if (error instanceof LinearAuthError)
395
+ unread = message(error);
396
+ else
397
+ skipped.push(`Linear: ${message(error).split("\n")[0]}`);
398
+ }
399
+ },
400
+ };
401
+ }
402
+ /**
403
+ * Compare one client repo (or every one) with n8n, git, Linear and its own lint.
404
+ * Never throws for a source it cannot read: the source goes into
405
+ * `unreadSources` (whole run) or the client's `skipped` list, and the other
406
+ * checks still run.
407
+ */
408
+ export async function clientDrift(options) {
409
+ const workspaceDir = resolve(options.workspaceDir ?? ".");
410
+ const slugs = clientSlugs(workspaceDir, options);
411
+ const now = (options.now ?? (() => new Date()))();
412
+ const silenceDays = options.silenceDays ?? CLIENT_DRIFT_SILENCE_DAYS;
413
+ const execFileImpl = options.execFileImpl ?? execFileAsync;
414
+ const statusFn = options.statusFn ?? gitStatus;
415
+ const n8nOpts = {
416
+ baseUrl: options.baseUrl,
417
+ apiKey: options.apiKey,
418
+ env: options.env,
419
+ fetchImpl: options.fetchImpl,
420
+ };
421
+ const unreadSources = [];
422
+ let live = null;
423
+ try {
424
+ live = await fetchLiveWorkflows(n8nOpts);
425
+ }
426
+ catch (error) {
427
+ unreadSources.push(`n8n workflows: ${message(error)}`);
428
+ }
429
+ const runs = runReader(n8nOpts, now);
430
+ const linear = linearReader(options);
431
+ const clients = [];
432
+ for (const slug of slugs) {
433
+ const dir = join(workspaceDir, "clients", `client-${slug}`);
434
+ const findings = [];
435
+ const skipped = [];
436
+ const add = (check, level, subject, sourceA, sourceB, hint) => findings.push({ client: slug, check, level, subject, sourceA, sourceB, hint });
437
+ let rows = [];
438
+ const clientMdPath = join(dir, "CLIENT.md");
439
+ const clientMd = existsSync(clientMdPath) ? readFileSync(clientMdPath, "utf8") : null;
440
+ if (clientMd === null) {
441
+ skipped.push("Builds checks: no CLIENT.md");
442
+ }
443
+ else {
444
+ const manifest = parseBuildsManifest(clientMd);
445
+ if (manifest.state === "ok")
446
+ rows = manifest.rows;
447
+ else {
448
+ const why = manifest.state === "invalid" ? `invalid (${manifest.errors[0]})` : manifest.state;
449
+ skipped.push(`Builds checks: the CLIENT.md ## Builds block is ${why}`);
450
+ }
451
+ }
452
+ if (live) {
453
+ await checkBuildsAgainstN8n(slug, workspaceDir, rows, live, runs, { now, silenceDays, execFileImpl }, add, skipped);
454
+ }
455
+ if (options.git ?? true)
456
+ await checkGit(dir, statusFn, execFileImpl, add, skipped);
457
+ await checkLint(dir, execFileImpl, add, skipped);
458
+ if (clientMd !== null && (options.linear ?? true)) {
459
+ await linear.check(dir, clientMd, now, add, skipped);
460
+ }
461
+ findings.sort((a, b) => (a.level === b.level ? 0 : a.level === "drift" ? -1 : 1));
462
+ clients.push({ slug, dir, findings, skipped });
463
+ }
464
+ if (runs.unread)
465
+ unreadSources.push(`n8n executions: ${runs.unread}`);
466
+ if (linear.unread)
467
+ unreadSources.push(`Linear: ${linear.unread}`);
468
+ const all = clients.flatMap((c) => c.findings);
469
+ return {
470
+ workspaceDir,
471
+ generatedAt: now.toISOString(),
472
+ clients,
473
+ driftCount: all.filter((f) => f.level === "drift").length,
474
+ checkCount: all.filter((f) => f.level === "check").length,
475
+ unreadSources,
476
+ executionWindowDays: runs.windowDays,
477
+ notes: [
478
+ "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.",
479
+ `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.`,
480
+ "`check` rows are prompts for a person; only `drift` rows (and unread sources) fail the run.",
481
+ ],
482
+ };
483
+ }
484
+ // ── The weekly report ────────────────────────────────────────────────────────
485
+ /** Slack mrkdwn escapes the three control characters; everything else is text. */
486
+ const slackText = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
487
+ /**
488
+ * The Slack text for a drift result, or null when there is nothing to say (no
489
+ * finding and no unread source). Internal channel only: it names clients and
490
+ * builds, never PII, never money.
491
+ */
492
+ export function formatClientDriftSlack(result) {
493
+ const withFindings = result.clients.filter((c) => c.findings.length > 0);
494
+ if (withFindings.length === 0 && result.unreadSources.length === 0)
495
+ return null;
496
+ const lines = [
497
+ `*Client drift* · ${result.generatedAt.slice(0, 10)} · ${result.driftCount} drift, ${result.checkCount} to check · ${result.clients.length} repo(s)`,
498
+ ];
499
+ for (const client of withFindings) {
500
+ // Drift rows in full; check rows only as counts — a weekly post a person
501
+ // reads, not the table (`ia client-drift --all` has every row and hint).
502
+ const drift = client.findings.filter((f) => f.level === "drift");
503
+ const checks = new Map();
504
+ for (const f of client.findings) {
505
+ if (f.level === "check")
506
+ checks.set(f.check, (checks.get(f.check) ?? 0) + 1);
507
+ }
508
+ const toCheck = [...checks].map(([check, n]) => `${n} ${check}`).join(", ");
509
+ const heading = `*${slackText(client.slug)}*`;
510
+ if (drift.length === 0) {
511
+ lines.push("", `${heading} — to check: ${toCheck}`);
512
+ continue;
513
+ }
514
+ lines.push("", heading);
515
+ for (const f of drift.slice(0, SLACK_LINES_PER_CLIENT)) {
516
+ lines.push(`• DRIFT · ${f.check} · ${slackText(f.subject)} — ${slackText(f.sourceA)} ≠ ${slackText(f.sourceB)}`);
517
+ }
518
+ const more = drift.length - SLACK_LINES_PER_CLIENT;
519
+ if (more > 0)
520
+ lines.push(`• …and ${more} more drift row(s)`);
521
+ if (toCheck)
522
+ lines.push(`• to check: ${toCheck}`);
523
+ }
524
+ if (result.unreadSources.length > 0) {
525
+ lines.push("", `_Not read, so this report is partial: ${slackText(result.unreadSources.join("; "))}_`);
526
+ }
527
+ lines.push("", "Full table and hints: `ia client-drift --all`");
528
+ return lines.join("\n");
529
+ }
530
+ /**
531
+ * Post the weekly drift report — only when `formatClientDriftSlack` has
532
+ * something to say. Throws when Slack refuses, so a scheduled run fails loudly.
533
+ */
534
+ export async function postClientDriftReport(result, opts) {
535
+ if (!opts.token)
536
+ throw new Error("posting the drift report needs a Slack bot token ($SLACK_BOT_TOKEN)");
537
+ if (!opts.channel)
538
+ throw new Error("posting the drift report needs a Slack channel id");
539
+ const text = formatClientDriftSlack(result);
540
+ if (text === null)
541
+ return { status: "empty" };
542
+ const fetchImpl = opts.fetchImpl ?? fetch;
543
+ const response = await fetchImpl("https://slack.com/api/chat.postMessage", {
544
+ method: "POST",
545
+ headers: {
546
+ authorization: `Bearer ${opts.token}`,
547
+ "content-type": "application/json; charset=utf-8",
548
+ },
549
+ body: JSON.stringify({ channel: opts.channel, text, unfurl_links: false, unfurl_media: false }),
550
+ });
551
+ const body = (await response.json().catch(() => ({})));
552
+ if (!response.ok || !body.ok) {
553
+ throw new Error(`Slack refused the drift report: ${body.error ?? `HTTP ${response.status}`}`);
554
+ }
555
+ return { status: "posted", ts: String(body.ts) };
556
+ }
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, 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";
@@ -44,7 +45,7 @@ export { expectedGithubAccount, type PrOpenOptions, type PrOpenResult, parseGith
44
45
  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
46
  export { type SyncRepoResult, type SyncRepoStatus, type SyncReposOptions, type SyncReposResult, syncRepos, workspaceRepoNames, } from "./sync-repos.js";
46
47
  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";
48
+ export { TEMPLATE_SYNC_EXCLUDED, TEMPLATE_SYNCED_FILES, type TemplateSyncFileResult, type TemplateSyncFileStatus, type TemplateSyncOptions, type TemplateSyncRepoResult, type TemplateSyncResult, templateSync, } from "./template-sync.js";
48
49
  export { TRIAGE_BACKFILL_CHUNK, type TriageBackfillOptions, type TriageBackfillResult, triageBackfill, } from "./triage-backfill.js";
49
50
  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
51
  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, 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";
@@ -47,7 +48,7 @@ export { expectedGithubAccount, parseGithubRemote, prOpen, } from "./pr-open.js"
47
48
  export { standup, } from "./standup.js";
48
49
  export { syncRepos, workspaceRepoNames, } from "./sync-repos.js";
49
50
  export { syncTemplates, TEMPLATE_CLAUDE_SETTINGS, TEMPLATE_ROOT_DOCS, } from "./sync-templates.js";
50
- export { TEMPLATE_SYNCED_FILES, templateSync, } from "./template-sync.js";
51
+ export { TEMPLATE_SYNC_EXCLUDED, TEMPLATE_SYNCED_FILES, templateSync, } from "./template-sync.js";
51
52
  export { TRIAGE_BACKFILL_CHUNK, triageBackfill, } from "./triage-backfill.js";
52
53
  export { checkTriageRecordWiring, detectWorkflowProvider, PORTAL_INGEST_CREDENTIAL_NAME, TRIAGE_RECORDS_PATH, triageEnable, } from "./triage-enable.js";
53
54
  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