@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,69 @@
1
+ import { type ExecFileFn } from "./exec.js";
2
+ export type MirrorState =
3
+ /** Export and live workflow are joined, and the export is at least as new. */
4
+ "tracked"
5
+ /** Joined, but the instance changed after this file was last committed. Diff them. */
6
+ | "needs-diff"
7
+ /** Live on the instance, in no client repo. */
8
+ | "not-exported"
9
+ /** In a client repo, no live workflow matched. Archived or deleted — the API cannot say which. */
10
+ | "no-live-match";
11
+ export interface MirrorRow {
12
+ /** Client slug, when the row came from (or matched) a client repo. */
13
+ client: string | null;
14
+ /** Path relative to the workspace root, when there is an export. */
15
+ file: string | null;
16
+ /** Live n8n id, when known — from the export's own record or the live list. */
17
+ workflowId: string | null;
18
+ workflowName: string;
19
+ state: MirrorState;
20
+ /** How the export was joined to the live workflow. `null` when unjoined. */
21
+ matchedBy: "id" | "name" | null;
22
+ liveUpdatedAt: string | null;
23
+ liveActive: boolean | null;
24
+ /** True when the live workflow is archived in n8n. Archived is not deleted. */
25
+ liveArchived: boolean | null;
26
+ /** The export's last commit time (ISO), or null outside a git checkout. */
27
+ exportedAt: string | null;
28
+ hint: string;
29
+ }
30
+ export interface MirrorSummary {
31
+ liveWorkflows: number;
32
+ exports: number;
33
+ tracked: number;
34
+ needsDiff: number;
35
+ notExported: number;
36
+ noLiveMatch: number;
37
+ /** Exports joined by name because they record no id — the fragile joins. */
38
+ nameMatched: number;
39
+ }
40
+ export interface AgentMirrorResult {
41
+ workspaceDir: string;
42
+ summary: MirrorSummary;
43
+ rows: MirrorRow[];
44
+ /**
45
+ * False when `git log` produced no commit time for any export — outside a
46
+ * checkout, or with no git. `needs-diff` cannot be evaluated without it, so
47
+ * every joined row reads `tracked` and that is NOT evidence of being current.
48
+ */
49
+ commitTimesAvailable: boolean;
50
+ notes: string[];
51
+ }
52
+ export interface AgentMirrorOptions {
53
+ /** The installagent/ workspace root (the dir that contains clients/). */
54
+ workspaceDir?: string;
55
+ /** Limit the check to one client slug (without the `client-` prefix). */
56
+ client?: string;
57
+ baseUrl?: string;
58
+ apiKey?: string;
59
+ env?: NodeJS.ProcessEnv;
60
+ fetchImpl?: typeof fetch;
61
+ /** Injectable for tests; defaults to real git via execFile. */
62
+ execFileImpl?: ExecFileFn;
63
+ }
64
+ /**
65
+ * Compare every n8n workflow against every client repo's exports. Read-only:
66
+ * it fetches the workflow list, reads files, and shells out to `git log`.
67
+ * It never writes, never touches the instance, and never exports anything.
68
+ */
69
+ export declare function checkAgentMirror(opts?: AgentMirrorOptions): Promise<AgentMirrorResult>;
@@ -0,0 +1,275 @@
1
+ // Every n8n workflow a client build depends on is supposed to have a reviewed
2
+ // copy in that client's repo under workflows/*.json. Nothing enforced it, so
3
+ // the two drifted: a 2026-09-15 audit found one live workflow in no repo at
4
+ // all, and a probe that had been renamed on the instance while its export kept
5
+ // the old name. This module is the read-only check that finds both.
6
+ //
7
+ // Two lessons from that audit are load-bearing here, and both cost a wrong
8
+ // answer before they were learned:
9
+ //
10
+ // 1. A NEWER updatedAt IS NOT DRIFT. Deactivating a workflow bumps it
11
+ // without touching the definition. Two of the three exports flagged that
12
+ // day turned out to be byte-faithful. So this module never reports
13
+ // "stale" — it reports `needs-diff`, which means "open these two and
14
+ // compare", not "this file is wrong".
15
+ // 2. MATCH ON ID, NOT ON NAME. The renamed probe was reported as a deletion
16
+ // by a name-matched pass. Exports that record their live id get an exact
17
+ // join; the rest fall back to name and are labelled `matchedBy: "name"`
18
+ // so a reader knows the join is a guess.
19
+ //
20
+ // One more trap, and this one was got WRONG first and caught by this very
21
+ // module on its first real run. The n8n REST workflow list INCLUDES archived
22
+ // workflows (they come back with isArchived: true) — it is the n8n MCP
23
+ // search tool that hides them, returning 61 of 101. An audit built on that
24
+ // tool reported three live-but-archived exports as deleted. So: read
25
+ // isArchived from the list, say "archived" when it is set, and only then is
26
+ // an unmatched export genuinely absent.
27
+ import { readdir, readFile } from "node:fs/promises";
28
+ import { basename, join } from "node:path";
29
+ import { N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError } from "./agent-templates.js";
30
+ import { execFileAsync } from "./exec.js";
31
+ /** n8n workflow ids are 16 chars of base62 — tight enough to find in prose. */
32
+ const N8N_ID = /\b[A-Za-z0-9]{16}\b/g;
33
+ /** Pull every n8n-shaped id out of a blob of text. */
34
+ function idsIn(text) {
35
+ return text.match(N8N_ID) ?? [];
36
+ }
37
+ /**
38
+ * Did the instance change after the file was last committed?
39
+ *
40
+ * Compared as instants, never as strings. `git log --format=%cI` emits a local
41
+ * offset ("2026-09-11T13:52:11-04:00") while n8n emits UTC
42
+ * ("2026-09-11T17:50:32.202Z"). Lexically the first looks older; as instants it
43
+ * is 100 seconds NEWER. Comparing the strings made every single export on a
44
+ * real workspace report `needs-diff` — the exact cry-wolf this check exists to
45
+ * avoid. Unparseable on either side means "cannot tell", which is not drift.
46
+ */
47
+ function instanceMovedAfterExport(liveUpdatedAt, exportedAt) {
48
+ if (liveUpdatedAt === null || exportedAt === null)
49
+ return false;
50
+ const live = Date.parse(liveUpdatedAt);
51
+ const exported = Date.parse(exportedAt);
52
+ if (Number.isNaN(live) || Number.isNaN(exported))
53
+ return false;
54
+ return live > exported;
55
+ }
56
+ /**
57
+ * The live id an export claims, if any. Checked in order of how deliberate the
58
+ * record is: a real `id` field, then the prose fields repos use to note the
59
+ * live instance, then the `.md` sidecar sitting next to it.
60
+ */
61
+ async function recordedIdFor(absPath, parsed, knownIds) {
62
+ const direct = typeof parsed.id === "string" ? parsed.id : null;
63
+ if (direct && knownIds.has(direct))
64
+ return direct;
65
+ const prose = [parsed._export_note, parsed.description]
66
+ .filter((v) => typeof v === "string")
67
+ .join(" ");
68
+ for (const candidate of idsIn(prose))
69
+ if (knownIds.has(candidate))
70
+ return candidate;
71
+ try {
72
+ const sidecar = await readFile(absPath.replace(/\.json$/, ".md"), "utf8");
73
+ for (const candidate of idsIn(sidecar))
74
+ if (knownIds.has(candidate))
75
+ return candidate;
76
+ }
77
+ catch {
78
+ // No sidecar is normal.
79
+ }
80
+ return null;
81
+ }
82
+ async function listExports(workspaceDir, only) {
83
+ const clientsDir = join(workspaceDir, "clients");
84
+ let entries = [];
85
+ try {
86
+ entries = await readdir(clientsDir);
87
+ }
88
+ catch {
89
+ return [];
90
+ }
91
+ const out = [];
92
+ for (const entry of entries.sort()) {
93
+ if (!entry.startsWith("client-") || entry === "client-template")
94
+ continue;
95
+ const slug = entry.slice("client-".length);
96
+ if (only && slug !== only)
97
+ continue;
98
+ const wfDir = join(clientsDir, entry, "workflows");
99
+ let files = [];
100
+ try {
101
+ files = await readdir(wfDir);
102
+ }
103
+ catch {
104
+ continue;
105
+ }
106
+ for (const file of files.sort()) {
107
+ if (!file.endsWith(".json"))
108
+ continue;
109
+ const absPath = join(wfDir, file);
110
+ let parsed;
111
+ try {
112
+ parsed = JSON.parse(await readFile(absPath, "utf8"));
113
+ }
114
+ catch {
115
+ continue; // An unparseable export is repo-lint's problem, not this check's.
116
+ }
117
+ out.push({
118
+ client: slug,
119
+ file: `clients/${entry}/workflows/${file}`,
120
+ absPath,
121
+ name: typeof parsed.name === "string" ? parsed.name : basename(file, ".json"),
122
+ parsed,
123
+ recordedId: null, // filled once the live ids are known
124
+ });
125
+ }
126
+ }
127
+ return out;
128
+ }
129
+ /** Last commit time of one file, ISO, or null outside a checkout. */
130
+ async function lastCommitIso(repoDir, relPath, execFileImpl) {
131
+ try {
132
+ const { stdout } = await execFileImpl("git", [
133
+ "-C",
134
+ repoDir,
135
+ "log",
136
+ "-1",
137
+ "--format=%cI",
138
+ "--",
139
+ relPath,
140
+ ]);
141
+ const value = stdout.trim();
142
+ return value || null;
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ }
148
+ /**
149
+ * Compare every n8n workflow against every client repo's exports. Read-only:
150
+ * it fetches the workflow list, reads files, and shells out to `git log`.
151
+ * It never writes, never touches the instance, and never exports anything.
152
+ */
153
+ export async function checkAgentMirror(opts = {}) {
154
+ const workspaceDir = opts.workspaceDir ?? ".";
155
+ const env = opts.env ?? process.env;
156
+ const baseUrl = (opts.baseUrl ?? env[N8N_API_URL_ENV])?.replace(/\/+$/, "");
157
+ const apiKey = opts.apiKey ?? env[N8N_API_KEY_ENV];
158
+ if (!baseUrl || !apiKey) {
159
+ throw new N8nAuthError(`n8n API not configured — set $${N8N_API_URL_ENV} (incl. /api/v1) and $${N8N_API_KEY_ENV} (1Password).`);
160
+ }
161
+ const fetchImpl = opts.fetchImpl ?? fetch;
162
+ const execFileImpl = opts.execFileImpl ?? execFileAsync;
163
+ const response = await fetchImpl(`${baseUrl}/workflows?limit=250`, {
164
+ headers: { "X-N8N-API-KEY": apiKey, accept: "application/json" },
165
+ });
166
+ if (!response.ok)
167
+ throw new Error(`n8n API ${response.status} listing workflows`);
168
+ const payload = (await response.json());
169
+ const live = (payload.data ?? []).map((w) => ({
170
+ id: String(w.id ?? ""),
171
+ name: String(w.name ?? ""),
172
+ active: Boolean(w.active),
173
+ archived: Boolean(w.isArchived),
174
+ updatedAt: typeof w.updatedAt === "string" ? w.updatedAt : null,
175
+ }));
176
+ const knownIds = new Set(live.map((w) => w.id));
177
+ const exports = await listExports(workspaceDir, opts.client);
178
+ for (const exp of exports) {
179
+ exp.recordedId = await recordedIdFor(exp.absPath, exp.parsed, knownIds);
180
+ }
181
+ const byId = new Map(live.map((w) => [w.id, w]));
182
+ const byName = new Map();
183
+ for (const w of live)
184
+ if (!byName.has(w.name))
185
+ byName.set(w.name, w);
186
+ const rows = [];
187
+ const claimed = new Set();
188
+ for (const exp of exports) {
189
+ const viaId = exp.recordedId ? byId.get(exp.recordedId) : undefined;
190
+ const match = viaId ?? byName.get(exp.name);
191
+ const matchedBy = viaId ? "id" : match ? "name" : null;
192
+ if (match)
193
+ claimed.add(match.id);
194
+ const exportedAt = await lastCommitIso(join(workspaceDir, "clients", `client-${exp.client}`), exp.file.replace(`clients/client-${exp.client}/`, ""), execFileImpl);
195
+ if (!match) {
196
+ rows.push({
197
+ client: exp.client,
198
+ file: exp.file,
199
+ workflowId: exp.recordedId,
200
+ workflowName: exp.name,
201
+ state: "no-live-match",
202
+ matchedBy: null,
203
+ liveUpdatedAt: null,
204
+ liveActive: null,
205
+ liveArchived: null,
206
+ exportedAt,
207
+ hint: "No live workflow matched — not even an archived one, since the REST list includes those. Either it was deleted on the instance, or this export records a name/id that never existed. Confirm in the UI before removing the file; an export is cheap history.",
208
+ });
209
+ continue;
210
+ }
211
+ const moved = instanceMovedAfterExport(match.updatedAt, exportedAt);
212
+ rows.push({
213
+ client: exp.client,
214
+ file: exp.file,
215
+ workflowId: match.id,
216
+ workflowName: match.name,
217
+ state: moved ? "needs-diff" : "tracked",
218
+ matchedBy,
219
+ liveUpdatedAt: match.updatedAt,
220
+ liveActive: match.active,
221
+ liveArchived: match.archived,
222
+ exportedAt,
223
+ hint: moved
224
+ ? "The instance changed after this file was last committed. That is a prompt to DIFF, not a verdict — deactivating a workflow bumps updatedAt without touching the definition."
225
+ : matchedBy === "name"
226
+ ? "Joined by name only — this export records no live id, so a rename on the instance would read as a deletion. Record the id in the export or its .md sidecar."
227
+ : "Export is at least as new as the instance.",
228
+ });
229
+ }
230
+ // With --client we cannot attribute an unexported live workflow to anyone:
231
+ // nothing on a workflow says which client it belongs to. Listing them all
232
+ // under a single-client run would be noise, so they are left out.
233
+ for (const w of live) {
234
+ if (claimed.has(w.id) || opts.client)
235
+ continue;
236
+ rows.push({
237
+ client: null,
238
+ file: null,
239
+ workflowId: w.id,
240
+ workflowName: w.name,
241
+ state: "not-exported",
242
+ matchedBy: null,
243
+ liveUpdatedAt: w.updatedAt,
244
+ liveActive: w.active,
245
+ liveArchived: w.archived,
246
+ exportedAt: null,
247
+ hint: "Live on the instance, in no client repo. Team-level and one-off workflows are expected here; a client build workflow is not.",
248
+ });
249
+ }
250
+ const summary = {
251
+ liveWorkflows: live.length,
252
+ exports: exports.length,
253
+ tracked: rows.filter((r) => r.state === "tracked").length,
254
+ needsDiff: rows.filter((r) => r.state === "needs-diff").length,
255
+ notExported: rows.filter((r) => r.state === "not-exported").length,
256
+ noLiveMatch: rows.filter((r) => r.state === "no-live-match").length,
257
+ nameMatched: rows.filter((r) => r.matchedBy === "name").length,
258
+ };
259
+ const commitTimesAvailable = rows.some((r) => r.exportedAt !== null);
260
+ const notes = [
261
+ "Read-only: nothing on the n8n instance was read beyond the workflow list, and nothing was written anywhere.",
262
+ "`needs-diff` means open both and compare. It is never on its own a reason to re-export.",
263
+ "`no-live-match` means no live workflow at all, archived ones included — the REST list returns archived workflows with isArchived set, unlike the n8n MCP search tool, which hides them.",
264
+ ];
265
+ if (exports.length > 0 && !commitTimesAvailable) {
266
+ notes.unshift("WARNING: no commit time could be read for any export (not a git checkout, or git is unavailable), so `needs-diff` was NOT evaluated. Every joined row reads `tracked` — that is the absence of a check, not a clean result.");
267
+ }
268
+ if (opts.client) {
269
+ notes.push(`Scoped to client "${opts.client}": live workflows with no export are NOT listed, because nothing on a workflow records which client it belongs to. Run without --client to see them.`);
270
+ }
271
+ if (summary.nameMatched > 0) {
272
+ notes.push(`${summary.nameMatched} export(s) joined by NAME because they record no live id. A rename on the instance would read as a deletion — record the id in the export or its .md sidecar.`);
273
+ }
274
+ return { workspaceDir, summary, rows, commitTimesAvailable, notes };
275
+ }
@@ -50,19 +50,33 @@ export interface SaveAgentTemplateResult {
50
50
  nodeCount: number;
51
51
  strippedCredentials: StrippedCredential[];
52
52
  manifestCreated: boolean;
53
+ /** True when this save scaffolded sop.md (an existing one is never touched). */
54
+ sopCreated: boolean;
53
55
  nextSteps: string[];
54
56
  }
55
57
  /**
56
58
  * Bank a live n8n workflow: fetch by id, sanitize, write
57
- * agents/<template>/workflow.json (+ template.md scaffold on first save; an
58
- * existing manifest is never overwritten).
59
+ * agents/<template>/workflow.json (+ template.md and sop.md scaffolds on first
60
+ * save; existing files are never overwritten).
59
61
  */
60
62
  export declare function saveAgentTemplate(input: SaveAgentTemplateInput, opts?: SaveAgentTemplateOptions): Promise<SaveAgentTemplateResult>;
63
+ /** sop.md status: absent, still the unfilled save-time scaffold, or written. */
64
+ export type SopState = "missing" | "scaffold" | "filled";
61
65
  export interface AgentTemplateInfo {
62
66
  slug: string;
63
67
  workflowName: string;
64
68
  description: string | null;
65
69
  hasManifest: boolean;
70
+ /**
71
+ * Whether the template ships a FILLED delivery SOP (sopState === "filled").
72
+ * False means the template is not deliverable yet — the SOP is missing or
73
+ * still the scaffold `save` wrote, so a technician has the machine but not
74
+ * the method (agents/AGENT.md § "The delivery SOP contract"), and callers
75
+ * surface it.
76
+ */
77
+ hasSop: boolean;
78
+ /** Distinguishes a missing sop.md from a scaffold-only one (see hasSop). */
79
+ sopState: SopState;
66
80
  }
67
81
  export interface ListAgentTemplatesResult {
68
82
  agentsDir: string;
@@ -70,6 +84,26 @@ export interface ListAgentTemplatesResult {
70
84
  }
71
85
  /** Catalog the bank: every agents/<slug>/ dir that holds a workflow.json. */
72
86
  export declare function listAgentTemplates(opts?: AgentBankOptions): Promise<ListAgentTemplatesResult>;
87
+ export interface AgentTemplateMatch extends AgentTemplateInfo {
88
+ /** Term-centered slice of template.md; empty when the template has no manifest. */
89
+ snippet: string;
90
+ }
91
+ export interface SearchAgentTemplatesResult {
92
+ agentsDir: string;
93
+ query: string;
94
+ matches: AgentTemplateMatch[];
95
+ }
96
+ export interface SearchAgentTemplatesOptions extends AgentBankOptions {
97
+ /** Max matches returned (default 5). */
98
+ limit?: number;
99
+ }
100
+ /**
101
+ * "Do we already have a workflow for X?" — rank banked templates against
102
+ * search terms, weighting slug + workflow-name hits over manifest-body hits
103
+ * (same scoring shape as docsSearch/clientBuild). Templates without a
104
+ * manifest still match on slug/name so `save` gaps stay findable.
105
+ */
106
+ export declare function searchAgentTemplates(query: string, opts?: SearchAgentTemplatesOptions): Promise<SearchAgentTemplatesResult>;
73
107
  export interface CreateFromTemplateInput {
74
108
  template: string;
75
109
  /** Where the JSON lands; defaults to the current working directory. */
@@ -66,10 +66,68 @@ ${credLines}
66
66
  (\`ia portal create-agent\`).
67
67
  `;
68
68
  }
69
+ /**
70
+ * Scaffold for the delivery SOP. Deliberately mostly questions: the SOP has to
71
+ * be written from the engagement the technician is actually in, and a
72
+ * confidently-worded template invites someone to leave the defaults in place.
73
+ * Contract: agents/AGENT.md § "The delivery SOP (`sop.md`) contract".
74
+ */
75
+ function sopScaffold(template, workflowName) {
76
+ return `# ${template} — delivery SOP
77
+
78
+ > Banked from n8n workflow “${workflowName}”. **This is a scaffold, not an
79
+ > SOP.** Fill it from the engagement you are in — a rollout method written
80
+ > from memory is the thing this file exists to prevent. Contract:
81
+ > \`agents/AGENT.md\` § *The delivery SOP contract*. Worked example:
82
+ > \`agents/email-gmail-triage/sop.md\`.
83
+
84
+ One paragraph: how many stages, roughly how long, and what the client has at
85
+ the end.
86
+
87
+ ## Preconditions
88
+
89
+ Credentials, access, client agreements, anything that must be pre-created.
90
+ A checklist. Anything missing here blocks stage 1.
91
+
92
+ - [ ] …
93
+
94
+ ## Stages
95
+
96
+ Does this automation write to a system the client depends on? Then it needs at
97
+ least an observe-only first stage and a full stage. "Deploy it and watch" is
98
+ not a stage. Selection is **one config value**, never a disabled node.
99
+
100
+ | Stage | Config value | What runs | Deliberately off | Exit gate |
101
+ |---|---|---|---|---|
102
+ | 1. | | | | |
103
+
104
+ ## Gate proof
105
+
106
+ Per promotion: the sample, the thresholds, the zero-tolerance list, and the
107
+ \`evidence/\` filename. **A gate with no number is not a gate.** Name the
108
+ errors that are never acceptable at any percentage.
109
+
110
+ ## Client comms
111
+
112
+ What we tell the client at each promotion, and over which channel. Use the
113
+ \`house-voice\` skill. A silent promotion is how a client finds out by
114
+ noticing something changed.
115
+
116
+ ## Steady state
117
+
118
+ After the last stage: who watches what, how often, and the one signal that
119
+ says it is still healthy.
120
+
121
+ ## Rollback
122
+
123
+ How to undo each stage, and the pause switch. Every action that looks
124
+ irreversible should be recoverable by one search or one config value.
125
+ `;
126
+ }
69
127
  /**
70
128
  * Bank a live n8n workflow: fetch by id, sanitize, write
71
- * agents/<template>/workflow.json (+ template.md scaffold on first save; an
72
- * existing manifest is never overwritten).
129
+ * agents/<template>/workflow.json (+ template.md and sop.md scaffolds on first
130
+ * save; existing files are never overwritten).
73
131
  */
74
132
  export async function saveAgentTemplate(input, opts = {}) {
75
133
  if (!SLUG_PATTERN.test(input.template)) {
@@ -105,6 +163,15 @@ export async function saveAgentTemplate(input, opts = {}) {
105
163
  await writeFile(manifestPath, manifestScaffold(input.template, workflow.name, strippedCredentials));
106
164
  manifestCreated = true;
107
165
  }
166
+ const sopPath = join(dir, "sop.md");
167
+ let sopCreated = false;
168
+ try {
169
+ await readFile(sopPath, "utf8");
170
+ }
171
+ catch {
172
+ await writeFile(sopPath, sopScaffold(input.template, workflow.name));
173
+ sopCreated = true;
174
+ }
108
175
  return {
109
176
  template: input.template,
110
177
  dir,
@@ -112,11 +179,15 @@ export async function saveAgentTemplate(input, opts = {}) {
112
179
  nodeCount: workflow.nodes.length,
113
180
  strippedCredentials,
114
181
  manifestCreated,
182
+ sopCreated,
115
183
  nextSteps: [
116
184
  "Review workflow.json for client-specific parameter values (replace with REPLACE_ME_*).",
117
185
  manifestCreated
118
186
  ? "Fill in the description paragraph in template.md."
119
187
  : "template.md already existed — confirm it still matches the export.",
188
+ sopCreated
189
+ ? "Fill in sop.md — stages, numbered gates, client comms, rollback. A template with an unfilled SOP is not deliverable (agents/AGENT.md)."
190
+ : "sop.md already existed — confirm its stages still match the export.",
120
191
  "Commit the template in the agents/ repo.",
121
192
  ],
122
193
  };
@@ -134,6 +205,17 @@ function manifestDescription(markdown) {
134
205
  }
135
206
  return null;
136
207
  }
208
+ // sopScaffold() hard-wraps this sentence inside a blockquote, so detection
209
+ // strips markdown quote/emphasis markup and collapses whitespace first.
210
+ const SOP_SCAFFOLD_MARKER = "This is a scaffold, not an SOP";
211
+ // Fallback for a scaffold whose intro was trimmed: the stage table still
212
+ // holds the empty placeholder row sopScaffold() wrote.
213
+ const SOP_EMPTY_STAGE_ROW = /^\|\s*1\.\s*\|\s*\|\s*\|\s*\|\s*\|\s*$/m;
214
+ /** True when sop.md is still the unfilled scaffold from sopScaffold(). */
215
+ function isSopScaffold(markdown) {
216
+ const normalized = markdown.replace(/[>*_`]/g, "").replace(/\s+/g, " ");
217
+ return normalized.includes(SOP_SCAFFOLD_MARKER) || SOP_EMPTY_STAGE_ROW.test(markdown);
218
+ }
137
219
  /** Catalog the bank: every agents/<slug>/ dir that holds a workflow.json. */
138
220
  export async function listAgentTemplates(opts = {}) {
139
221
  const dir = agentsDir(opts);
@@ -165,11 +247,99 @@ export async function listAgentTemplates(opts = {}) {
165
247
  catch {
166
248
  // manifest missing — listed anyway so `save` gaps are visible
167
249
  }
168
- templates.push({ slug: entry.name, workflowName, description, hasManifest });
250
+ let sopState = "missing";
251
+ try {
252
+ const sop = await readFile(join(dir, entry.name, "sop.md"), "utf8");
253
+ sopState = isSopScaffold(sop) ? "scaffold" : "filled";
254
+ }
255
+ catch {
256
+ // SOP missing — listed anyway; callers flag it as not-yet-deliverable
257
+ }
258
+ templates.push({
259
+ slug: entry.name,
260
+ workflowName,
261
+ description,
262
+ hasManifest,
263
+ hasSop: sopState === "filled",
264
+ sopState,
265
+ });
169
266
  }
170
267
  templates.sort((a, b) => a.slug.localeCompare(b.slug));
171
268
  return { agentsDir: dir, templates };
172
269
  }
270
+ const DEFAULT_SEARCH_LIMIT = 5;
271
+ const SNIPPET_RADIUS = 120;
272
+ function countOccurrences(text, term) {
273
+ return term ? text.split(term).length - 1 : 0;
274
+ }
275
+ function termSnippet(markdown, terms) {
276
+ const haystack = markdown.toLowerCase();
277
+ let index = -1;
278
+ for (const term of terms) {
279
+ index = haystack.indexOf(term);
280
+ if (index !== -1)
281
+ break;
282
+ }
283
+ if (index === -1)
284
+ return "";
285
+ const start = Math.max(0, index - SNIPPET_RADIUS);
286
+ const end = Math.min(markdown.length, index + SNIPPET_RADIUS);
287
+ const slice = markdown.slice(start, end).replace(/\s+/g, " ").trim();
288
+ return `${start > 0 ? "…" : ""}${slice}${end < markdown.length ? "…" : ""}`;
289
+ }
290
+ /**
291
+ * "Do we already have a workflow for X?" — rank banked templates against
292
+ * search terms, weighting slug + workflow-name hits over manifest-body hits
293
+ * (same scoring shape as docsSearch/clientBuild). Templates without a
294
+ * manifest still match on slug/name so `save` gaps stay findable.
295
+ */
296
+ export async function searchAgentTemplates(query, opts = {}) {
297
+ const trimmed = query.trim();
298
+ if (!trimmed) {
299
+ throw new Error("searchAgentTemplates needs a non-empty query — use listAgentTemplates for the full catalog.");
300
+ }
301
+ const { agentsDir: dir, templates } = await listAgentTemplates(opts);
302
+ const terms = trimmed.toLowerCase().split(/\s+/).filter(Boolean);
303
+ const limit = opts.limit ?? DEFAULT_SEARCH_LIMIT;
304
+ const scored = await Promise.all(templates.map(async (template) => {
305
+ let manifest = "";
306
+ if (template.hasManifest) {
307
+ try {
308
+ manifest = await readFile(join(dir, template.slug, "template.md"), "utf8");
309
+ }
310
+ catch {
311
+ // listed with hasManifest just above; a race here only costs the snippet
312
+ }
313
+ }
314
+ // A filled SOP is searched too, so rollout questions ("staged rollout",
315
+ // "soak week", "promotion gate") find the template that answers them.
316
+ // Scaffold-only SOPs are skipped — the boilerplate mentions stages,
317
+ // gates and rollback, so it would false-match every rollout query.
318
+ // The snippet still comes from the manifest — that's the front door.
319
+ let sop = "";
320
+ if (template.sopState === "filled") {
321
+ try {
322
+ sop = await readFile(join(dir, template.slug, "sop.md"), "utf8");
323
+ }
324
+ catch {
325
+ // same race as above; costs only this template's SOP-body score
326
+ }
327
+ }
328
+ const title = `${template.slug} ${template.workflowName}`.toLowerCase();
329
+ const body = `${manifest}\n${sop}`.toLowerCase();
330
+ let score = 0;
331
+ for (const term of terms) {
332
+ score += countOccurrences(title, term) * 5 + countOccurrences(body, term);
333
+ }
334
+ return { template, manifest, score };
335
+ }));
336
+ const matches = scored
337
+ .filter((entry) => entry.score > 0)
338
+ .sort((a, b) => b.score - a.score)
339
+ .slice(0, limit)
340
+ .map(({ template, manifest }) => ({ ...template, snippet: termSnippet(manifest, terms) }));
341
+ return { agentsDir: dir, query: trimmed, matches };
342
+ }
173
343
  /**
174
344
  * Start a client build from a banked template: copy its workflow.json to
175
345
  * <destDir>/<template>.json, ready to import into the client's n8n. Never