@installagent/sdk 0.1.0 → 0.3.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 (114) hide show
  1. package/dist/agent-mirror.d.ts +69 -0
  2. package/dist/agent-mirror.js +275 -0
  3. package/dist/agent-templates.d.ts +36 -2
  4. package/dist/agent-templates.js +173 -3
  5. package/dist/claude-hours.d.ts +118 -0
  6. package/dist/claude-hours.js +523 -0
  7. package/dist/client-drive.d.ts +3 -0
  8. package/dist/client-drive.js +2 -2
  9. package/dist/client-linear-create.d.ts +26 -0
  10. package/dist/client-linear-create.js +46 -0
  11. package/dist/client-linear.d.ts +28 -9
  12. package/dist/client-linear.js +36 -14
  13. package/dist/docs-search.d.ts +19 -6
  14. package/dist/docs-search.js +32 -11
  15. package/dist/doctor.d.ts +9 -0
  16. package/dist/doctor.js +126 -23
  17. package/dist/env-fill.d.ts +13 -0
  18. package/dist/env-fill.js +55 -13
  19. package/dist/env-push.d.ts +3 -0
  20. package/dist/env-push.js +11 -6
  21. package/dist/env-registry.d.ts +29 -0
  22. package/dist/env-registry.js +123 -9
  23. package/dist/exec.js +15 -2
  24. package/dist/git.d.ts +31 -0
  25. package/dist/git.js +59 -0
  26. package/dist/google-service-account.d.ts +20 -0
  27. package/dist/google-service-account.js +49 -0
  28. package/dist/hours-estimate.d.ts +43 -0
  29. package/dist/hours-estimate.js +159 -0
  30. package/dist/hours-export-schedule.d.ts +35 -0
  31. package/dist/hours-export-schedule.js +188 -0
  32. package/dist/hours-ledger.d.ts +129 -0
  33. package/dist/hours-ledger.js +882 -0
  34. package/dist/index.d.ts +25 -6
  35. package/dist/index.js +25 -6
  36. package/dist/linear-project.d.ts +2 -2
  37. package/dist/linear-project.js +2 -2
  38. package/dist/log.d.ts +28 -0
  39. package/dist/log.js +73 -0
  40. package/dist/n8n-executions.d.ts +85 -0
  41. package/dist/n8n-executions.js +259 -0
  42. package/dist/op-cli.d.ts +29 -0
  43. package/dist/op-cli.js +52 -0
  44. package/dist/platform.d.ts +35 -0
  45. package/dist/platform.js +39 -0
  46. package/dist/portal-admin.d.ts +108 -0
  47. package/dist/portal-admin.js +94 -1
  48. package/dist/standup.d.ts +88 -0
  49. package/dist/standup.js +235 -0
  50. package/dist/sync-repos.d.ts +54 -0
  51. package/dist/sync-repos.js +89 -0
  52. package/dist/template-sync.d.ts +11 -0
  53. package/dist/template-sync.js +16 -0
  54. package/dist/triage-backfill.d.ts +37 -0
  55. package/dist/triage-backfill.js +211 -0
  56. package/dist/triage-enable.d.ts +90 -0
  57. package/dist/triage-enable.js +428 -0
  58. package/dist/triage-gates.d.ts +252 -0
  59. package/dist/triage-gates.js +951 -0
  60. package/dist/wizard.d.ts +15 -0
  61. package/dist/wizard.js +35 -56
  62. package/dist/workspace-docs.d.ts +44 -0
  63. package/dist/workspace-docs.js +73 -0
  64. package/dist/workspace-push.d.ts +39 -0
  65. package/dist/workspace-push.js +78 -0
  66. package/dist/workspace-status.d.ts +37 -0
  67. package/dist/workspace-status.js +114 -0
  68. package/package.json +2 -2
  69. package/templates/env.example +37 -23
  70. package/templates/workspace-root/.claude/settings.json +12 -1
  71. package/templates/workspace-root/AGENT.md +7 -5
  72. package/templates/workspace-root/ONBOARDING.md +65 -8
  73. package/templates/workspace-root/skills/.github/workflows/pr-to-slack.yml +127 -0
  74. package/templates/workspace-root/skills/CLAUDE.md +29 -6
  75. package/templates/workspace-root/skills/README.md +171 -0
  76. package/templates/workspace-root/skills/ad-machine/SKILL.md +140 -0
  77. package/templates/workspace-root/skills/backtest-acceptance-gates/SKILL.md +293 -0
  78. package/templates/workspace-root/skills/backtest-acceptance-gates/backtest-acceptance-gates-guide.pdf +0 -0
  79. package/templates/workspace-root/skills/backtest-acceptance-gates/references/evidence-record-template.md +128 -0
  80. package/templates/workspace-root/skills/backtest-acceptance-gates/references/harness-checklist.md +90 -0
  81. package/templates/workspace-root/skills/client-deliverables/SKILL.md +1 -1
  82. package/templates/workspace-root/skills/client-deliverables/references/package-layout.md +3 -2
  83. package/templates/workspace-root/skills/client-latest/SKILL.md +343 -0
  84. package/templates/workspace-root/skills/client-latest/catchup.command.md +18 -0
  85. package/templates/workspace-root/skills/cloud-devops/SKILL.md +235 -0
  86. package/templates/workspace-root/skills/email-triage-rollout/SKILL.md +258 -0
  87. package/templates/workspace-root/skills/engagement-spec/SKILL.md +51 -18
  88. package/templates/workspace-root/skills/engagement-spec/references/spec-templates.md +10 -4
  89. package/templates/workspace-root/skills/gcloud-cli-setup/SKILL.md +100 -0
  90. package/templates/workspace-root/skills/github-profile/SKILL.md +106 -0
  91. package/templates/workspace-root/skills/google-chat-app-setup/SKILL.md +136 -0
  92. package/templates/workspace-root/skills/google-chat-app-setup/google-chat-app-setup-guide.pdf +0 -0
  93. package/templates/workspace-root/skills/house-voice/SKILL.md +80 -4
  94. package/templates/workspace-root/skills/ia-cli/SKILL.md +49 -7
  95. package/templates/workspace-root/skills/init_repo/SKILL.md +188 -0
  96. package/templates/workspace-root/skills/installagent-brand-kit/SKILL.md +59 -10
  97. package/templates/workspace-root/skills/installagent-brand-kit/assets/installagent-deck-template.pptx +0 -0
  98. package/templates/workspace-root/skills/installagent-brand-kit/references/deck-guide.md +181 -0
  99. package/templates/workspace-root/skills/installagent-brand-kit/scripts/deck.py +652 -0
  100. package/templates/workspace-root/skills/installagent-brand-kit/scripts/deck_lint.py +201 -0
  101. package/templates/workspace-root/skills/installagent-brand-kit/scripts/logo_raster.py +102 -0
  102. package/templates/workspace-root/skills/installagent-brand-kit/scripts/make_deck_template.py +290 -0
  103. package/templates/workspace-root/skills/salesforce-api-snapshot/SKILL.md +379 -0
  104. package/templates/workspace-root/skills/salesforce-api-snapshot/references/schema-discovery-soql.md +153 -0
  105. package/templates/workspace-root/skills/salesforce-api-snapshot/references/snapshot-storage.md +122 -0
  106. package/templates/workspace-root/skills/salesforce-api-snapshot/salesforce-api-snapshot-guide.pdf +0 -0
  107. package/templates/workspace-root/skills/slack-voice/SKILL.md +158 -0
  108. package/templates/workspace-root/skills/sso-gated-client-app/SKILL.md +337 -0
  109. package/templates/workspace-root/skills/sso-gated-client-app/sso-gated-client-app-guide.pdf +0 -0
  110. package/templates/workspace-root/skills/tech-call-prep/SKILL.md +146 -47
  111. package/templates/workspace-root/skills/vendor-feed-ingestion/SKILL.md +323 -0
  112. package/templates/workspace-root/skills/vendor-feed-ingestion/references/delivery-contract-template.md +110 -0
  113. package/templates/workspace-root/skills/vendor-feed-ingestion/references/feed-guards.md +134 -0
  114. package/templates/workspace-root/skills/vendor-feed-ingestion/vendor-feed-ingestion-guide.pdf +0 -0
