@installagent/sdk 0.4.1 → 0.5.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 (37) hide show
  1. package/dist/agent-mirror.js +22 -10
  2. package/dist/agent-templates.d.ts +10 -12
  3. package/dist/agent-templates.js +34 -6
  4. package/dist/doctor.d.ts +11 -1
  5. package/dist/doctor.js +24 -22
  6. package/dist/index.d.ts +4 -1
  7. package/dist/index.js +4 -1
  8. package/dist/lefthook-hooks.d.ts +36 -0
  9. package/dist/lefthook-hooks.js +64 -0
  10. package/dist/n8n-defaults.d.ts +90 -0
  11. package/dist/n8n-defaults.js +153 -0
  12. package/dist/portal-admin.d.ts +104 -13
  13. package/dist/portal-admin.js +113 -28
  14. package/dist/pr-open.d.ts +45 -0
  15. package/dist/pr-open.js +98 -0
  16. package/dist/sync-repos.d.ts +8 -1
  17. package/dist/sync-repos.js +10 -9
  18. package/dist/triage-enable.js +20 -7
  19. package/package.json +1 -1
  20. package/templates/workspace-root/ONBOARDING.md +9 -7
  21. package/templates/workspace-root/skills/CLAUDE.md +4 -4
  22. package/templates/workspace-root/skills/README.md +2 -2
  23. package/templates/workspace-root/skills/ad-machine/SKILL.md +14 -18
  24. package/templates/workspace-root/skills/backtest-acceptance-gates/SKILL.md +14 -16
  25. package/templates/workspace-root/skills/client-latest/SKILL.md +14 -18
  26. package/templates/workspace-root/skills/email-triage-rollout/SKILL.md +22 -16
  27. package/templates/workspace-root/skills/engagement-spec/SKILL.md +11 -14
  28. package/templates/workspace-root/skills/engagement-spec/references/spec-templates.md +9 -0
  29. package/templates/workspace-root/skills/house-voice/SKILL.md +67 -19
  30. package/templates/workspace-root/skills/ia-cli/SKILL.md +14 -17
  31. package/templates/workspace-root/skills/installagent-brand-kit/SKILL.md +14 -20
  32. package/templates/workspace-root/skills/installagent-brand-kit/scripts/brand.py +2 -2
  33. package/templates/workspace-root/skills/salesforce-api-snapshot/SKILL.md +13 -15
  34. package/templates/workspace-root/skills/slack-voice/SKILL.md +50 -31
  35. package/templates/workspace-root/skills/sso-gated-client-app/SKILL.md +14 -15
  36. package/templates/workspace-root/skills/tech-call-prep/SKILL.md +13 -19
  37. package/templates/workspace-root/skills/vendor-feed-ingestion/SKILL.md +13 -15
@@ -53,26 +53,38 @@ function instanceMovedAfterExport(liveUpdatedAt, exportedAt) {
53
53
  return false;
54
54
  return live > exported;
55
55
  }
56
+ /**
57
+ * Pick the export's own id out of the live ids a text names. Prose also names
58
+ * OTHER workflows (a sub-workflow it calls), so the first id is not proof:
59
+ * the one whose live name equals the export's name wins; a single id is taken
60
+ * as is (the workflow may have been renamed); several with no name match is
61
+ * ambiguous, and ambiguity is null, never a guess.
62
+ */
63
+ function ownIdIn(text, exportName, liveNames) {
64
+ const candidates = [...new Set(idsIn(text).filter((id) => liveNames.has(id)))];
65
+ const byName = candidates.find((id) => liveNames.get(id) === exportName);
66
+ if (byName)
67
+ return byName;
68
+ return candidates.length === 1 ? candidates[0] : null;
69
+ }
56
70
  /**
57
71
  * The live id an export claims, if any. Checked in order of how deliberate the
58
72
  * record is: a real `id` field, then the prose fields repos use to note the
59
73
  * live instance, then the `.md` sidecar sitting next to it.
60
74
  */
