@installagent/sdk 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -60,7 +60,35 @@ export interface AgentMirrorOptions {
60
60
  fetchImpl?: typeof fetch;
61
61
  /** Injectable for tests; defaults to real git via execFile. */
62
62
  execFileImpl?: ExecFileFn;
63
+ /**
64
+ * The live workflow list, when the caller already read it with
65
+ * `fetchLiveWorkflows` (`client-drift --all` reads it once for every
66
+ * client). The n8n API is then not called at all.
67
+ */
68
+ liveWorkflows?: LiveWorkflow[];
69
+ }
70
+ export interface LiveWorkflow {
71
+ id: string;
72
+ name: string;
73
+ /** The workflow's own description, when the instance has one. */
74
+ description: string | null;
75
+ active: boolean;
76
+ archived: boolean;
77
+ updatedAt: string | null;
78
+ /** True when a node is a schedule trigger (scheduleTrigger, cron, interval). */
79
+ scheduled: boolean;
80
+ }
81
+ export interface FetchLiveWorkflowsOptions {
82
+ baseUrl?: string;
83
+ apiKey?: string;
84
+ env?: NodeJS.ProcessEnv;
85
+ fetchImpl?: typeof fetch;
63
86
  }
87
+ /**
88
+ * Every workflow on the n8n instance, archived ones included (the REST list
89
+ * returns them with isArchived set). Read-only: GET /workflows, page by page.
90
+ */
91
+ export declare function fetchLiveWorkflows(opts?: FetchLiveWorkflowsOptions): Promise<LiveWorkflow[]>;
64
92
  /**
65
93
  * Compare every n8n workflow against every client repo's exports. Read-only:
66
94
  * it fetches the workflow list, reads files, and shells out to `git log`.
@@ -30,6 +30,50 @@ import { N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError } from "./agent-template
30
30
  import { execFileAsync } from "./exec.js";
31
31
  /** n8n workflow ids are 16 chars of base62 — tight enough to find in prose. */
32
32
  const N8N_ID = /\b[A-Za-z0-9]{16}\b/g;
33
+ /** A trigger that fires on the clock, so a run is expected even with no input. */
34
+ const SCHEDULE_TRIGGER = /\.(scheduleTrigger|cron|interval)$/;
35
+ const WORKFLOW_PAGE_SIZE = 250;
36
+ /**
37
+ * Every workflow on the n8n instance, archived ones included (the REST list
38
+ * returns them with isArchived set). Read-only: GET /workflows, page by page.
39
+ */
40
+ export async function fetchLiveWorkflows(opts = {}) {
41
+ const env = opts.env ?? process.env;
42
+ const baseUrl = (opts.baseUrl ?? env[N8N_API_URL_ENV])?.replace(/\/+$/, "");
43
+ const apiKey = opts.apiKey ?? env[N8N_API_KEY_ENV];
44
+ if (!baseUrl || !apiKey) {
45
+ throw new N8nAuthError(`n8n API not configured — set $${N8N_API_URL_ENV} (incl. /api/v1) and $${N8N_API_KEY_ENV} (1Password).`);
46
+ }
47
+ const fetchImpl = opts.fetchImpl ?? fetch;
48
+ const live = [];
49
+ let cursor;
50
+ do {
51
+ const params = new URLSearchParams({ limit: String(WORKFLOW_PAGE_SIZE) });
52
+ if (cursor)
53
+ params.set("cursor", cursor);
54
+ const response = await fetchImpl(`${baseUrl}/workflows?${params}`, {
55
+ headers: { "X-N8N-API-KEY": apiKey, accept: "application/json" },
56
+ });
57
+ if (!response.ok)
58
+ throw new Error(`n8n API ${response.status} listing workflows`);
59
+ const payload = (await response.json());
60
+ const page = payload.data ?? [];
61
+ for (const w of page) {
62
+ const nodes = Array.isArray(w.nodes) ? w.nodes : [];
63
+ live.push({
64
+ id: String(w.id ?? ""),
65
+ name: String(w.name ?? ""),
66
+ description: typeof w.description === "string" ? w.description : null,
67
+ active: Boolean(w.active),
68
+ archived: Boolean(w.isArchived),
69
+ updatedAt: typeof w.updatedAt === "string" ? w.updatedAt : null,
70
+ scheduled: nodes.some((n) => typeof n.type === "string" && SCHEDULE_TRIGGER.test(n.type)),
71
+ });
72
+ }
73
+ cursor = payload.nextCursor && page.length > 0 ? String(payload.nextCursor) : undefined;
74
+ } while (cursor);
75
+ return live;
76
+ }
33
77
  /** Pull every n8n-shaped id out of a blob of text. */