@@ -0,0 +1,235 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { parseLinearProjectSlugId } from "./client-linear.js";
4
+ import { execFailureDetail, execFileAsync } from "./exec.js";
5
+ import { findProjectBySlugId, LINEAR_API_TOKEN_ENV, linearProjectIssues, } from "./linear-project.js";
6
+ import { createLogger } from "./log.js";
7
+ // `ia standup` — the cross-client "where do I start this morning?" report.
8
+ // Scope decided 2026-08-22 (docs/standup-plan.md): all local
9
+ // clients/client-* checkouts, Linear on by default with graceful skip,
10
+ // registry reads limited to calls/ file NAMES and mtimes (never content),
11
+ // and report-only — this module must never gain a write or an --apply.
12
+ /** Same field CLIENT.md records for client-linear — parsed locally here. */
13
+ const LINEAR_PROJECT_FIELD_PATTERN = /^linear_project:\s*(\S+)\s*$/m;
14
+ /** Call-note files are ISO-dated: YYYY-MM-DD.md or YYYY-MM-DD-<hint>.md. */
15
+ const CALL_DATE_PATTERN = /^(\d{4}-\d{2}-\d{2})/;
16
+ const DATE_PATTERN = /\b20\d{2}-\d{2}-\d{2}\b/g;
17
+ const DAY_MS = 24 * 60 * 60 * 1000;
18
+ /** Fetch enough open issues that the counts are honest, then summarize. */
19
+ const LINEAR_COUNT_LIMIT = 250;
20
+ const STALE_TODO_DAYS = 30;
21
+ const log = createLogger("sdk.standup");
22
+ function parseGitPorcelain(output) {
23
+ const state = { staged: 0, unstaged: 0, untracked: 0 };
24
+ for (const line of output.split("\n")) {
25
+ if (line.length < 2)
26
+ continue;
27
+ const x = line[0];
28
+ const y = line[1];
29
+ if (x === "?" && y === "?") {
30
+ state.untracked += 1;
31
+ continue;
32
+ }
33
+ if (x !== " ")
34
+ state.staged += 1;
35
+ if (y !== " ")
36
+ state.unstaged += 1;
37
+ }
38
+ return state;
39
+ }
40
+ function ageDays(isoDate, now) {
41
+ const then = Date.parse(`${isoDate}T00:00:00Z`);
42
+ return Math.max(0, Math.floor((now.getTime() - then) / DAY_MS));
43
+ }
44
+ function lastShippedDate(repoDir) {
45
+ const logPath = join(repoDir, "docs", "00-delivery-log.md");
46
+ if (!existsSync(logPath))
47
+ return null;
48
+ const dates = readFileSync(logPath, "utf8").match(DATE_PATTERN);
49
+ if (!dates || dates.length === 0)
50
+ return null;
51
+ return [...dates].sort().at(-1) ?? null;
52
+ }
53
+ /**
54
+ * Registry read, deliberately minimal: call file NAMES (for their ISO date
55
+ * prefix) and the agenda file's mtime. Never call content — that boundary is
56
+ * part of the decided scope, not an optimization.
57
+ */
58
+ function callPrep(workspaceDir, slug, repoDir) {
59
+ const registryDir = join(workspaceDir, "team-clients", "clients", slug);
60
+ if (!existsSync(registryDir))
61
+ return { status: "no-registry" };
62
+ const callsDir = join(registryDir, "calls");
63
+ const callDates = existsSync(callsDir)
64
+ ? readdirSync(callsDir)
65
+ .map((file) => CALL_DATE_PATTERN.exec(file)?.[1])
66
+ .filter((date) => Boolean(date))
67
+ .sort()
68
+ : [];
69
+ const latestCall = callDates.at(-1);
70
+ if (!latestCall)
71
+ return { status: "no-calls" };
72
+ const agendaPath = join(repoDir, "docs", "05-call-agenda.md");
73
+ if (!existsSync(agendaPath))
74
+ return { status: "missing-agenda", latestCall };
75
+ const agendaDay = statSync(agendaPath).mtime.toISOString().slice(0, 10);
76
+ return { status: agendaDay < latestCall ? "stale" : "fresh", latestCall };
77
+ }
78
+ async function linearSummary(repoDir, slug, enabled, token, fetchImpl) {
79
+ if (!enabled || !token) {
80
+ return { status: "skipped", reason: token ? "offline" : `$${LINEAR_API_TOKEN_ENV} not set` };
81
+ }
82
+ const clientMdPath = join(repoDir, "CLIENT.md");
83
+ if (!existsSync(clientMdPath)) {
84
+ return { status: "skipped", reason: "no CLIENT.md" };
85
+ }
86
+ const url = LINEAR_PROJECT_FIELD_PATTERN.exec(readFileSync(clientMdPath, "utf8"))?.[1];
87
+ if (!url) {
88
+ return { status: "skipped", reason: "no linear_project in CLIENT.md" };
89
+ }
90
+ if (!url.startsWith("http")) {
91
+ // Scaffolded-but-unfilled CLIENT.md (e.g. "<LINEAR_PROJECT_URL_HERE>").
92
+ return { status: "skipped", reason: "linear_project not filled in CLIENT.md" };
93
+ }
94
+ const slugId = parseLinearProjectSlugId(url);
95
+ if (!slugId) {
96
+ return { status: "skipped", reason: "no linear_project in CLIENT.md" };
97
+ }
98
+ try {
99
+ const project = await findProjectBySlugId(fetchImpl, token, slugId);
100
+ const { issues } = await linearProjectIssues(fetchImpl, token, project, {
101
+ limit: LINEAR_COUNT_LIMIT,
102
+ });
103
+ const next = issues[0];
104
+ return {
105
+ status: "ok",
106
+ open: issues.length,
107
+ inProgress: issues.filter((issue) => issue.stateType === "started").length,
108
+ next: next ? { identifier: next.identifier, title: next.title, state: next.state } : null,
109
+ };
110
+ }
111
+ catch (error) {
112
+ // One client's Linear hiccup must not sink the whole morning report.
113
+ log.debug("linear-summary-failed", { slug });
114
+ return { status: "error", reason: error instanceof Error ? error.message : String(error) };
115
+ }
116
+ }
117
+ function staleTodos(workspaceDir, now) {
118
+ const found = [];
119
+ for (const entry of readdirSync(workspaceDir, { withFileTypes: true })) {
120
+ if (!entry.isDirectory())
121
+ continue;
122
+ const todoDir = join(workspaceDir, entry.name, "todo");
123
+ if (!existsSync(todoDir))
124
+ continue;
125
+ for (const file of readdirSync(todoDir)) {
126
+ if (!file.endsWith(".md") || file.toLowerCase() === "readme.md")
127
+ continue;
128
+ const days = Math.floor((now.getTime() - statSync(join(todoDir, file)).mtime.getTime()) / DAY_MS);
129
+ if (days >= STALE_TODO_DAYS) {
130
+ found.push({ file: `${entry.name}/todo/${file}`, ageDays: days });
131
+ }
132
+ }
133
+ }
134
+ return found.sort((a, b) => b.ageDays - a.ageDays);
135
+ }
136
+ function attentionFlags(repo) {
137
+ const flags = [];
138
+ if (repo.repoLint && !repo.repoLint.ok)
139
+ flags.push("repo-lint failing");
140
+ if (repo.gitError)
141
+ flags.push("git status failed");
142
+ if (repo.git && repo.git.staged + repo.git.unstaged + repo.git.untracked > 0) {
143
+ flags.push("uncommitted work");
144
+ }
145
+ if (!repo.hooksInstalled)
146
+ flags.push("lefthook hooks not installed");
147
+ if (repo.callPrep.status === "stale" || repo.callPrep.status === "missing-agenda") {
148
+ flags.push("call prep stale");
149
+ }
150
+ return flags;
151
+ }
152
+ /**
153
+ * Cross-client morning report: for every clients/client-* checkout — git
154
+ * state, repo-lint, lefthook hooks, delivery-log recency, call-prep
155
+ * freshness, and the client's open Linear issues — plus workspace todo/
156
+ * files older than 30 days. Strictly read-only, by decision: it reports and
157
+ * never fixes (fixes route to `ia template-sync`, `npx lefthook install`,
158
+ * `ia client <slug>`). The only network calls are Linear reads, skipped
159
+ * gracefully when offline or the token is absent.
160
+ */
161
+ export async function standup(options = {}) {
162
+ const workspaceDir = resolve(options.workspaceDir ?? ".");
163
+ const execFileImpl = options.execFileImpl ?? execFileAsync;
164
+ const fetchImpl = options.fetchImpl ?? fetch;
165
+ const env = options.env ?? process.env;
166
+ const now = (options.now ?? (() => new Date()))();
167
+ const offline = options.offline ?? false;
168
+ const linearToken = options.linearToken ?? env[LINEAR_API_TOKEN_ENV];
169
+ const linearEnabled = !offline && Boolean(linearToken);
170
+ const clientsDir = join(workspaceDir, "clients");
171
+ const repoDirs = existsSync(clientsDir)
172
+ ? readdirSync(clientsDir, { withFileTypes: true })
173
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith("client-"))
174
+ .map((entry) => entry.name)
175
+ .filter((name) => name !== "client-template")
176
+ .filter((name) => existsSync(join(clientsDir, name, ".git")))
177
+ .sort()
178
+ : [];
179
+ const repos = [];
180
+ for (const name of repoDirs) {
181
+ const dir = join(clientsDir, name);
182
+ const slug = name.slice("client-".length);
183
+ let git = null;
184
+ let gitError;
185
+ try {
186
+ const { stdout } = await execFileImpl("git", ["-C", dir, "status", "--porcelain"]);
187
+ git = parseGitPorcelain(stdout);
188
+ }
189
+ catch (error) {
190
+ gitError = execFailureDetail(error).detail.split("\n")[0];
191
+ }
192
+ let repoLint = null;
193
+ const lintScript = join(dir, "ci", "repo-lint.mjs");
194
+ if (existsSync(lintScript)) {
195
+ try {
196
+ await execFileImpl(process.execPath, [lintScript, dir]);
197
+ repoLint = { ok: true };
198
+ }
199
+ catch (error) {
200
+ const { detail } = execFailureDetail(error);
201
+ repoLint = { ok: false, detail: detail.split("\n").find(Boolean) ?? "exit 1" };
202
+ }
203
+ }
204
+ const hookPath = join(dir, ".git", "hooks", "pre-commit");
205
+ const hooksInstalled = existsSync(hookPath) && readFileSync(hookPath, "utf8").includes("lefthook");
206
+ const lastShipped = lastShippedDate(dir);
207
+ const partial = {
208
+ slug,
209
+ dir,
210
+ git,
211
+ ...(gitError ? { gitError } : {}),
212
+ repoLint,
213
+ hooksInstalled,
214
+ lastShipped,
215
+ lastShippedAgeDays: lastShipped ? ageDays(lastShipped, now) : null,
216
+ callPrep: callPrep(workspaceDir, slug, dir),
217
+ linear: await linearSummary(dir, slug, linearEnabled, linearToken, fetchImpl),
218
+ };
219
+ repos.push({ ...partial, attention: attentionFlags(partial) });
220
+ }
221
+ // Most actionable first: more attention flags, then staler delivery logs.
222
+ repos.sort((a, b) => {
223
+ if (b.attention.length !== a.attention.length) {
224
+ return b.attention.length - a.attention.length;
225
+ }
226
+ return (b.lastShippedAgeDays ?? -1) - (a.lastShippedAgeDays ?? -1);
227
+ });
228
+ return {
229
+ workspaceDir,
230
+ generatedAt: now.toISOString(),
231
+ linearEnabled,
232
+ repos,
233
+ staleTodos: staleTodos(workspaceDir, now),
234
+ };
235
+ }
@@ -0,0 +1,54 @@
1
+ import { type PullFn } from "./git.js";
2
+ import { type EnvExampleStatus, type WorkspaceDocsResult } from "./workspace-docs.js";
3
+ /**
4
+ * `ia sync` — bring every repo in the workspace up to date in one command.
5
+ *
6
+ * Exists because `ia wizard --update` was the only way to pull, and it does
7
+ * more than a technician wants day to day: it also rewrites root docs and
8
+ * skills. Worse, it never touched `clients/client-*` at all, so the repos
9
+ * holding the actual client work were the ones nobody was pulling. `ia sync`
10
+ * covers every clone including those, and leaves docs alone unless asked.
11
+ *
12
+ * Never merges. Every pull is fast-forward-only, so a repo with local commits
13
+ * or a dirty tree fails loudly and keeps its work — losing a technician's
14
+ * uncommitted client changes to a convenience command would be unforgivable.
15
+ * `.env` is never read or written here.
16
+ */
17
+ export interface SyncReposOptions {
18
+ /** installagent/ workspace root. Defaults to the current dir. */
19
+ dir?: string;
20
+ /**
21
+ * Also refresh drifted root docs + skills/ from the templates (what
22
+ * `ia wizard --update` does). Default false — a plain sync only pulls git
23
+ * repos, so it can never touch a file a technician edited.
24
+ */
25
+ docs?: boolean;
26
+ /** Injectable for tests; defaults to real `git pull --ff-only`. */
27
+ pull?: PullFn;
28
+ }
29
+ export type SyncRepoStatus = "updated" | "absent" | "failed";
30
+ export interface SyncRepoResult {
31
+ /** Path relative to the workspace root, e.g. `clients/client-mpnrealty`. */
32
+ name: string;
33
+ status: SyncRepoStatus;
34
+ detail: string;
35
+ }
36
+ export interface SyncReposResult {
37
+ /** False when any repo failed to pull. */
38
+ ok: boolean;
39
+ dir: string;
40
+ repos: SyncRepoResult[];
41
+ /** Present only when `docs` was set. */
42
+ docs?: WorkspaceDocsResult;
43
+ /** Present only when `docs` was set. `.env` itself is never touched. */
44
+ envExample?: EnvExampleStatus;
45
+ nextSteps: string[];
46
+ }
47
+ /**
48
+ * Every repo `ia sync`/`ia status`/`ia push` operate on: the team repos plus
49
+ * every `clients/client-*` clone actually present on this machine. POSIX-
50
+ * separated relative paths (see `clientRepoPaths`) — split with `/` before
51
+ * joining onto a filesystem path.
52
+ */
53
+ export declare function workspaceRepoNames(workspaceDir: string): string[];
54
+ export declare function syncRepos(options?: SyncReposOptions): Promise<SyncReposResult>;
@@ -0,0 +1,89 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { gitPullFfOnly } from "./git.js";
4
+ import { WIZARD_REPO_NAMES } from "./wizard.js";
5
+ import { refreshEnvExample, refreshWorkspaceDocs, } from "./workspace-docs.js";
6
+ /**
7
+ * Every `clients/client-*` directory that is a git clone, sorted.
8
+ *
9
+ * Returns POSIX-separated relative paths deliberately, NOT `join()` output:
10
+ * these strings are the `name` a technician reads and an MCP caller matches
11
+ * on, so `clients/client-acme` must not become `clients\\client-acme` on
12
+ * Windows. Only the filesystem probe below uses platform separators.
13
+ */
14
+ function clientRepoPaths(workspaceDir) {
15
+ const clientsDir = join(workspaceDir, "clients");
16
+ if (!existsSync(clientsDir))
17
+ return [];
18
+ return readdirSync(clientsDir, { withFileTypes: true })
19
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith("client-"))
20
+ .map((entry) => `clients/${entry.name}`)
21
+ .filter((rel) => existsSync(join(workspaceDir, ...rel.split("/"), ".git")))
22
+ .sort();
23
+ }
24
+ /**
25
+ * Every repo `ia sync`/`ia status`/`ia push` operate on: the team repos plus
26
+ * every `clients/client-*` clone actually present on this machine. POSIX-
27
+ * separated relative paths (see `clientRepoPaths`) — split with `/` before
28
+ * joining onto a filesystem path.
29
+ */
30
+ export function workspaceRepoNames(workspaceDir) {
31
+ return [...WIZARD_REPO_NAMES.map(String), ...clientRepoPaths(workspaceDir)];
32
+ }
33
+ export async function syncRepos(options = {}) {
34
+ const dir = resolve(options.dir ?? ".");
35
+ const pull = options.pull ?? gitPullFfOnly;
36
+ const withDocs = options.docs ?? false;
37
+ // Team repos first (team-tools carries the templates a --docs refresh
38
+ // reads, so it must be current before the docs step runs), then every
39
+ // client clone the technician actually has.
40
+ const targets = workspaceRepoNames(dir);
41
+ const repos = [];
42
+ for (const rel of targets) {
43
+ // rel is always POSIX (see clientRepoPaths); split it back out so the
44
+ // filesystem sees native separators.
45
+ const path = join(dir, ...rel.split("/"));
46
+ if (!existsSync(join(path, ".git"))) {
47
+ repos.push({
48
+ name: rel,
49
+ status: "absent",
50
+ detail: "not cloned on this machine — `ia wizard` clones the team repos",
51
+ });
52
+ continue;
53
+ }
54
+ try {
55
+ await pull(path);
56
+ repos.push({ name: rel, status: "updated", detail: "pulled (fast-forward only)" });
57
+ }
58
+ catch (error) {
59
+ repos.push({
60
+ name: rel,
61
+ status: "failed",
62
+ detail: String(error instanceof Error ? error.message : error),
63
+ });
64
+ }
65
+ }
66
+ const docs = withDocs ? await refreshWorkspaceDocs(dir, { overwrite: true }) : undefined;
67
+ const envExample = withDocs ? await refreshEnvExample(dir, { overwrite: true }) : undefined;
68
+ const failed = repos.filter((repo) => repo.status === "failed");
69
+ const nextSteps = [];
70
+ if (failed.length > 0) {
71
+ nextSteps.push(`${failed.length} repo(s) would not fast-forward — commit, stash or push your work in ${failed
72
+ .map((repo) => repo.name)
73
+ .join(", ")}, then re-run \`ia sync\` (nothing was merged or discarded)`);
74
+ }
75
+ if (!withDocs) {
76
+ nextSteps.push("`ia sync --docs` also refreshes the root docs, skills/ and .env.example");
77
+ }
78
+ if (nextSteps.length === 0) {
79
+ nextSteps.push(`run \`ia doctor -w ${dir}\` if anything looks off`);
80
+ }
81
+ return {
82
+ ok: failed.length === 0,
83
+ dir,
84
+ repos,
85
+ ...(docs ? { docs } : {}),
86
+ ...(envExample ? { envExample } : {}),
87
+ nextSteps,
88
+ };
89
+ }
@@ -18,6 +18,17 @@
18
18
  * and onboarding.html are deliberately NOT here: they're per-client by