61
- async function recordedIdFor(absPath, parsed, knownIds) {
75
+ async function recordedIdFor(absPath, parsed, exportName, liveNames) {
62
76
  const direct = typeof parsed.id === "string" ? parsed.id : null;
63
- if (direct && knownIds.has(direct))
77
+ if (direct && liveNames.has(direct))
64
78
  return direct;
65
79
  const prose = [parsed._export_note, parsed.description]
66
80
  .filter((v) => typeof v === "string")
67
81
  .join(" ");
68
- for (const candidate of idsIn(prose))
69
- if (knownIds.has(candidate))
70
- return candidate;
82
+ const fromProse = ownIdIn(prose, exportName, liveNames);
83
+ if (fromProse)
84
+ return fromProse;
71
85
  try {
72
86
  const sidecar = await readFile(absPath.replace(/\.json$/, ".md"), "utf8");
73
- for (const candidate of idsIn(sidecar))
74
- if (knownIds.has(candidate))
75
- return candidate;
87
+ return ownIdIn(sidecar, exportName, liveNames);
76
88
  }
77
89
  catch {
78
90
  // No sidecar is normal.
@@ -173,10 +185,10 @@ export async function checkAgentMirror(opts = {}) {
173
185
  archived: Boolean(w.isArchived),
174
186
  updatedAt: typeof w.updatedAt === "string" ? w.updatedAt : null,
175
187
  }));
176
- const knownIds = new Set(live.map((w) => w.id));
188
+ const liveNames = new Map(live.map((w) => [w.id, w.name]));
177
189
  const exports = await listExports(workspaceDir, opts.client);
178
190
  for (const exp of exports) {
179
- exp.recordedId = await recordedIdFor(exp.absPath, exp.parsed, knownIds);
191
+ exp.recordedId = await recordedIdFor(exp.absPath, exp.parsed, exp.name, liveNames);
180
192
  }
181
193
  const byId = new Map(live.map((w) => [w.id, w]));
182
194
  const byName = new Map();
@@ -14,13 +14,6 @@ export interface StrippedCredential {
14
14
  /** n8n credential TYPE (e.g. gmailOAuth2) — never the name or id. */
15
15
  type: string;
16
16
  }
17
- /**
18
- * Reduce a raw n8n workflow payload to the importable core. Everything
19
- * instance- or client-bound is dropped: ids, timestamps, tags, sharing, meta,
20
- * pinData/staticData (can embed real client payloads), per-node credentials
21
- * and webhook ids. Credential TYPES are reported so the manifest can list
22
- * what a target n8n must provide.
23
- */
24
17
  export declare function sanitizeN8nWorkflow(raw: Record<string, unknown>): {
25
18
  workflow: SanitizedWorkflow;
26
19
  strippedCredentials: StrippedCredential[];
@@ -108,6 +101,16 @@ export interface CreateFromTemplateInput {
108
101
  template: string;
109
102
  /** Where the JSON lands; defaults to the current working directory. */
110
103
  destDir?: string;
104
+ /**
105
+ * Client slug. Names the clone `<client> - <template> - <purpose>`, the
106
+ * house pattern `ia agent lint` checks. Without it the template title stays.
107
+ */
108
+ client?: string;
109
+ /**
110
+ * Error workflow id for the target n8n. Defaults to the shared instance's
111
+ * global error handler; pass the client's own when they run their own n8n.
112
+ */
113
+ errorWorkflowId?: string;
111
114
  }
112
115
  export interface CreateFromTemplateResult {
113
116
  template: string;
@@ -116,9 +119,4 @@ export interface CreateFromTemplateResult {
116
119
  workflowName: string;
117
120
  nextSteps: string[];
118
121
  }
119
- /**
120
- * Start a client build from a banked template: copy its workflow.json to
121
- * <destDir>/<template>.json, ready to import into the client's n8n. Never
122
- * overwrites.
123
- */
124
122
  export declare function createFromAgentTemplate(input: CreateFromTemplateInput, opts?: AgentBankOptions): Promise<CreateFromTemplateResult>;
@@ -5,6 +5,7 @@
5
5
  // adapters over it.
6
6
  import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
7
7
  import { join, resolve } from "node:path";
8
+ import { applyClientDefaults, DEFAULT_WORKFLOW_SETTINGS, ERROR_WORKFLOW_PLACEHOLDER, } from "./n8n-defaults.js";
8
9
  import { SLUG_PATTERN } from "./new-client.js";
9
10
  export const N8N_API_URL_ENV = "N8N_API_URL";
10
11
  export const N8N_API_KEY_ENV = "N8N_API_KEY";
@@ -16,8 +17,22 @@ export class N8nAuthError extends Error {
16
17
  * instance- or client-bound is dropped: ids, timestamps, tags, sharing, meta,
17
18
  * pinData/staticData (can embed real client payloads), per-node credentials
18
19
  * and webhook ids. Credential TYPES are reported so the manifest can list
19
- * what a target n8n must provide.
20
+ * what a target n8n must provide. Settings get the house defaults (timeout,
21
+ * error-execution saving) and the error workflow id becomes the placeholder,
22
+ * so a clone never points at the instance it was banked from.
20
23
  */
24
+ function bankSettings(raw) {
25
+ const settings = {
26
+ ...DEFAULT_WORKFLOW_SETTINGS,
27
+ ...(raw.settings ?? {}),
28
+ };
29
+ const nodes = raw.nodes ?? [];
30
+ if (nodes.some((n) => n.type === "n8n-nodes-base.errorTrigger"))
31
+ delete settings.errorWorkflow;
32
+ else
33
+ settings.errorWorkflow = ERROR_WORKFLOW_PLACEHOLDER;
34
+ return settings;
35
+ }
21
36
  export function sanitizeN8nWorkflow(raw) {
22
37
  const strippedCredentials = [];
23
38
  const nodes = (raw.nodes ?? []).map((node) => {
@@ -34,7 +49,7 @@ export function sanitizeN8nWorkflow(raw) {
34
49
  name: String(raw.name ?? ""),
35
50
  nodes,
36
51
  connections: raw.connections ?? {},
37
- settings: raw.settings ?? {},
52
+ settings: bankSettings(raw),
38
53
  },
39
54
  strippedCredentials,
40
55
  };
@@ -63,7 +78,7 @@ ${credLines}
63
78
  - [ ] Replace client-specific parameter values (search for URLs, ids, names —
64
79
  use \`REPLACE_ME_*\` placeholders in the banked copy).
65
80
  - [ ] Rename the workflow for the client, activate, register in the portal
66
- (\`ia portal create-agent\`).
81
+ (\`ia portal create-build\`).
67
82
  `;
68
83
  }
69
84
  /**
@@ -345,6 +360,7 @@ export async function searchAgentTemplates(query, opts = {}) {
345
360
  * <destDir>/<template>.json, ready to import into the client's n8n. Never
346
361
  * overwrites.
347
362
  */
363
+ const CLIENT_SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
348
364
  export async function createFromAgentTemplate(input, opts = {}) {
349
365
  const source = join(agentsDir(opts), input.template, "workflow.json");
350
366
  let json;
@@ -356,10 +372,18 @@ export async function createFromAgentTemplate(input, opts = {}) {
356
372
  const known = templates.map((t) => t.slug).join(", ") || "none banked yet";
357
373
  throw new Error(`No template "${input.template}" in the bank (${source}). Known: ${known}.`);
358
374
  }
359
- const workflowName = (JSON.parse(json).name ?? input.template).toString();
375
+ if (input.client !== undefined && !CLIENT_SLUG.test(input.client)) {
376
+ throw new Error(`--client "${input.client}" is not a slug (lowercase letters, digits and hyphens, e.g. best-materials).`);
377
+ }
378
+ const workflow = applyClientDefaults(JSON.parse(json), {
379
+ template: input.template,
380
+ client: input.client,
381
+ errorWorkflowId: input.errorWorkflowId,
382
+ });
383
+ const workflowName = String(workflow.name ?? input.template);
360
384
  const dest = join(resolve(input.destDir ?? "."), `${input.template}.json`);
361
385
  try {
362
- await writeFile(dest, json, { flag: "wx" });
386
+ await writeFile(dest, `${JSON.stringify(workflow, null, 2)}\n`, { flag: "wx" });
363
387
  }
364
388
  catch (error) {
365
389
  if (error.code === "EEXIST") {
@@ -373,9 +397,13 @@ export async function createFromAgentTemplate(input, opts = {}) {
373
397
  dest,
374
398
  workflowName,
375
399
  nextSteps: [
400
+ ...(input.client
401
+ ? []
402
+ : ["Rename it `<client-slug> - <slug> - <purpose>` (or re-run with --client <slug>)."]),
403
+ `Check it: ia agent lint ${dest}`,
376
404
  "Import the JSON into the client's n8n (Workflows → Import from file).",
377
405
  "Recreate credentials and replace REPLACE_ME_* values per the template.md manifest.",
378
- "Register it for the org: ia portal create-agent (or the portal admin UI).",
406
+ "Register it for the org: ia portal create-build (or the portal admin UI).",
379
407
  ],
380
408
  };
381
409
  }
package/dist/doctor.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type ExecFileFn } from "./exec.js";
2
+ import { type HookInstallFn } from "./lefthook-hooks.js";
2
3
  import { type PlatformInfo } from "./platform.js";
3
4
  export interface DoctorOptions {
4
5
  /** installagent/ workspace root to inspect. Defaults to the current dir. */
@@ -13,6 +14,14 @@ export interface DoctorOptions {
13
14
  fetchImpl?: typeof fetch;
14
15
  /** Injectable for tests; defaults to the running machine. Picks fix-it text. */
15
16
  platform?: PlatformInfo;
17
+ /**
18
+ * Apply the one safe fix doctor knows: run `npx lefthook install` in each
19
+ * cloned client repo that has no hook. Default false — a plain checkup
20
+ * writes nothing.
21
+ */
22
+ fix?: boolean;
23
+ /** Injectable for tests; defaults to a real `npx --yes lefthook install`. */
24
+ installHooks?: HookInstallFn;
16
25
  }
17
26
  export type DoctorStatus = "ok" | "missing" | "warn";
18
27
  export interface DoctorCheck {
@@ -44,7 +53,8 @@ export interface DoctorResult {
44
53
  * whether the root .env has a line for every registry var. Set credentials
45
54
  * are validated live against their APIs — a revoked token or expired cookie
46
55
  * reads `missing`, not green — unless `offline` is set (then presence only).
47
- * Nothing is ever written and no secret value is ever included in a result;
56
+ * Nothing is written unless `fix` is set (then only the missing client-repo
57
+ * hooks are installed), and no secret value is ever included in a result;
48
58
  * a network hiccup during validation downgrades to a warning, never a
49
59
  * failure. `ok` is false only when a core check is `missing`; role-specific
50
60
  * gaps surface as warnings.
package/dist/doctor.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, readdirSync, readFileSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import { join, resolve } from "node:path";
3
3
  import { N8N_API_KEY_ENV, N8N_API_URL_ENV } from "./agent-templates.js";
4
4
  import { AIRTABLE_API_TOKEN_ENV, GOOGLE_SERVICE_ACCOUNT_KEY_ENV } from "./client-drive.js";
@@ -7,6 +7,7 @@ import { parseEnvFile } from "./env-file.js";
7
7
  import { DEFAULT_TECH_VAULT, opSecretReference, TECH_ENV_VARS, } from "./env-registry.js";
8
8
  import { execFailureDetail, execFileAsync } from "./exec.js";
9
9
  import { GITHUB_API_TOKEN_ENV, GITHUB_TOKEN_FIX } from "./github-token.js";
10
+ import { clientCloneNames, installClientHooks, unhookedClientRepos, } from "./lefthook-hooks.js";
10
11
  import { LINEAR_API_TOKEN_ENV } from "./linear-project.js";
11
12
  import { opInstallFix, opIntegrationFix } from "./op-cli.js";
12
13
  import { detectPlatformInfo } from "./platform.js";
@@ -63,7 +64,8 @@ const WORKSPACE_CHECKS = [
63
64
  * whether the root .env has a line for every registry var. Set credentials
64
65
  * are validated live against their APIs — a revoked token or expired cookie
65
66
  * reads `missing`, not green — unless `offline` is set (then presence only).
66
- * Nothing is ever written and no secret value is ever included in a result;
67
+ * Nothing is written unless `fix` is set (then only the missing client-repo
68
+ * hooks are installed), and no secret value is ever included in a result;
67
69
  * a network hiccup during validation downgrades to a warning, never a
68
70
  * failure. `ok` is false only when a core check is `missing`; role-specific
69
71
  * gaps surface as warnings.
@@ -89,7 +91,10 @@ export async function doctor(options = {}) {
89
91
  ...(present ? {} : { fixIt: spec.fixIt }),
90
92
  });
91
93
  }
92
- checks.push(lefthookCheck(workspaceDir));
94
+ const hookFix = options.fix
95
+ ? await installClientHooks(workspaceDir, options.installHooks)
96
+ : undefined;
97
+ checks.push(lefthookCheck(workspaceDir, hookFix));
93
98
  const envFreshness = envFreshnessCheck(workspaceDir);
94
99
  if (envFreshness)
95
100
  checks.push(envFreshness);
@@ -135,44 +140,41 @@ function envFixIt(spec) {
135
140
  * silently stops enforcing the skeleton rules, and client repos are often
136
141
  * local-only so no CI catches it either.
137
142
  */
138
- function lefthookCheck(workspaceDir) {
143
+ function lefthookCheck(workspaceDir, fixed) {
139
144
  const base = {
140
145
  id: "workspace/lefthook-hooks",
141
146
  group: "workspace",
142
147
  label: "lefthook hooks in cloned client repos",
143
148
  };
144
- const clientsDir = join(workspaceDir, "clients");
145
- if (!existsSync(clientsDir)) {
149
+ if (!existsSync(join(workspaceDir, "clients"))) {
146
150
  return { ...base, status: "ok", detail: "no clients/ dir yet — nothing to check" };
147
151
  }
148
- const gitRepos = readdirSync(clientsDir, { withFileTypes: true })
149
- .filter((entry) => entry.isDirectory() && entry.name.startsWith("client-"))
150
- .map((entry) => entry.name)
151
- .filter((name) => existsSync(join(clientsDir, name, ".git")))
152
- .sort();
152
+ const gitRepos = clientCloneNames(workspaceDir);
153
153
  if (gitRepos.length === 0) {
154
154
  return { ...base, status: "ok", detail: "no client git repos cloned yet — nothing to check" };
155
155
  }
156
- const unhooked = gitRepos.filter((name) => {
157
- const hookPath = join(clientsDir, name, ".git", "hooks", "pre-commit");
158
- if (!existsSync(hookPath))
159
- return true;
160
- return !readFileSync(hookPath, "utf8").includes("lefthook");
161
- });
156
+ const installedNote = fixed && fixed.installed.length > 0
157
+ ? ` (installed now in ${fixed.installed.length}: ${fixed.installed.join(", ")})`
158
+ : "";
159
+ const unhooked = unhookedClientRepos(workspaceDir);
162
160
  if (unhooked.length === 0) {
163
161
  return {
164
162
  ...base,
165
163
  status: "ok",
166
- detail: `all ${gitRepos.length} client repo(s) have the pre-commit hook installed`,
164
+ detail: `all ${gitRepos.length} client repo(s) have the pre-commit hook installed${installedNote}`,
167
165
  };
168
166
  }
167
+ const failedNote = fixed && fixed.failed.length > 0
168
+ ? `; install failed in ${fixed.failed.map((f) => `${f.name} (${f.detail})`).join(", ")}`
169
+ : "";
169
170
  return {
170
171
  ...base,
171
172
  status: "warn",
172
- detail: `${unhooked.length} of ${gitRepos.length} client repo(s) missing the lefthook pre-commit hook: ${unhooked.join(", ")}`,
173
- fixIt: "hooks are per-clone — run `npx lefthook install` inside each listed repo (client repos carry no " +
174
- "package.json, so there is no local lefthook to call; npx fetches it. `npx` ships with Node, so the " +
175
- "same command works in PowerShell, cmd and any POSIX shell). repo-lint never runs without it",
173
+ detail: `${unhooked.length} of ${gitRepos.length} client repo(s) missing the lefthook pre-commit hook: ${unhooked.join(", ")}${installedNote}${failedNote}`,
174
+ fixIt: "`ia doctor --fix` installs them, or run `npx lefthook install` inside each listed repo (client " +
175
+ "repos carry no package.json, so there is no local lefthook to call; npx fetches it. `npx` ships " +
176
+ "with Node, so the same command works in PowerShell, cmd and any POSIX shell). repo-lint never " +
177
+ "runs without it",
176
178
  };
177
179
  }
178
180
  /**
package/dist/index.d.ts CHANGED
@@ -23,14 +23,17 @@ export { type ActivityEvent, type EstimateHoursOptions, estimateHours, HOURS_SOU
23
23
  export { type HoursExportScheduleOptions, type HoursExportScheduleResult, installHoursExportSchedule, type UninstallHoursExportScheduleOptions, uninstallHoursExportSchedule, } from "./hours-export-schedule.js";
24
24
  export { buildHoursLedger, CLIENT_FIELDS, DEFAULT_HOURS_LEDGER_DIR, type HoursLedgerConfig, type HoursLedgerData, type HoursLedgerIngest, type HoursLedgerOptions, type HoursLedgerPersonTotal, type HoursLedgerResult, type HoursLedgerRow, identityMatches, LEDGER_WINDOW_START, OTHER_LEAD_SLUG, TEAM_FIELDS, } from "./hours-ledger.js";
25
25
  export { CLIENT_TEMPLATE_URL, type InitStep, type InitWorkspaceOptions, type InitWorkspaceResult, initWorkspace, MCP_RECOMMENDATIONS, type McpRecommendation, TEAM_CLIENTS_URL, } from "./init.js";
26
+ export { type HookInstallFn, type InstallClientHooksResult, installClientHooks, unhookedClientRepos, } from "./lefthook-hooks.js";
26
27
  export { findProjectBySlugId, LINEAR_API_TOKEN_ENV, LinearAuthError, type LinearIssue, LinearProjectNotFoundError, type LinearProjectOptions, type LinearProjectResult, linearProject, linearProjectIssues, linearRequest, type ProjectNode, } from "./linear-project.js";
27
28
  export { type CreateLoggerOptions, createLogger, type LogFields, type Logger, type LogLevel, redactFields, } from "./log.js";
29
+ export { applyClientDefaults, clientWorkflowName, DEFAULT_EXECUTION_TIMEOUT_S, DEFAULT_GET_RETRY, DEFAULT_WORKFLOW_SETTINGS, ERROR_WORKFLOW_PLACEHOLDER, IA_ERROR_WORKFLOW_ID, type LintFileResult, type LintFinding, type LintOptions, lintN8nWorkflow, lintWorkflowFiles, WORKFLOW_NAME_PATTERN, } from "./n8n-defaults.js";
28
30
  export { type ExtractNodeOutputsOptions, extractNodeOutputs, listN8nExecutions, listNodesRun, type N8nExecutionDetail, type N8nExecutionStatus, type N8nExecutionSummary, type N8nExecutionsInput, type N8nExecutionsOptions, type N8nExecutionsResult, type N8nNodeOutput, unflattenExecutionData, } from "./n8n-executions.js";
29
31
  export { type NewClientOptions, type NewClientResult, newClient, SLUG_PATTERN, } from "./new-client.js";
30
32
  export { opInstallCommand, opInstallFix, opIntegrationFix } from "./op-cli.js";
31
33
  export { type PingResult, ping } from "./ping.js";
32
34
  export { detectPlatform, detectPlatformInfo, detectShell, opNeedsAnotherShell, type Platform, type PlatformInfo, type Shell, } from "./platform.js";
33
- export { DEFAULT_PORTAL_URL, PORTAL_ADMIN_SECRET_ENV, PORTAL_PASSWORD_WARNING, PORTAL_SYNC_MAX_DAYS, PORTAL_URL_ENV, type PortalAddUserInput, type PortalAddUserResult, PortalAdminAuthError, type PortalAdminOptions, type PortalAgent, type PortalAgentSyncRow, type PortalCreateAgentInput, type PortalCreateOrgInput, type PortalCreateOrgResult, type PortalListAgentsResult, type PortalListOrgsResult, type PortalOrg, type PortalOrgUser, PortalRequestError, type PortalSetAgentNameInput, type PortalSetAgentNameResult, type PortalSetAgentStatusInput, type PortalSetAgentStatusResult, type PortalSetAgentTriageResult, type PortalSetAgentWorkflowInput, type PortalSetAgentWorkflowResult, type PortalSetDriveFolderResult, type PortalSetPasswordResult, type PortalSyncRunsResult, type PortalTriageBackfillResult, type PortalTriageProvider, type PortalTriageRecordsPage, portalAddUser, portalBackfillTriageRecords, portalCreateAgent, portalCreateOrg, portalListAgents, portalListOrgs, portalReadTriageRecords, portalSetAgentName, portalSetAgentStatus, portalSetAgentTriage, portalSetAgentWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSyncRuns, } from "./portal-admin.js";
35
+ 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 PortalSetBuildStatusInput, type PortalSetDriveFolderResult, type PortalSetPasswordResult, type PortalSyncRunsResult, type PortalTriageBackfillResult, type PortalTriageProvider, type PortalTriageRecordsPage, portalAddUser, portalBackfillTriageRecords, portalBuildType, portalBuildWorkflowId, portalCreateAgent, portalCreateBuild, portalCreateOrg, portalListAgents, portalListBuilds, portalListOrgs, portalReadTriageRecords, portalSetAgentName, portalSetAgentStatus, portalSetAgentTriage, portalSetAgentWorkflow, portalSetBuildName, portalSetBuildStatus, portalSetBuildTriage, portalSetBuildWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSyncRuns, validatePortalBuildFields, } from "./portal-admin.js";
36
+ export { expectedGithubAccount, type PrOpenOptions, type PrOpenResult, parseGithubRemote, prOpen, } from "./pr-open.js";
34
37
  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";
35
38
  export { type SyncRepoResult, type SyncRepoStatus, type SyncReposOptions, type SyncReposResult, syncRepos, workspaceRepoNames, } from "./sync-repos.js";
36
39
  export { type SyncTemplatesFileResult, type SyncTemplatesFileStatus, type SyncTemplatesOptions, type SyncTemplatesResult, syncTemplates, TEMPLATE_CLAUDE_SETTINGS, TEMPLATE_ROOT_DOCS, } from "./sync-templates.js";
package/dist/index.js CHANGED
@@ -26,14 +26,17 @@ export { estimateHours, HOURS_SOURCES, LEAD_HEAVY_MINUTES, LEAD_LIGHT_MINUTES, L
26
26
  export { installHoursExportSchedule, uninstallHoursExportSchedule, } from "./hours-export-schedule.js";
27
27
  export { buildHoursLedger, CLIENT_FIELDS, DEFAULT_HOURS_LEDGER_DIR, identityMatches, LEDGER_WINDOW_START, OTHER_LEAD_SLUG, TEAM_FIELDS, } from "./hours-ledger.js";
28
28
  export { CLIENT_TEMPLATE_URL, initWorkspace, MCP_RECOMMENDATIONS, TEAM_CLIENTS_URL, } from "./init.js";
29
+ export { installClientHooks, unhookedClientRepos, } from "./lefthook-hooks.js";
29
30
  export { findProjectBySlugId, LINEAR_API_TOKEN_ENV, LinearAuthError, LinearProjectNotFoundError, linearProject, linearProjectIssues, linearRequest, } from "./linear-project.js";
30
31
  export { createLogger, redactFields, } from "./log.js";
32
+ export { applyClientDefaults, clientWorkflowName, DEFAULT_EXECUTION_TIMEOUT_S, DEFAULT_GET_RETRY, DEFAULT_WORKFLOW_SETTINGS, ERROR_WORKFLOW_PLACEHOLDER, IA_ERROR_WORKFLOW_ID, lintN8nWorkflow, lintWorkflowFiles, WORKFLOW_NAME_PATTERN, } from "./n8n-defaults.js";
31
33
  export { extractNodeOutputs, listN8nExecutions, listNodesRun, unflattenExecutionData, } from "./n8n-executions.js";
32
34
  export { newClient, SLUG_PATTERN, } from "./new-client.js";
33
35
  export { opInstallCommand, opInstallFix, opIntegrationFix } from "./op-cli.js";
34
36
  export { ping } from "./ping.js";
35
37
  export { detectPlatform, detectPlatformInfo, detectShell, opNeedsAnotherShell, } from "./platform.js";
36
- export { DEFAULT_PORTAL_URL, PORTAL_ADMIN_SECRET_ENV, PORTAL_PASSWORD_WARNING, PORTAL_SYNC_MAX_DAYS, PORTAL_URL_ENV, PortalAdminAuthError, PortalRequestError, portalAddUser, portalBackfillTriageRecords, portalCreateAgent, portalCreateOrg, portalListAgents, portalListOrgs, portalReadTriageRecords, portalSetAgentName, portalSetAgentStatus, portalSetAgentTriage, portalSetAgentWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSyncRuns, } from "./portal-admin.js";
38
+ 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, portalSetBuildName, portalSetBuildStatus, portalSetBuildTriage, portalSetBuildWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSyncRuns, validatePortalBuildFields, } from "./portal-admin.js";
39
+ export { expectedGithubAccount, parseGithubRemote, prOpen, } from "./pr-open.js";
37
40
  export { standup, } from "./standup.js";
38
41
  export { syncRepos, workspaceRepoNames, } from "./sync-repos.js";
39
42
  export { syncTemplates, TEMPLATE_CLAUDE_SETTINGS, TEMPLATE_ROOT_DOCS, } from "./sync-templates.js";
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Per-clone git hooks for `clients/client-*` repos.
3
+ *
4
+ * lefthook wires the repo-lint and secret-scan pre-commit gates, but
5
+ * `lefthook install` is manual after every clone. Client repos carry no
6
+ * package.json, so no `pnpm install` ever runs it, and many are local-only
7
+ * so no CI catches what the hook would have. On 2026-10-15, 7 of 20 client
8
+ * clones on the founder's machine had no hook. `ia doctor` reported it;
9
+ * nothing fixed it. `ia sync` and `ia doctor --fix` now install it.
10
+ */
11
+ /** Runs `npx --yes lefthook install` with `repoDir` as the working dir. */
12
+ export type HookInstallFn = (repoDir: string) => Promise<void>;
13
+ export declare const npxLefthookInstall: HookInstallFn;
14
+ /** Every `clients/client-*` directory that is a git clone, by bare name, sorted. */
15
+ export declare function clientCloneNames(workspaceDir: string): string[];
16
+ /** True when the clone's pre-commit hook is lefthook's. */
17
+ export declare function hasLefthookHook(repoDir: string): boolean;
18
+ /** Client clones (bare names) whose pre-commit hook is not lefthook's. */
19
+ export declare function unhookedClientRepos(workspaceDir: string): string[];
20
+ export interface InstallClientHooksResult {
21
+ /** Bare repo names where the hook is now installed and verified. */
22
+ installed: string[];
23
+ /** Unhooked, but no lefthook.yml in the repo — nothing to install from. */
24
+ skipped: string[];
25
+ failed: {
26
+ name: string;
27
+ detail: string;
28
+ }[];
29
+ }
30
+ /**
31
+ * Install the lefthook hooks in every unhooked client clone that carries a
32
+ * `lefthook.yml`. A clone that already has the hook is left alone, so this
33
+ * is a no-op on a healthy workspace. An install only counts when the hook
34
+ * file is there afterwards.
35
+ */
36
+ export declare function installClientHooks(workspaceDir: string, install?: HookInstallFn): Promise<InstallClientHooksResult>;
@@ -0,0 +1,64 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { execFailureDetail } from "./exec.js";
6
+ export const npxLefthookInstall = async (repoDir) => {
7
+ // npx is npx.cmd on Windows, and Node refuses to spawn a .cmd without a
8
+ // shell. The args are constants, so the shell sees no user input.
9
+ const win = process.platform === "win32";
10
+ await promisify(execFile)(win ? "npx.cmd" : "npx", ["--yes", "lefthook", "install"], {
11
+ cwd: repoDir,
12
+ shell: win,
13
+ });
14
+ };
15
+ /** Every `clients/client-*` directory that is a git clone, by bare name, sorted. */
16
+ export function clientCloneNames(workspaceDir) {
17
+ const clientsDir = join(workspaceDir, "clients");
18
+ if (!existsSync(clientsDir))
19
+ return [];
20
+ return readdirSync(clientsDir, { withFileTypes: true })
21
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith("client-"))
22
+ .map((entry) => entry.name)
23
+ .filter((name) => existsSync(join(clientsDir, name, ".git")))
24
+ .sort();
25
+ }
26
+ /** True when the clone's pre-commit hook is lefthook's. */
27
+ export function hasLefthookHook(repoDir) {
28
+ const hookPath = join(repoDir, ".git", "hooks", "pre-commit");
29
+ return existsSync(hookPath) && readFileSync(hookPath, "utf8").includes("lefthook");
30
+ }
31
+ /** Client clones (bare names) whose pre-commit hook is not lefthook's. */
32
+ export function unhookedClientRepos(workspaceDir) {
33
+ return clientCloneNames(workspaceDir).filter((name) => !hasLefthookHook(join(workspaceDir, "clients", name)));
34
+ }
35
+ /**
36
+ * Install the lefthook hooks in every unhooked client clone that carries a
37
+ * `lefthook.yml`. A clone that already has the hook is left alone, so this
38
+ * is a no-op on a healthy workspace. An install only counts when the hook
39
+ * file is there afterwards.
40
+ */
41
+ export async function installClientHooks(workspaceDir, install = npxLefthookInstall) {
42
+ const result = { installed: [], skipped: [], failed: [] };
43
+ for (const name of unhookedClientRepos(workspaceDir)) {
44
+ const repoDir = join(workspaceDir, "clients", name);
45
+ if (!existsSync(join(repoDir, "lefthook.yml"))) {
46
+ result.skipped.push(name);
47
+ continue;
48
+ }
49
+ try {
50
+ await install(repoDir);
51
+ if (hasLefthookHook(repoDir))
52
+ result.installed.push(name);
53
+ else
54
+ result.failed.push({
55
+ name,
56
+ detail: "lefthook install ran but no pre-commit hook appeared",
57
+ });
58
+ }
59
+ catch (error) {
60
+ result.failed.push({ name, detail: execFailureDetail(error).detail });
61
+ }
62
+ }
63
+ return result;
64
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * House defaults for n8n workflows, and the lint that checks them.
3
+ *
4
+ * Measured 2026-10-15 on our shared instance: 0 of 48 workflows set a
5
+ * timeout, 33 of 48 had no retry anywhere, and 3 of 14 newer workflows had no
6
+ * error workflow — including a client-facing poller with 2,861 runs. A
7
+ * workflow without an error workflow fails in silence. These defaults live in
8
+ * every bank template; `ia agent create` fills the error workflow id and
9
+ * `ia agent lint` refuses a workflow without them.
10
+ */
11
+ /** The shared instance's global error handler (`IA - global-error-handler`). */
12
+ export declare const IA_ERROR_WORKFLOW_ID = "vJt4USrJnUQG0EWo";
13
+ /** What a bank template carries instead of a real error workflow id. */
14
+ export declare const ERROR_WORKFLOW_PLACEHOLDER = "REPLACE_ME_ERROR_WORKFLOW_ID";
15
+ /**
16
+ * 30 minutes. A ceiling for a stuck run, not a budget for a normal one: the
17
+ * longest agent runs on the instance finish in a few minutes. n8n kills the
18
+ * execution at this point and the error workflow reports it.
19
+ */
20
+ export declare const DEFAULT_EXECUTION_TIMEOUT_S = 1800;
21
+ /** The workflow-level `settings` every bank template carries. */
22
+ export declare const DEFAULT_WORKFLOW_SETTINGS: {
23
+ readonly executionOrder: "v1";
24
+ readonly errorWorkflow: "REPLACE_ME_ERROR_WORKFLOW_ID";
25
+ readonly executionTimeout: 1800;
26
+ readonly saveDataErrorExecution: "all";
27
+ };
28
+ /** Node-level retry for read-only HTTP calls. Writes never retry: a retried POST can double-send. */
29
+ export declare const DEFAULT_GET_RETRY: {
30
+ readonly retryOnFail: true;
31
+ readonly maxTries: 3;
32
+ readonly waitBetweenTries: 5000;
33
+ };
34
+ /**
35
+ * `<client-slug or IA> - <slug> - <purpose>` (team-web hub, Infra → n8n).
36
+ * Slugs are lowercase kebab-case; the purpose is free text.
37
+ */
38
+ export declare const WORKFLOW_NAME_PATTERN: RegExp;
39
+ type N8nNode = {
40
+ name?: unknown;
41
+ type?: unknown;
42
+ parameters?: Record<string, unknown>;
43
+ retryOnFail?: unknown;
44
+ };
45
+ type N8nWorkflow = {
46
+ name?: unknown;
47
+ nodes?: N8nNode[];
48
+ settings?: Record<string, unknown>;
49
+ };
50
+ export type LintLevel = "error" | "warn";
51
+ export interface LintFinding {
52
+ level: LintLevel;
53
+ rule: "name-pattern" | "error-workflow" | "timeout" | "get-retry" | "unreadable";
54
+ message: string;
55
+ }
56
+ export interface LintOptions {
57
+ /**
58
+ * Lint as a bank template: the error workflow must be the placeholder (a
59
+ * real id would point every clone at our instance), and the name is a
60
+ * template title, not the client pattern.
61
+ */
62
+ template?: boolean;
63
+ }
64
+ /** An HTTP Request node whose method is GET (n8n's default when unset). */
65
+ export declare function isGetHttpNode(node: N8nNode): boolean;
66
+ export declare function lintN8nWorkflow(wf: N8nWorkflow, options?: LintOptions): LintFinding[];
67
+ /**
68
+ * Turn a bank template into a client workflow: house settings filled in, the
69
+ * placeholder replaced by a real error workflow id, and (with a client slug)
70
+ * the house name. Keys the template already sets win over the defaults.
71
+ */
72
+ export declare function applyClientDefaults(wf: Record<string, unknown>, opts: {
73
+ template: string;
74
+ client?: string;
75
+ errorWorkflowId?: string;
76
+ }): Record<string, unknown>;
77
+ /** `<client> - <template slug> - <purpose>`; the purpose is the template title without bank markers. */
78
+ export declare function clientWorkflowName(client: string, template: string, templateTitle: string): string;
79
+ export interface LintFileResult {
80
+ file: string;
81
+ findings: LintFinding[];
82
+ /** True when any finding is an error. */
83
+ failed: boolean;
84
+ }
85
+ /** `ia agent lint`: read each workflow JSON and lint it. A file that is not JSON fails. */
86
+ export declare function lintWorkflowFiles(files: string[], options?: LintOptions): Promise<{
87
+ ok: boolean;
88
+ results: LintFileResult[];
89
+ }>;
90
+ export {};