34
78
  function idsIn(text) {
35
79
  return text.match(N8N_ID) ?? [];
@@ -164,27 +208,8 @@ async function lastCommitIso(repoDir, relPath, execFileImpl) {
164
208
  */
165
209
  export async function checkAgentMirror(opts = {}) {
166
210
  const workspaceDir = opts.workspaceDir ?? ".";
167
- const env = opts.env ?? process.env;
168
- const baseUrl = (opts.baseUrl ?? env[N8N_API_URL_ENV])?.replace(/\/+$/, "");
169
- const apiKey = opts.apiKey ?? env[N8N_API_KEY_ENV];
170
- if (!baseUrl || !apiKey) {
171
- throw new N8nAuthError(`n8n API not configured — set $${N8N_API_URL_ENV} (incl. /api/v1) and $${N8N_API_KEY_ENV} (1Password).`);
172
- }
173
- const fetchImpl = opts.fetchImpl ?? fetch;
174
211
  const execFileImpl = opts.execFileImpl ?? execFileAsync;
175
- const response = await fetchImpl(`${baseUrl}/workflows?limit=250`, {
176
- headers: { "X-N8N-API-KEY": apiKey, accept: "application/json" },
177
- });
178
- if (!response.ok)
179
- throw new Error(`n8n API ${response.status} listing workflows`);
180
- const payload = (await response.json());
181
- const live = (payload.data ?? []).map((w) => ({
182
- id: String(w.id ?? ""),
183
- name: String(w.name ?? ""),
184
- active: Boolean(w.active),
185
- archived: Boolean(w.isArchived),
186
- updatedAt: typeof w.updatedAt === "string" ? w.updatedAt : null,
187
- }));
212
+ const live = opts.liveWorkflows ?? (await fetchLiveWorkflows(opts));
188
213
  const liveNames = new Map(live.map((w) => [w.id, w.name]));
189
214
  const exports = await listExports(workspaceDir, opts.client);
190
215
  for (const exp of exports) {
@@ -0,0 +1,120 @@
1
+ import { type ExecFileFn } from "./exec.js";
2
+ import { type StatusFn } from "./git.js";
3
+ export type { RepoStatusInfo, StatusFn } from "./git.js";
4
+ /** An active scheduled workflow with no run in this many days is silent. */
5
+ export declare const CLIENT_DRIFT_SILENCE_DAYS = 7;
6
+ export type DriftLevel = "drift" | "check";
7
+ export type DriftCheck =
8
+ /** CLIENT.md Builds `status` vs n8n `active`/archived. */
9
+ "active-flag"
10
+ /** A Builds `workflow_id` that the instance does not have. */
11
+ | "missing-workflow"
12
+ /** A Builds agent whose workflow has no export in workflows/. */
13
+ | "missing-export"
14
+ /** The instance changed after the export's last commit: diff them. */
15
+ | "stale-export"
16
+ /** An export with no live workflow, archived ones included. */
17
+ | "orphan-export"
18
+ /** An active scheduled workflow with no recent run. */
19
+ | "silence"
20
+ /** The newest run failed (status only). */
21
+ | "last-error"
22
+ /** "SHADOW"/"TEST" in the live name or description of an active build. */
23
+ | "name"
24
+ /** Uncommitted, untracked or unpushed work; no upstream. */
25
+ | "git" | "open-pr"
26
+ /** A drift rule (12+) of the repo's own repo-lint, or repo-lint failing. */
27
+ | "lint"
28
+ /** Linear vs the delivery log (Linear is a mirror, never a source). */
29
+ | "linear";
30
+ export interface DriftFinding {
31
+ client: string;
32
+ check: DriftCheck;
33
+ level: DriftLevel;
34
+ /** The build slug, export file, branch, PR number or lint rule it is about. */
35
+ subject: string;
36
+ /** What one source says. */
37
+ sourceA: string;
38
+ /** What the other source says. */
39
+ sourceB: string;
40
+ /** The next step, for a person who has never seen this repo. */
41
+ hint: string;
42
+ }
43
+ export interface ClientDriftClient {
44
+ slug: string;
45
+ dir: string;
46
+ findings: DriftFinding[];
47
+ /** Checks that did not run for this client, and why. A skip is not a pass. */
48
+ skipped: string[];
49
+ }
50
+ export interface ClientDriftResult {
51
+ workspaceDir: string;
52
+ generatedAt: string;
53
+ clients: ClientDriftClient[];
54
+ driftCount: number;
55
+ checkCount: number;
56
+ /**
57
+ * Sources that could not be read for the whole run (no n8n key, a key
58
+ * without execution:read). Non-empty means the report is partial.
59
+ */
60
+ unreadSources: string[];
61
+ /** How many days of runs the instance keeps, when it had to be measured. */
62
+ executionWindowDays: number | null;
63
+ notes: string[];
64
+ }
65
+ export interface ClientDriftOptions {
66
+ /** The installagent/ workspace root (contains clients/). */
67
+ workspaceDir?: string;
68
+ /** One client, without the `client-` prefix. Give this or `all`. */
69
+ slug?: string;
70
+ /** Every clients/client-*\/ checkout except client-template. */
71
+ all?: boolean;
72
+ /** Check git status and open PRs. Default true. */
73
+ git?: boolean;
74
+ silenceDays?: number;
75
+ now?: () => Date;
76
+ /** n8n API base incl. /api/v1; defaults to $N8N_API_URL. */
77
+ baseUrl?: string;
78
+ /** Defaults to $N8N_API_KEY. */
79
+ apiKey?: string;
80
+ env?: NodeJS.ProcessEnv;
81
+ fetchImpl?: typeof fetch;
82
+ /** git log/remote, gh, node ci/repo-lint.mjs. Injectable for tests. */
83
+ execFileImpl?: ExecFileFn;
84
+ statusFn?: StatusFn;
85
+ /** Compare Linear with the delivery log. Default true. Read-only. */
86
+ linear?: boolean;
87
+ /** Linear API key; defaults to $LINEAR_API_TOKEN. */
88
+ linearToken?: string;
89
+ }
90
+ /**
91
+ * Compare one client repo (or every one) with n8n, git, Linear and its own lint.
92
+ * Never throws for a source it cannot read: the source goes into
93
+ * `unreadSources` (whole run) or the client's `skipped` list, and the other
94
+ * checks still run.
95
+ */
96
+ export declare function clientDrift(options: ClientDriftOptions): Promise<ClientDriftResult>;
97
+ /**
98
+ * The Slack text for a drift result, or null when there is nothing to say (no
99
+ * finding and no unread source). Internal channel only: it names clients and
100
+ * builds, never PII, never money.
101
+ */
102
+ export declare function formatClientDriftSlack(result: ClientDriftResult): string | null;
103
+ export interface PostClientDriftOptions {
104
+ /** A Slack bot token that is a member of the channel ($SLACK_BOT_TOKEN, Agent Zero). */
105
+ token: string;
106
+ /** The channel id (not the name). */
107
+ channel: string;
108
+ fetchImpl?: typeof fetch;
109
+ }
110
+ export type PostClientDriftResult = {
111
+ status: "posted";
112
+ ts: string;
113
+ } | {
114
+ status: "empty";
115
+ };
116
+ /**
117
+ * Post the weekly drift report — only when `formatClientDriftSlack` has
118
+ * something to say. Throws when Slack refuses, so a scheduled run fails loudly.
119
+ */
120
+ export declare function postClientDriftReport(result: ClientDriftResult, opts: PostClientDriftOptions): Promise<PostClientDriftResult>;