19
19
  * design, so byte-drift is expected, and repo-lint already enforces their
20
20
  * presence.
21
+ *
22
+ * pr-to-slack.yml (added 2026-08-22, switched from the fantomă webhook to
23
+ * @Agent Zero 2026-08-26) is the review notification every repo posts to
24
+ * Slack's #notify-prs. It carries no client-specific content — the repo name
25
+ * comes from the GitHub event and the posting token from an org-level secret
26
+ * — so it syncs verbatim. Keeping it here matters more than for the lint
27
+ * chain: a per-repo edit to the Block Kit payload silently changes what the
28
+ * reviewer sees, and the pr_merge/pr_close button `value` carries the
29
+ * owner/repo/PR number as JSON for Agent Zero to act on, so a repo that
30
+ * drops or reshapes that block breaks its own buttons with no error
31
+ * anywhere.
21
32
  */
22
33
  export declare const TEMPLATE_SYNCED_FILES: string[];
23
34
  export interface TemplateSyncOptions {
@@ -21,6 +21,17 @@ import { dirname, join, resolve } from "node:path";
21
21
  * and onboarding.html are deliberately NOT here: they're per-client by
22
22
  * design, so byte-drift is expected, and repo-lint already enforces their
23
23
  * presence.
24
+ *
25
+ * pr-to-slack.yml (added 2026-08-22, switched from the fantomă webhook to
26
+ * @Agent Zero 2026-08-26) is the review notification every repo posts to
27
+ * Slack's #notify-prs. It carries no client-specific content — the repo name
28
+ * comes from the GitHub event and the posting token from an org-level secret
29
+ * — so it syncs verbatim. Keeping it here matters more than for the lint
30
+ * chain: a per-repo edit to the Block Kit payload silently changes what the
31
+ * reviewer sees, and the pr_merge/pr_close button `value` carries the
32
+ * owner/repo/PR number as JSON for Agent Zero to act on, so a repo that
33
+ * drops or reshapes that block breaks its own buttons with no error
34
+ * anywhere.
24
35
  */
25
36
  export const TEMPLATE_SYNCED_FILES = [
26
37
  "CADENCE.md",
@@ -28,6 +39,11 @@ export const TEMPLATE_SYNCED_FILES = [
28
39
  "ci/repo-lint.test.mjs",
29
40
  "lefthook.yml",
30
41
  ".github/workflows/repo-lint.yml",
42
+ ".github/workflows/pr-to-slack.yml",
43
+ // The generic kickoff deck the technician presents on the first call. Same
44
+ // file in every client repo, never edited per client — client specifics go
45
+ // in that repo's onboarding.html.
46
+ "docs/kickoff-presentation.html",
31
47
  ];
32
48
  /**
33
49
  * Compare (and optionally fix) the shared infra files every client-<slug>
@@ -0,0 +1,37 @@
1
+ import { type PortalAdminOptions } from "./portal-admin.js";
2
+ import { type TriageProvider, type TriageSourceOptions } from "./triage-gates.js";
3
+ /** The portal accepts 1–500 rows a request; 200 keeps each body far below its cap. */
4
+ export declare const TRIAGE_BACKFILL_CHUNK = 200;
5
+ export interface TriageBackfillOptions extends Pick<TriageSourceOptions, "csv" | "sheetId" | "workspaceDir" | "serviceAccountKey" | "fetchImpl" | "now"> {
6
+ /** Portal agent slug — needed only when the org has more than one triage agent. */
7
+ agent?: string;
8
+ /** Portal admin API access; the secret defaults to $IA_PORTAL_ADMIN_SECRET. */
9
+ portal?: Omit<PortalAdminOptions, "fetchImpl">;
10
+ /** Read and count only; send nothing. */
11
+ dryRun?: boolean;
12
+ /**
13
+ * A JSON file with the 🧺 Batch Record Rows output of an n8n execution —
14
+ * `{ rows: […] }`, the batch object, n8n's copied item list, or a bare array
15
+ * of rows — instead of a sheet.
16
+ */
17
+ rowsFile?: string;
18
+ }
19
+ export interface TriageBackfillResult {
20
+ slug: string;
21
+ provider: TriageProvider;
22
+ source: string;
23
+ /** The portal agent the rows landed under (null on a dry run). */
24
+ agent: string | null;
25
+ /** Record rows found in the sheet. */
26
+ rowsInSource: number;
27
+ sent: number;
28
+ inserted: number;
29
+ duplicates: number;
30
+ /** Sheet rows with no valid recorded_at or message_id — not records, never sent. */
31
+ skipped: number;
32
+ /** Sheet columns the template does not write — dropped, because the portal refuses unknown keys. */
33
+ droppedHeaders: string[];
34
+ chunks: number;
35
+ dryRun: boolean;
36
+ }
37
+ export declare function triageBackfill(slug: string, options?: TriageBackfillOptions): Promise<TriageBackfillResult>;
@@ -0,0 +1,211 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { PORTAL_ADMIN_SECRET_ENV, PortalAdminAuthError, PortalRequestError, portalBackfillTriageRecords, portalListAgents, } from "./portal-admin.js";
3
+ import { detectProvider, GMAIL_HEADERS, OUTLOOK_HEADERS, readRecordSheetTable, } from "./triage-gates.js";
4
+ // `ia triage backfill <slug>`: copy a client's classification record SHEET
5
+ // into the portal (`triage_classifications`) — the first step of moving a
6
+ // client off the sheet. The rows go over as they are (the portal's wire row
7
+ // IS the sheet row), through the portal's admin backfill door, which shares
8
+ // the ingest's validation and its idempotent insert. So a re-run inserts
9
+ // nothing, and "new: 0" on a re-run is the proof that every sheet row is in
10
+ // the portal. Reads the sheet only — never the portal as its source.
11
+ //
12
+ // `--rows <file>` is the recovery path for a client with no sheet: when a
13
+ // record POST fails, the technician copies the 🧺 Batch Record Rows output of
14
+ // that execution into a file, and this sends the same rows through the same
15
+ // door. The batch names its workflow, so rows of another client's workflow
16
+ // are refused before anything is sent.
17
+ /** The portal accepts 1–500 rows a request; 200 keeps each body far below its cap. */
18
+ export const TRIAGE_BACKFILL_CHUNK = 200;
19
+ /** A value from the n8n output as the sheet would hold it. */
20
+ function asCell(value) {
21
+ if (value === null || value === undefined)
22
+ return "";
23
+ if (Array.isArray(value))
24
+ return value.map(asCell).join("|");
25
+ if (typeof value === "object")
26
+ return JSON.stringify(value);
27
+ return String(value);
28
+ }
29
+ function isRecord(value) {
30
+ return typeof value === "object" && value !== null && !Array.isArray(value);
31
+ }
32
+ /**
33
+ * The rows and the workflow ids in a copied 🧺 Batch Record Rows output. n8n
34
+ * copies an item list (`[{…batch}]`, sometimes `[{ json: {…batch} }]`); a
35
+ * technician may also paste only the batch, only `{ rows }`, or the rows.
36
+ */
37
+ function rowsOfBatchOutput(value) {
38
+ const rows = [];
39
+ const workflowIds = new Set();
40
+ const visit = (item) => {
41
+ if (Array.isArray(item)) {
42
+ for (const entry of item)
43
+ visit(entry);
44
+ return;
45
+ }
46
+ if (!isRecord(item))
47
+ return;
48
+ if (isRecord(item.json) && Object.keys(item).every((k) => k === "json" || k === "pairedItem")) {
49
+ visit(item.json);
50
+ return;
51
+ }
52
+ if (Array.isArray(item.rows)) {
53
+ if (typeof item.workflowId === "string" && item.workflowId.trim()) {
54
+ workflowIds.add(item.workflowId.trim());
55
+ }
56
+ for (const row of item.rows)
57
+ if (isRecord(row))
58
+ rows.push(row);
59
+ return;
60
+ }
61
+ if ("message_id" in item)
62
+ rows.push(item);
63
+ };
64
+ visit(value);
65
+ return { rows, workflowIds };
66
+ }
67
+ /** The rows file as a header + body table — the shape the sheet path already sends. */
68
+ async function readRowsFileTable(path) {
69
+ let parsed;
70
+ try {
71
+ parsed = JSON.parse(await readFile(path, "utf8"));
72
+ }
73
+ catch (error) {
74
+ const reason = error instanceof Error ? error.message : String(error);
75
+ throw new Error(`cannot read the rows file ${path}: ${reason}`);
76
+ }
77
+ const { rows, workflowIds } = rowsOfBatchOutput(parsed);
78
+ if (rows.length === 0) {
79
+ throw new Error(`${path} holds no record rows — copy the OUTPUT of 🧺 Batch Record Rows (its rows[] carry ` +
80
+ "recorded_at, message_id, …) from the failed execution");
81
+ }
82
+ if (workflowIds.size > 1) {
83
+ throw new Error(`${path} mixes rows from two or more workflows (${[...workflowIds].join(", ")}) — one file per workflow`);
84
+ }
85
+ const header = [];
86
+ for (const row of rows)
87
+ for (const key of Object.keys(row))
88
+ if (!header.includes(key))
89
+ header.push(key);
90
+ return {
91
+ table: [header, ...rows.map((row) => header.map((key) => asCell(row[key])))],
92
+ workflowId: [...workflowIds][0] ?? null,
93
+ };
94
+ }
95
+ function toWireRows(provider, header, body, firstLine) {
96
+ const keys = header.map((h) => h.trim());
97
+ const allowed = provider === "gmail" ? GMAIL_HEADERS : OUTLOOK_HEADERS;
98
+ const droppedHeaders = keys.filter((k) => k && !allowed.includes(k));
99
+ const rows = [];
100
+ let skipped = 0;
101
+ body.forEach((line, index) => {
102
+ const cells = {};
103
+ for (const key of allowed) {
104
+ const column = keys.indexOf(key);
105
+ cells[key] = column === -1 ? "" : (line[column] ?? "").trim();
106
+ }
107
+ const recordedAt = new Date(cells.recorded_at ?? "");
108
+ if (Number.isNaN(recordedAt.getTime()) || !cells.message_id) {
109
+ skipped += 1;
110
+ return;
111
+ }
112
+ // Sheet row numbers count the header as row 1; a rows file counts from 1.
113
+ rows.push({ line: index + firstLine, cells });
114
+ });
115
+ return { rows, skipped, droppedHeaders };
116
+ }
117
+ /** "rows[3]: …" from the portal → the sheet row it came from. */
118
+ function refusedSheetRow(error, chunk) {
119
+ const match = /rows\[(\d+)\]/.exec(error.serverError ?? "");
120
+ const row = match ? chunk[Number(match[1])] : undefined;
121
+ return row ? row.line : null;
122
+ }
123
+ /**
124
+ * The agent of this client that reports as `workflowId`. Refuses rows from a
125
+ * workflow no agent of the client runs — the wrong file, or the wrong client.
126
+ */
127
+ async function agentOfWorkflow(slug, workflowId, wanted, portalOptions) {
128
+ const { agents } = await portalListAgents({ slug }, portalOptions);
129
+ const owner = agents.find((a) => a.workflowId === workflowId);
130
+ if (!owner) {
131
+ throw new Error(`the rows come from n8n workflow ${workflowId}, but no agent under ${slug} reports as that ` +
132
+ "workflow — the wrong file, or the wrong client. Nothing was sent.");
133
+ }
134
+ if (wanted && wanted !== owner.slug) {
135
+ throw new Error(`the rows come from ${slug}/${owner.slug} (workflow ${workflowId}), not --agent ${wanted}`);
136
+ }
137
+ return owner.slug;
138
+ }
139
+ export async function triageBackfill(slug, options = {}) {
140
+ const portalOptions = {
141
+ ...options.portal,
142
+ ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
143
+ };
144
+ if (!options.dryRun && !(portalOptions.secret ?? process.env[PORTAL_ADMIN_SECRET_ENV])) {
145
+ throw new PortalAdminAuthError(`the backfill writes to the portal — set ${PORTAL_ADMIN_SECRET_ENV} (ia env fill), or add --dry-run to only count`);
146
+ }
147
+ let record;
148
+ let agent = options.agent;
149
+ if (options.rowsFile) {
150
+ if (options.csv || options.sheetId) {
151
+ throw new Error(`pass --rows or a sheet source (--csv / --sheet), not both`);
152
+ }
153
+ const file = await readRowsFileTable(options.rowsFile);
154
+ if (file.workflowId && (portalOptions.secret ?? process.env[PORTAL_ADMIN_SECRET_ENV])) {
155
+ agent = await agentOfWorkflow(slug, file.workflowId, agent, portalOptions);
156
+ }
157
+ record = {
158
+ table: file.table,
159
+ source: `rows file ${options.rowsFile}${file.workflowId ? ` (workflow ${file.workflowId})` : ""}`,
160
+ };
161
+ }
162
+ else {
163
+ record = await readRecordSheetTable(slug, options);
164
+ }
165
+ const [header, ...body] = record.table;
166
+ if (!header)
167
+ throw new Error(`${record.source} is empty — the header row must be row 1`);
168
+ const provider = detectProvider(header);
169
+ const fromFile = options.rowsFile !== undefined;
170
+ const { rows, skipped, droppedHeaders } = toWireRows(provider, header, body, fromFile ? 1 : 2);
171
+ const rowName = (line) => fromFile ? `row ${line} of the rows file` : `sheet row ${line}`;
172
+ const rangeName = (first, last) => fromFile ? `rows ${first}–${last} of the rows file` : `sheet rows ${first}–${last}`;
173
+ const result = {
174
+ slug,
175
+ provider,
176
+ source: record.source,
177
+ agent: null,
178
+ rowsInSource: rows.length,
179
+ sent: 0,
180
+ inserted: 0,
181
+ duplicates: 0,
182
+ skipped,
183
+ droppedHeaders,
184
+ chunks: 0,
185
+ dryRun: options.dryRun === true,
186
+ };
187
+ if (options.dryRun)
188
+ return result;
189
+ for (let start = 0; start < rows.length; start += TRIAGE_BACKFILL_CHUNK) {
190
+ const chunk = rows.slice(start, start + TRIAGE_BACKFILL_CHUNK);
191
+ try {
192
+ const report = await portalBackfillTriageRecords({ org: slug, agent, rows: chunk.map((row) => row.cells) }, portalOptions);
193
+ result.agent = report.agent;
194
+ result.sent += report.received;
195
+ result.inserted += report.inserted;
196
+ result.duplicates += report.duplicates;
197
+ result.chunks += 1;
198
+ }
199
+ catch (error) {
200
+ if (!(error instanceof PortalRequestError))
201
+ throw error;
202
+ const line = refusedSheetRow(error, chunk);
203
+ const first = chunk[0]?.line ?? 0;
204
+ const last = chunk.at(-1)?.line ?? 0;
205
+ throw new Error(`the portal refused ${line ? rowName(line) : `the batch of ${rangeName(first, last)}`}: ` +
206
+ `${error.serverError ?? error.message}. ${result.sent} row(s) already sent ` +
207
+ `(${result.inserted} new) — the backfill is idempotent, so it is safe to re-run once the row is fixed.`);
208
+ }
209
+ }
210
+ return result;
211
+ }