@installagent/sdk 0.16.1 → 0.18.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.
@@ -77,6 +77,24 @@ export interface LiveWorkflow {
77
77
  updatedAt: string | null;
78
78
  /** True when a node is a schedule trigger (scheduleTrigger, cron, interval). */
79
79
  scheduled: boolean;
80
+ /** Tag names, sorted. Most workflows on the instance have none. */
81
+ tags: string[];
82
+ /**
83
+ * An active workflow whose saved version is not the published one
84
+ * (`versionId` ≠ `activeVersionId`). False for an inactive workflow: all of
85
+ * it is unpublished. Null when the instance does not report version ids.
86
+ */
87
+ hasUnpublishedChanges: boolean | null;
88
+ /**
89
+ * Which credential SLOTS each node type uses (`gmailOAuth2`), sorted. The
90
+ * slot name is the credential type. The credential's id and its display
91
+ * name are dropped here, at the read, so no caller can print them.
92
+ */
93
+ credentialSlots: WorkflowCredentialSlots[];
94
+ }
95
+ export interface WorkflowCredentialSlots {
96
+ nodeType: string;
97
+ slots: string[];
80
98
  }
81
99
  export interface FetchLiveWorkflowsOptions {
82
100
  baseUrl?: string;
@@ -30,6 +30,30 @@ 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
+ function credentialSlotsOf(nodes) {
34
+ const byType = new Map();
35
+ for (const node of nodes) {
36
+ const credentials = node.credentials;
37
+ if (typeof node.type !== "string" || !credentials || typeof credentials !== "object")
38
+ continue;
39
+ const slots = byType.get(node.type) ?? new Set();
40
+ // Keys only: the values hold the credential id and name.
41
+ for (const slot of Object.keys(credentials))
42
+ slots.add(slot);
43
+ if (slots.size > 0)
44
+ byType.set(node.type, slots);
45
+ }
46
+ return [...byType]
47
+ .map(([nodeType, slots]) => ({ nodeType, slots: [...slots].sort() }))
48
+ .sort((a, b) => a.nodeType.localeCompare(b.nodeType, "en"));
49
+ }
50
+ function unpublishedChanges(w) {
51
+ if (!w.active)
52
+ return false;
53
+ if (typeof w.versionId !== "string" || typeof w.activeVersionId !== "string")
54
+ return null;
55
+ return w.versionId !== w.activeVersionId;
56
+ }
33
57
  /** A trigger that fires on the clock, so a run is expected even with no input. */
34
58
  const SCHEDULE_TRIGGER = /\.(scheduleTrigger|cron|interval)$/;
35
59
  const WORKFLOW_PAGE_SIZE = 250;
@@ -68,6 +92,12 @@ export async function fetchLiveWorkflows(opts = {}) {
68
92
  archived: Boolean(w.isArchived),
69
93
  updatedAt: typeof w.updatedAt === "string" ? w.updatedAt : null,
70
94
  scheduled: nodes.some((n) => typeof n.type === "string" && SCHEDULE_TRIGGER.test(n.type)),
95
+ tags: (Array.isArray(w.tags) ? w.tags : [])
96
+ .map((tag) => (typeof tag?.name === "string" ? tag.name : ""))
97
+ .filter(Boolean)
98
+ .sort(),
99
+ hasUnpublishedChanges: unpublishedChanges(w),
100
+ credentialSlots: credentialSlotsOf(nodes),
71
101
  });
72
102
  }
73
103
  cursor = payload.nextCursor && page.length > 0 ? String(payload.nextCursor) : undefined;
@@ -40,10 +40,34 @@ export interface DriftFinding {
40
40
  /** The next step, for a person who has never seen this repo. */
41
41
  hint: string;
42
42
  }
43
+ /**
44
+ * How many findings one rule has. A rule is the check name, or `lint rule <n>`
45
+ * for a repo-lint drift rule: one lint rule can give dozens of rows, and those
46
+ * must not hide the three rows of real drift next to them.
47
+ */
48
+ export interface DriftRuleCount {
49
+ rule: string;
50
+ check: DriftCheck;
51
+ driftCount: number;
52
+ checkCount: number;
53
+ /** driftCount + checkCount. */
54
+ count: number;
55
+ }
56
+ /** One rule's findings, for a view that prints them together. */
57
+ export interface DriftRuleGroup extends DriftRuleCount {
58
+ findings: DriftFinding[];
59
+ }
60
+ /** A rule's total across every client of the run. */
61
+ export interface DriftRuleTotal extends DriftRuleCount {
62
+ /** How many client repos have at least one finding of this rule. */
63
+ clients: number;
64
+ }
43
65
  export interface ClientDriftClient {
44
66
  slug: string;
45
67
  dir: string;
46
68
  findings: DriftFinding[];
69
+ /** The same findings counted per rule, smallest group first, largest last. */
70
+ rules: DriftRuleCount[];
47
71
  /** Checks that did not run for this client, and why. A skip is not a pass. */
48
72
  skipped: string[];
49
73
  }
@@ -53,6 +77,8 @@ export interface ClientDriftResult {
53
77
  clients: ClientDriftClient[];
54
78
  driftCount: number;
55
79
  checkCount: number;
80
+ /** Per-rule totals across every client, smallest first, largest last. */
81
+ rules: DriftRuleTotal[];
56
82
  /**
57
83
  * Sources that could not be read for the whole run (no n8n key, a key
58
84
  * without execution:read). Non-empty means the report is partial.
@@ -87,6 +113,15 @@ export interface ClientDriftOptions {
87
113
  /** Linear API key; defaults to $LINEAR_API_TOKEN. */
88
114
  linearToken?: string;
89
115
  }
116
+ /** The rule a finding belongs to: its check, or `lint rule <n>` for a repo-lint drift rule. */
117
+ export declare function driftRuleOf(finding: Pick<DriftFinding, "check" | "subject">): string;
118
+ /**
119
+ * Findings grouped by rule. Smallest group first and largest last, so in a
120
+ * terminal the noisy rule ends up at the bottom and the small groups (where
121
+ * the real drift usually is) are read first. Equal counts: more drift first,
122
+ * then by name, so the order is stable.
123
+ */
124
+ export declare function groupDriftFindings(findings: DriftFinding[]): DriftRuleGroup[];
90
125
  /**
91
126
  * The day client-template's repo-lint rule 20 starts: from then on, a log
92
127
  * entry's Follow-ups is `none` or INS ids only (owed work, never shipped work).
@@ -40,6 +40,47 @@ const FIRST_DRIFT_RULE = 12;
40
40
  /** Enough pages to reach the oldest run n8n keeps (it prunes at ~10,000). */
41
41
  const WINDOW_SCAN_LIMIT = 20_000;
42
42
  const SLACK_LINES_PER_CLIENT = 12;
43
+ /** The rule a finding belongs to: its check, or `lint rule <n>` for a repo-lint drift rule. */
44
+ export function driftRuleOf(finding) {
45
+ return finding.check === "lint" && /^rule \d+$/.test(finding.subject)
46
+ ? `lint ${finding.subject}`
47
+ : finding.check;
48
+ }
49
+ /**
50
+ * Findings grouped by rule. Smallest group first and largest last, so in a
51
+ * terminal the noisy rule ends up at the bottom and the small groups (where
52
+ * the real drift usually is) are read first. Equal counts: more drift first,
53
+ * then by name, so the order is stable.
54
+ */
55
+ export function groupDriftFindings(findings) {
56
+ const groups = new Map();
57
+ for (const finding of findings) {
58
+ const rule = driftRuleOf(finding);
59
+ const group = groups.get(rule) ?? {
60
+ rule,
61
+ check: finding.check,
62
+ driftCount: 0,
63
+ checkCount: 0,
64
+ count: 0,
65
+ findings: [],
66
+ };
67
+ if (finding.level === "drift")
68
+ group.driftCount += 1;
69
+ else
70
+ group.checkCount += 1;
71
+ group.count += 1;
72
+ group.findings.push(finding);
73
+ groups.set(rule, group);
74
+ }
75
+ return [...groups.values()].sort((a, b) => a.count - b.count || b.driftCount - a.driftCount || a.rule.localeCompare(b.rule, "en"));
76
+ }
77
+ const ruleCount = ({ rule, check, driftCount, checkCount, count }) => ({
78
+ rule,
79
+ check,
80
+ driftCount,
81
+ checkCount,
82
+ count,
83
+ });
43
84
  const message = (error) => (error instanceof Error ? error.message : String(error));
44
85
  const short = (text, max) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
45
86
  const days = (ms) => ms / DAY_MS;
@@ -456,7 +497,13 @@ export async function clientDrift(options) {
456
497
  await linear.check(dir, clientMd, now, add, skipped);
457
498
  }
458
499
  findings.sort((a, b) => (a.level === b.level ? 0 : a.level === "drift" ? -1 : 1));
459
- clients.push({ slug, dir, findings, skipped });
500
+ clients.push({
501
+ slug,
502
+ dir,
503
+ findings,
504
+ rules: groupDriftFindings(findings).map(ruleCount),
505
+ skipped,
506
+ });
460
507
  }
461
508
  if (runs.unread)
462
509
  unreadSources.push(`n8n executions: ${runs.unread}`);
@@ -469,6 +516,10 @@ export async function clientDrift(options) {
469
516
  clients,
470
517
  driftCount: all.filter((f) => f.level === "drift").length,
471
518
  checkCount: all.filter((f) => f.level === "check").length,
519
+ rules: groupDriftFindings(all).map((group) => ({
520
+ ...ruleCount(group),
521
+ clients: new Set(group.findings.map((f) => f.client)).size,
522
+ })),
472
523
  unreadSources,
473
524
  executionWindowDays: runs.windowDays,
474
525
  notes: [
@@ -0,0 +1,85 @@
1
+ /** The label the follow-up loop reads. It is looked up by name and never created here. */
2
+ export declare const WAITING_ON_CLIENT_LABEL = "Waiting on client";
3
+ export type AskReason = "title" | "description";
4
+ /**
5
+ * Why an issue looks like an ask to the client, or null when it does not.
6
+ * `title` is the weaker signal: "Get Koz to review" starts with an ask word
7
+ * but asks a teammate, so a person reads the list before the label write.
8
+ */
9
+ export declare function askReason(title: string, description: string | null): AskReason | null;
10
+ export interface ClientAsk {
11
+ slug: string;
12
+ /** The issue id a person reads, for example INS-123. */
13
+ identifier: string;
14
+ title: string;
15
+ /** Whole days since the issue was created. */
16
+ ageDays: number;
17
+ reason: AskReason;
18
+ url: string;
19
+ }
20
+ export interface ClientLinearAsksClient {
21
+ slug: string;
22
+ /** `skipped`: no Linear project. `error`: Linear could not be read for this client. */
23
+ status: "ok" | "skipped" | "error";
24
+ /** Open issues read. */
25
+ open: number;
26
+ /** Asks listed for this client. */
27
+ asks: number;
28
+ reason?: string;
29
+ }
30
+ export interface ClientLinearAsksApplied {
31
+ /** Issues that now have the label. */
32
+ labeled: string[];
33
+ /** Issues a person told the run to leave (`skip`). */
34
+ skipped: string[];
35
+ failed: Array<{
36
+ identifier: string;
37
+ error: string;
38
+ }>;
39
+ }
40
+ export interface ClientLinearAsksResult {
41
+ workspaceDir: string;
42
+ generatedAt: string;
43
+ /** The label an ask must have. */
44
+ label: string;
45
+ /** Per client, oldest first. With `applied`, this is the list BEFORE the write. */
46
+ asks: ClientAsk[];
47
+ clients: ClientLinearAsksClient[];
48
+ notes: string[];
49
+ /** Only from `clientLinearAsksApply`. */
50
+ applied?: ClientLinearAsksApplied;
51
+ }
52
+ export interface ClientLinearAsksOptions {
53
+ /** The installagent/ workspace root (contains clients/). */
54
+ workspaceDir?: string;
55
+ /** One client, without the `client-` prefix. Give this or `all`. */
56
+ slug?: string;
57
+ /** Every clients/client-* checkout with a Linear project. */
58
+ all?: boolean;
59
+ /** Linear API key; defaults to $LINEAR_API_TOKEN. */
60
+ token?: string;
61
+ env?: NodeJS.ProcessEnv;
62
+ fetchImpl?: typeof fetch;
63
+ now?: () => Date;
64
+ }
65
+ export interface ClientLinearAsksApplyOptions extends ClientLinearAsksOptions {
66
+ /** Issue ids (INS-123) to leave without the label: asks to a teammate, not the client. */
67
+ skip?: string[];
68
+ }
69
+ /**
70
+ * Open issues in client Linear projects that look like an ask to the client
71
+ * and do not have the "Waiting on client" label. The project of each client
72
+ * comes from the `linear_project` line of its local CLIENT.md, never from a
73
+ * name. Strictly read-only: GraphQL queries only. The result has ids, titles
74
+ * and ages; it never has a description.
75
+ */
76
+ export declare function clientLinearAsks(options: ClientLinearAsksOptions): Promise<ClientLinearAsksResult>;
77
+ /**
78
+ * The label backfill: ADD "Waiting on client" to each listed ask, except the
79
+ * ids in `skip`. One `issueAddLabel` call per issue: it adds one label and
80
+ * cannot replace the label set or change any other field. The label is looked
81
+ * up by name and never created: no label, no write. A `skip` id that is not in
82
+ * the list stops the run before any write (a typo must not label the issue it
83
+ * was meant to protect).
84
+ */
85
+ export declare function clientLinearAsksApply(options: ClientLinearAsksApplyOptions): Promise<ClientLinearAsksResult>;
@@ -0,0 +1,247 @@
1
+ // `ia client-linear-asks` — the open client asks that the follow-up loop cannot see.
2
+ //
3
+ // An ask is an issue that waits on the client: a file, a login, an answer. The
4
+ // label "Waiting on client" is what the follow-up loop and the portal read, so
5
+ // an ask without the label is silent: nobody is reminded and the client never
6
+ // sees it. This module lists those issues. The list is read-only (GraphQL
7
+ // queries). `clientLinearAsksApply` is the one write, CLI only: it ADDS the one
8
+ // label with `issueAddLabel`, which cannot change a state, an assignee, a title,
9
+ // a description or the other labels.
10
+ import { existsSync, readFileSync } from "node:fs";
11
+ import { join, resolve } from "node:path";
12
+ import { parseLinearProjectSlugId } from "./client-linear.js";
13
+ import { readManifestKey } from "./client-manifest.js";
14
+ import { findProjectBySlugId, LINEAR_API_TOKEN_ENV, LinearAuthError, linearRequest, } from "./linear-project.js";
15
+ import { selectClientSlugs } from "./template-sync.js";
16
+ /** The label the follow-up loop reads. It is looked up by name and never created here. */
17
+ export const WAITING_ON_CLIENT_LABEL = "Waiting on client";
18
+ /** A parked issue is out of the plan on purpose: it is not an open ask. */
19
+ const PARKED_LABEL = "parked";
20
+ // The same closed types as linear-project.ts: "duplicate" is its own type.
21
+ const CLOSED_STATE_TYPES = ["completed", "canceled", "duplicate"];
22
+ const PAGE_SIZE = 250;
23
+ const MAX_PAGES = 20;
24
+ const DAY_MS = 86_400_000;
25
+ /** The first whole word(s) of the title: Ask, Get, Confirm, Question, Request, "Need from". */
26
+ const ASK_TITLE = /^(?:ask|get|confirm|question|request|need\s+from)\b/i;
27
+ /** A `Client question:` or `Client to-do:` field line (plain, a list item, or bold). */
28
+ const ASK_DESCRIPTION = /^[ \t]*(?:[-*][ \t]+)?(?:\*\*)?client (?:question|to-do):/im;
29
+ /**
30
+ * Why an issue looks like an ask to the client, or null when it does not.
31
+ * `title` is the weaker signal: "Get Koz to review" starts with an ask word
32
+ * but asks a teammate, so a person reads the list before the label write.
33
+ */
34
+ export function askReason(title, description) {
35
+ if (ASK_TITLE.test(title.trimStart()))
36
+ return "title";
37
+ if (description && ASK_DESCRIPTION.test(description))
38
+ return "description";
39
+ return null;
40
+ }
41
+ const ISSUES_QUERY = `
42
+ query ProjectOpenIssuesForAsks($projectId: ID!, $closedStateTypes: [String!]!, $first: Int!, $after: String) {
43
+ issues(
44
+ filter: { project: { id: { eq: $projectId } }, state: { type: { nin: $closedStateTypes } } }
45
+ first: $first
46
+ after: $after
47
+ ) {
48
+ nodes {
49
+ id
50
+ identifier
51
+ title
52
+ url
53
+ description
54
+ createdAt
55
+ team { id }
56
+ labels { nodes { name } }
57
+ }
58
+ pageInfo { hasNextPage endCursor }
59
+ }
60
+ }
61
+ `;
62
+ const LABEL_QUERY = `
63
+ query AskLabelByName($name: String!) {
64
+ issueLabels(filter: { name: { eqIgnoreCase: $name } }, first: 50) {
65
+ nodes { id name team { id } }
66
+ }
67
+ }
68
+ `;
69
+ const ADD_LABEL_MUTATION = `
70
+ mutation AddAskLabel($id: String!, $labelId: String!) {
71
+ issueAddLabel(id: $id, labelId: $labelId) { success }
72
+ }
73
+ `;
74
+ const message = (error) => (error instanceof Error ? error.message : String(error));
75
+ async function openIssues(fetchImpl, token, project) {
76
+ const out = [];
77
+ let after = null;
78
+ for (let page = 0; page < MAX_PAGES; page++) {
79
+ const { issues, } = await linearRequest(fetchImpl, token, ISSUES_QUERY, {
80
+ projectId: project.id,
81
+ closedStateTypes: CLOSED_STATE_TYPES,
82
+ first: PAGE_SIZE,
83
+ after,
84
+ });
85
+ out.push(...issues.nodes);
86
+ if (!issues.pageInfo.hasNextPage || !issues.pageInfo.endCursor)
87
+ break;
88
+ after = issues.pageInfo.endCursor;
89
+ }
90
+ return out;
91
+ }
92
+ async function collect(options) {
93
+ const workspaceDir = resolve(options.workspaceDir ?? ".");
94
+ const { slugs, adhoc } = selectClientSlugs(workspaceDir, options, "client-linear-asks");
95
+ const env = options.env ?? process.env;
96
+ const token = options.token ?? env[LINEAR_API_TOKEN_ENV];
97
+ const fetchImpl = options.fetchImpl ?? fetch;
98
+ const now = (options.now ?? (() => new Date()))();
99
+ const clients = [];
100
+ const rows = [];
101
+ for (const slug of slugs) {
102
+ const skip = (reason) => clients.push({ slug, status: "skipped", open: 0, asks: 0, reason });
103
+ const clientMdPath = join(workspaceDir, "clients", `client-${slug}`, "CLIENT.md");
104
+ if (!existsSync(clientMdPath)) {
105
+ skip("no CLIENT.md");
106
+ continue;
107
+ }
108
+ const url = readManifestKey(readFileSync(clientMdPath, "utf8"), "linear_project")?.split(/\s+/)[0];
109
+ const slugId = url?.startsWith("http") ? parseLinearProjectSlugId(url) : undefined;
110
+ if (!slugId) {
111
+ skip("no Linear project in CLIENT.md");
112
+ continue;
113
+ }
114
+ // Only now is the token needed: a run with nothing to read needs no key.
115
+ if (!token) {
116
+ throw new LinearAuthError(`Linear API key required — set ${LINEAR_API_TOKEN_ENV} (a personal API key) or pass token`);
117
+ }
118
+ try {
119
+ const project = await findProjectBySlugId(fetchImpl, token, slugId);
120
+ const issues = await openIssues(fetchImpl, token, project);
121
+ const found = [];
122
+ for (const issue of issues) {
123
+ const labels = issue.labels.nodes.map((label) => label.name.toLowerCase());
124
+ if (labels.includes(WAITING_ON_CLIENT_LABEL.toLowerCase()))
125
+ continue;
126
+ if (labels.includes(PARKED_LABEL))
127
+ continue;
128
+ const reason = askReason(issue.title, issue.description);
129
+ if (!reason)
130
+ continue;
131
+ found.push({
132
+ ask: {
133
+ slug,
134
+ identifier: issue.identifier,
135
+ title: issue.title,
136
+ ageDays: Math.max(0, Math.floor((now.getTime() - Date.parse(issue.createdAt)) / DAY_MS)),
137
+ reason,
138
+ url: issue.url,
139
+ },
140
+ issueId: issue.id,
141
+ teamId: issue.team?.id ?? null,
142
+ });
143
+ }
144
+ found.sort((a, b) => b.ask.ageDays - a.ask.ageDays ||
145
+ a.ask.identifier.localeCompare(b.ask.identifier, "en", { numeric: true }));
146
+ rows.push(...found);
147
+ clients.push({ slug, status: "ok", open: issues.length, asks: found.length });
148
+ }
149
+ catch (error) {
150
+ // A rejected key fails every client the same way: stop, do not list 20 errors.
151
+ if (error instanceof LinearAuthError)
152
+ throw error;
153
+ clients.push({
154
+ slug,
155
+ status: "error",
156
+ open: 0,
157
+ asks: 0,
158
+ reason: message(error).split("\n")[0],
159
+ });
160
+ }
161
+ }
162
+ const notes = [
163
+ `An ask: an open issue (not completed, not canceled) whose title starts with Ask, Get, Confirm, Question, Request or "Need from", or whose description has a "Client question:" or "Client to-do:" line. Issues that have the "${WAITING_ON_CLIENT_LABEL}" label or the "${PARKED_LABEL}" label are not listed.`,
164
+ 'A title match can be an ask to a teammate ("Get <teammate> to review"). Read the list before a label write.',
165
+ ...(adhoc.length > 0
166
+ ? [`Skipped ad hoc repos (no Linear project; name one to see why): ${adhoc.join(", ")}.`]
167
+ : []),
168
+ ];
169
+ return {
170
+ result: {
171
+ workspaceDir,
172
+ generatedAt: now.toISOString(),
173
+ label: WAITING_ON_CLIENT_LABEL,
174
+ asks: rows.map((row) => row.ask),
175
+ clients,
176
+ notes,
177
+ },
178
+ rows,
179
+ token: token ?? "",
180
+ fetchImpl,
181
+ };
182
+ }
183
+ /**
184
+ * Open issues in client Linear projects that look like an ask to the client
185
+ * and do not have the "Waiting on client" label. The project of each client
186
+ * comes from the `linear_project` line of its local CLIENT.md, never from a
187
+ * name. Strictly read-only: GraphQL queries only. The result has ids, titles
188
+ * and ages; it never has a description.
189
+ */
190
+ export async function clientLinearAsks(options) {
191
+ return (await collect(options)).result;
192
+ }
193
+ /**
194
+ * The label backfill: ADD "Waiting on client" to each listed ask, except the
195
+ * ids in `skip`. One `issueAddLabel` call per issue: it adds one label and
196
+ * cannot replace the label set or change any other field. The label is looked
197
+ * up by name and never created: no label, no write. A `skip` id that is not in
198
+ * the list stops the run before any write (a typo must not label the issue it
199
+ * was meant to protect).
200
+ */
201
+ export async function clientLinearAsksApply(options) {
202
+ const { result, rows, token, fetchImpl } = await collect(options);
203
+ const skip = new Set((options.skip ?? []).map((id) => id.trim().toUpperCase()).filter(Boolean));
204
+ const listed = new Set(rows.map((row) => row.ask.identifier.toUpperCase()));
205
+ const unknown = [...skip].filter((id) => !listed.has(id));
206
+ if (unknown.length > 0) {
207
+ throw new Error(`--skip names ${unknown.join(", ")}, which the ask list does not have. Nothing was written.`);
208
+ }
209
+ const applied = { labeled: [], skipped: [], failed: [] };
210
+ const todo = rows.filter((row) => {
211
+ if (!skip.has(row.ask.identifier.toUpperCase()))
212
+ return true;
213
+ applied.skipped.push(row.ask.identifier);
214
+ return false;
215
+ });
216
+ if (todo.length === 0)
217
+ return { ...result, applied };
218
+ const { issueLabels } = await linearRequest(fetchImpl, token, LABEL_QUERY, { name: WAITING_ON_CLIENT_LABEL });
219
+ if (issueLabels.nodes.length === 0) {
220
+ throw new Error(`Linear has no label named "${WAITING_ON_CLIENT_LABEL}". It is never created here. Nothing was written.`);
221
+ }
222
+ for (const row of todo) {
223
+ // A team label can go only on that team's issues; a workspace label on any.
224
+ const label = issueLabels.nodes.find((node) => node.team !== null && node.team.id === row.teamId) ??
225
+ issueLabels.nodes.find((node) => node.team === null);
226
+ if (!label) {
227
+ applied.failed.push({
228
+ identifier: row.ask.identifier,
229
+ error: `no "${WAITING_ON_CLIENT_LABEL}" label for this issue's team`,
230
+ });
231
+ continue;
232
+ }
233
+ try {
234
+ const { issueAddLabel } = await linearRequest(fetchImpl, token, ADD_LABEL_MUTATION, { id: row.issueId, labelId: label.id });
235
+ if (issueAddLabel.success)
236
+ applied.labeled.push(row.ask.identifier);
237
+ else
238
+ applied.failed.push({ identifier: row.ask.identifier, error: "Linear said success=false" });
239
+ }
240
+ catch (error) {
241
+ if (error instanceof LinearAuthError)
242
+ throw error;
243
+ applied.failed.push({ identifier: row.ask.identifier, error: message(error).split("\n")[0] });
244
+ }
245
+ }
246
+ return { ...result, applied };
247
+ }
@@ -12,6 +12,12 @@ export interface ClientLinearCreateIssueInput {
12
12
  * "Waiting on client" is relying on that label to drive a follow-up loop.
13
13
  */
14
14
  labelNames?: string[];
15
+ /**
16
+ * The issue is an ask to the client (a file, a login, an answer). Adds the
17
+ * "Waiting on client" label name to `labelNames`, once. The label is looked
18
+ * up like any other: it is never created, and a missing label fails the call.
19
+ */
20
+ ask?: boolean;
15
21
  }
16
22
  export interface ClientLinearCreateIssueResult {
17
23
  project: ProjectNode;
@@ -1,4 +1,5 @@
1
1
  import { resolveClientLinearProject } from "./client-linear.js";
2
+ import { WAITING_ON_CLIENT_LABEL } from "./client-linear-asks.js";
2
3
  import { linearRequest } from "./linear-project.js";
3
4
  const PROJECT_TEAMS_QUERY = `
4
5
  query ProjectTeams($id: String!) {
@@ -43,7 +44,7 @@ export async function clientLinearCreateIssue(slug, input, options = {}) {
43
44
  if (!teamId) {
44
45
  throw new Error(`Linear project "${project.name}" has no team — can't create an issue without one.`);
45
46
  }
46
- const labelIds = await resolveLabelIds(fetchImpl, linearToken, input.labelNames ?? []);
47
+ const labelIds = await resolveLabelIds(fetchImpl, linearToken, labelNamesFor(input));
47
48
  const created = await linearRequest(fetchImpl, linearToken, CREATE_ISSUE_MUTATION, {
48
49
  input: {
49
50
  teamId,
@@ -58,6 +59,12 @@ export async function clientLinearCreateIssue(slug, input, options = {}) {
58
59
  }
59
60
  return { project, teamId, issue: created.issueCreate.issue };
60
61
  }
62
+ /** The label names of the input; `ask` adds "Waiting on client" unless it is already named. */
63
+ function labelNamesFor(input) {
64
+ const names = (input.labelNames ?? []).map((n) => n.trim()).filter(Boolean);
65
+ const hasAskLabel = names.some((n) => n.toLowerCase() === WAITING_ON_CLIENT_LABEL.toLowerCase());
66
+ return input.ask && !hasAskLabel ? [...names, WAITING_ON_CLIENT_LABEL] : names;
67
+ }
61
68
  /** Label names → ids. Empty in, empty out (no request). Any unresolved name throws. */
62
69
  async function resolveLabelIds(fetchImpl, token, names) {
63
70
  const wanted = names.map((n) => n.trim()).filter(Boolean);
package/dist/index.d.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  export { type AccessCheckItem, type AccessCheckOptions, type AccessCheckResult, type AccessService, type AccessStatus, accessCheck, classifyKey, clientVaultFor, } from "./access-check.js";
2
- export { type AgentMirrorOptions, type AgentMirrorResult, checkAgentMirror, type FetchLiveWorkflowsOptions, fetchLiveWorkflows, type LiveWorkflow, type MirrorRow, type MirrorState, type MirrorSummary, } from "./agent-mirror.js";
2
+ export { type AgentMirrorOptions, type AgentMirrorResult, checkAgentMirror, type FetchLiveWorkflowsOptions, fetchLiveWorkflows, type LiveWorkflow, type MirrorRow, type MirrorState, type MirrorSummary, type WorkflowCredentialSlots, } from "./agent-mirror.js";
3
3
  export { type AgentBankOptions, type AgentTemplateInfo, type AgentTemplateMatch, type CreateFromTemplateInput, type CreateFromTemplateResult, createFromAgentTemplate, type ListAgentTemplatesResult, listAgentTemplates, N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError, type SanitizedWorkflow, type SaveAgentTemplateInput, type SaveAgentTemplateOptions, type SaveAgentTemplateResult, type SearchAgentTemplatesOptions, type SearchAgentTemplatesResult, type SopState, type StrippedCredential, sanitizeN8nWorkflow, saveAgentTemplate, searchAgentTemplates, } from "./agent-templates.js";
4
4
  export { BASIS_CHAR_CAP, BUILD_ESTIMATE_MODEL, type BuildEstimateOptions, type BuildEstimateOutcome, type BuildEstimateResult, type BuildEstimateRow, buildEstimate, buildEstimatePrompt, type EstimatePromptInput, type HoursRange, isBuildSpecFile, parseEstimateReply, redactContactDetails, removeMoney, SPEC_CHAR_CAP, setEstHours, specSectionFor, workflowNodeSummary, } from "./build-estimate.js";
5
5
  export { CLAUDE_CONFIG_DIR_ENV, type ClaudeHoursExportOptions, type ClaudeHoursExportResult, type ClaudeHoursSummaryRow, compactClaudeHoursExport, type DeliverClaudeHoursExportOptions, type DeliverClaudeHoursExportResult, deliverClaudeHoursExport, exportClaudeHours, HOURS_EXPORT_DIR, HOURS_EXPORT_SCHEMA, HOURS_EXPORT_SECRET_ENV, HOURS_EXPORT_SECRET_HEADER, HOURS_EXPORT_WEBHOOK_URL, PROMPT_WINDOW_MINUTES, parseLedgerDate, parseMinuteIso, type SaveClaudeHoursExportOptions, type SendClaudeHoursExportOptions, saveClaudeHoursExport, sendClaudeHoursExport, TOOL_INPUT_PATH_KEYS, UNATTRIBUTED_SLUG, } from "./claude-hours.js";
6
6
  export { ClientBuildAuthError, type ClientBuildDoc, type ClientBuildOptions, type ClientBuildResult, clientBuild, GITHUB_API_TOKEN_ENV, } from "./client-build.js";
7
7
  export { type ClientCall, type ClientContextOptions, type ClientContextResult, clientContext, } from "./client-context.js";
8
- export { CLIENT_DRIFT_SILENCE_DAYS, type ClientDriftClient, type ClientDriftOptions, type ClientDriftResult, clientDrift, type DriftCheck, type DriftFinding, type DriftLevel, FOLLOWUPS_INS_FROM, formatClientDriftSlack, type PostClientDriftOptions, type PostClientDriftResult, postClientDriftReport, type RepoStatusInfo, type StatusFn, } from "./client-drift.js";
8
+ export { CLIENT_DRIFT_SILENCE_DAYS, type ClientDriftClient, type ClientDriftOptions, type ClientDriftResult, clientDrift, type DriftCheck, type DriftFinding, type DriftLevel, type DriftRuleCount, type DriftRuleGroup, type DriftRuleTotal, driftRuleOf, FOLLOWUPS_INS_FROM, formatClientDriftSlack, groupDriftFindings, type PostClientDriftOptions, type PostClientDriftResult, postClientDriftReport, type RepoStatusInfo, type StatusFn, } from "./client-drift.js";
9
9
  export { AIRTABLE_API_TOKEN_ENV, buildAssertionClaims, ClientDriveAuthError, type ClientDriveDoc, type ClientDriveSearchOptions, type ClientDriveSearchResult, clientDriveSearch, GOOGLE_SERVICE_ACCOUNT_KEY_ENV, parseServiceAccountKey, } from "./client-drive.js";
10
10
  export { ClientIntakeAuthError, type ClientIntakeInput, type ClientIntakeOptions, type ClientIntakeResult, type ClientIntakeStep, clientIntake, LINEAR_CLIENT_TEAM_ID_ENV, } from "./client-intake.js";
11
11
  export { ClientLinearAuthError, type ClientLinearProjectOptions, clientLinearProject, parseLinearProjectSlugId, type ResolvedClientLinearProject, resolveClientLinearProject, } from "./client-linear.js";
12
+ export { type AskReason, askReason, type ClientAsk, type ClientLinearAsksApplied, type ClientLinearAsksApplyOptions, type ClientLinearAsksClient, type ClientLinearAsksOptions, type ClientLinearAsksResult, clientLinearAsks, clientLinearAsksApply, WAITING_ON_CLIENT_LABEL, } from "./client-linear-asks.js";
12
13
  export { type ClientLinearCreateIssueInput, type ClientLinearCreateIssueResult, clientLinearCreateIssue, } from "./client-linear-create.js";
13
14
  export { GCP_MANIFEST_KEYS, type GcpManifest, type GcpManifestKey, readGcpManifest, readGcpManifestFromRepo, readManifestKey, } from "./client-manifest.js";
14
15
  export { DOCS_SEARCH_TOKEN_ENV, DOCS_SESSION_ENV, type DocsSearchOptions, type DocsSearchResponse, type DocsSearchResult, DocsSessionError, docsSearch, TEAM_DOCS_BASE_URL, } from "./docs-search.js";
@@ -34,7 +35,9 @@ export { type HookInstallFn, type InstallClientHooksResult, installClientHooks,
34
35
  export { CLIENT_LINE_MAX, clientLineOf, findProjectBySlugId, LINEAR_API_TOKEN_ENV, LinearAuthError, type LinearIssue, LinearProjectNotFoundError, type LinearProjectOptions, type LinearProjectResult, linearProject, linearProjectIssues, linearRequest, type ProjectNode, } from "./linear-project.js";
35
36
  export { type CreateLoggerOptions, createLogger, type LogFields, type Logger, type LogLevel, redactFields, } from "./log.js";
36
37
  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";
38
+ export { type N8nDraftSelectedBy, type N8nDraftsDiff, type N8nDraftsOptions, type N8nDraftsResult, type N8nDraftWorkflow, n8nDrafts, } from "./n8n-drafts.js";
37
39
  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";
40
+ export { type ClientWorkflowExport, type N8nExportItem, type N8nExportOptions, type N8nExportResult, n8nExport, sanitizeClientExport, } from "./n8n-export.js";
38
41
  export { type NewClientOptions, type NewClientResult, newClient, SLUG_PATTERN, } from "./new-client.js";
39
42
  export { opInstallCommand, opInstallFix, opIntegrationFix } from "./op-cli.js";
40
43
  export { defaultOpTitle, type MintImpls, type MintToOpOptions, type MintToOpRequest, type MintToOpResult, mintToOnePassword, } from "./op-store.js";
package/dist/index.js CHANGED
@@ -8,10 +8,11 @@ export { BASIS_CHAR_CAP, BUILD_ESTIMATE_MODEL, buildEstimate, buildEstimatePromp
8
8
  export { CLAUDE_CONFIG_DIR_ENV, compactClaudeHoursExport, deliverClaudeHoursExport, exportClaudeHours, HOURS_EXPORT_DIR, HOURS_EXPORT_SCHEMA, HOURS_EXPORT_SECRET_ENV, HOURS_EXPORT_SECRET_HEADER, HOURS_EXPORT_WEBHOOK_URL, PROMPT_WINDOW_MINUTES, parseLedgerDate, parseMinuteIso, saveClaudeHoursExport, sendClaudeHoursExport, TOOL_INPUT_PATH_KEYS, UNATTRIBUTED_SLUG, } from "./claude-hours.js";
9
9
  export { ClientBuildAuthError, clientBuild, GITHUB_API_TOKEN_ENV, } from "./client-build.js";
10
10
  export { clientContext, } from "./client-context.js";
11
- export { CLIENT_DRIFT_SILENCE_DAYS, clientDrift, FOLLOWUPS_INS_FROM, formatClientDriftSlack, postClientDriftReport, } from "./client-drift.js";
11
+ export { CLIENT_DRIFT_SILENCE_DAYS, clientDrift, driftRuleOf, FOLLOWUPS_INS_FROM, formatClientDriftSlack, groupDriftFindings, postClientDriftReport, } from "./client-drift.js";
12
12
  export { AIRTABLE_API_TOKEN_ENV, buildAssertionClaims, ClientDriveAuthError, clientDriveSearch, GOOGLE_SERVICE_ACCOUNT_KEY_ENV, parseServiceAccountKey, } from "./client-drive.js";
13
13
  export { ClientIntakeAuthError, clientIntake, LINEAR_CLIENT_TEAM_ID_ENV, } from "./client-intake.js";
14
14
  export { ClientLinearAuthError, clientLinearProject, parseLinearProjectSlugId, resolveClientLinearProject, } from "./client-linear.js";
15
+ export { askReason, clientLinearAsks, clientLinearAsksApply, WAITING_ON_CLIENT_LABEL, } from "./client-linear-asks.js";
15
16
  export { clientLinearCreateIssue, } from "./client-linear-create.js";
16
17
  export { GCP_MANIFEST_KEYS, readGcpManifest, readGcpManifestFromRepo, readManifestKey, } from "./client-manifest.js";
17
18
  export { DOCS_SEARCH_TOKEN_ENV, DOCS_SESSION_ENV, DocsSessionError, docsSearch, TEAM_DOCS_BASE_URL, } from "./docs-search.js";
@@ -37,7 +38,9 @@ export { installClientHooks, unhookedClientRepos, } from "./lefthook-hooks.js";
37
38
  export { CLIENT_LINE_MAX, clientLineOf, findProjectBySlugId, LINEAR_API_TOKEN_ENV, LinearAuthError, LinearProjectNotFoundError, linearProject, linearProjectIssues, linearRequest, } from "./linear-project.js";
38
39
  export { createLogger, redactFields, } from "./log.js";
39
40
  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";
41
+ export { n8nDrafts, } from "./n8n-drafts.js";
40
42
  export { extractNodeOutputs, listN8nExecutions, listNodesRun, unflattenExecutionData, } from "./n8n-executions.js";
43
+ export { n8nExport, sanitizeClientExport, } from "./n8n-export.js";
41
44
  export { newClient, SLUG_PATTERN, } from "./new-client.js";
42
45
  export { opInstallCommand, opInstallFix, opIntegrationFix } from "./op-cli.js";
43
46
  export { defaultOpTitle, mintToOnePassword, } from "./op-store.js";
@@ -0,0 +1,110 @@
1
+ import { type LiveWorkflow, type WorkflowCredentialSlots } from "./agent-mirror.js";
2
+ import type { ExecFileFn } from "./exec.js";
3
+ import { type BuildsManifestState, type ManifestBuildStatus } from "./portal-sync-builds.js";
4
+ /** How a live workflow was found to be this client's. */
5
+ export type N8nDraftSelectedBy =
6
+ /** It has the tag that CLIENT.md's `n8n_tag` names. */
7
+ "tag"
8
+ /** A `## Builds` row names its id. */
9
+ | "builds"
10
+ /** An export in workflows/ records its id. */
11
+ | "export";
12
+ export interface N8nDraftWorkflow {
13
+ id: string;
14
+ name: string;
15
+ /** `active` = published and on. `draft` = not active. `archived` = archived in n8n. */
16
+ state: "active" | "draft" | "archived";
17
+ /** An active workflow with saved changes that are not published. Null = the instance does not say. */
18
+ hasUnpublishedChanges: boolean | null;
19
+ tags: string[];
20
+ /** Credential slot names per node type. Never a credential id or name. */
21
+ credentialSlots: WorkflowCredentialSlots[];
22
+ updatedAt: string | null;
23
+ selectedBy: N8nDraftSelectedBy[];
24
+ /** The `## Builds` row that names this workflow, when there is one. */
25
+ build: string | null;
26
+ buildStatus: ManifestBuildStatus | null;
27
+ /** Its export in workflows/ (joined by id). `stale` = the instance changed after the last commit of the file. */
28
+ export: {
29
+ file: string;
30
+ state: "current" | "stale";
31
+ } | null;
32
+ }
33
+ export interface N8nDraftsDiff {
34
+ /** The instance changed after the export's last commit. Compare them: a newer time alone is not proof. */
35
+ staleExports: Array<{
36
+ file: string;
37
+ workflowId: string;
38
+ name: string;
39
+ exportedAt: string | null;
40
+ liveUpdatedAt: string | null;
41
+ }>;
42
+ /** A client workflow (not archived) with no export that records its id. */
43
+ missingExports: Array<{
44
+ workflowId: string;
45
+ name: string;
46
+ }>;
47
+ /**
48
+ * An export that joins to no live workflow by id. `no-live-workflow`: the
49
+ * instance has none, archived ones included. `no-recorded-id`: the file
50
+ * records no live id, so it cannot be joined (a name is never used).
51
+ */
52
+ orphanExports: Array<{
53
+ file: string;
54
+ name: string;
55
+ reason: "no-live-workflow" | "no-recorded-id";
56
+ }>;
57
+ /** An agent row (not retired) whose workflow_id the instance does not have. */
58
+ buildsWithoutWorkflow: Array<{
59
+ build: string;
60
+ workflowId: string;
61
+ status: ManifestBuildStatus;
62
+ }>;
63
+ /** An active client workflow that no Builds row names. A helper workflow is expected here. */
64
+ activeWithoutBuild: Array<{
65
+ workflowId: string;
66
+ name: string;
67
+ }>;
68
+ }
69
+ export interface N8nDraftsResult {
70
+ workspaceDir: string;
71
+ generatedAt: string;
72
+ slug: string;
73
+ /** CLIENT.md's `n8n_tag`, or null when it has none (or the template placeholder). */
74
+ n8nTag: string | null;
75
+ /** By name. */
76
+ workflows: N8nDraftWorkflow[];
77
+ diff: N8nDraftsDiff;
78
+ /** `ok`, or why the Builds diff did not run. */
79
+ buildsState: BuildsManifestState | "no-client-md";
80
+ /** False = no commit time for any export, so `stale` was not checked. */
81
+ commitTimesAvailable: boolean;
82
+ notes: string[];
83
+ }
84
+ export interface N8nDraftsOptions {
85
+ /** The installagent/ workspace root (contains clients/). */
86
+ workspaceDir?: string;
87
+ /** The client, without the `client-` prefix. */
88
+ slug: string;
89
+ /** n8n API base incl. /api/v1; defaults to $N8N_API_URL. */
90
+ baseUrl?: string;
91
+ /** Defaults to $N8N_API_KEY. */
92
+ apiKey?: string;
93
+ env?: NodeJS.ProcessEnv;
94
+ fetchImpl?: typeof fetch;
95
+ /** `git log` for the exports' commit times. Injectable for tests. */
96
+ execFileImpl?: ExecFileFn;
97
+ /** The live list, when the caller already read it. n8n is then not called. */
98
+ liveWorkflows?: LiveWorkflow[];
99
+ now?: () => Date;
100
+ }
101
+ /**
102
+ * One client's n8n workflows and how they compare with the client checkout.
103
+ *
104
+ * A workflow is the client's when one of these is true (nothing else on a
105
+ * workflow says whose it is): it has the tag CLIENT.md's `n8n_tag` names; a
106
+ * `## Builds` row names its id; an export in workflows/ records its id. Most
107
+ * workflows on the instance have no tag, so an untagged helper that no row and
108
+ * no export names is NOT listed: tag it in n8n, or export it.
109
+ */
110
+ export declare function n8nDrafts(options: N8nDraftsOptions): Promise<N8nDraftsResult>;
@@ -0,0 +1,157 @@
1
+ // `ia n8n drafts <slug>` — what does n8n hold for one client, and does the
2
+ // client checkout agree?
3
+ //
4
+ // Before a technician changes a client workflow they need three answers that
5
+ // took a browser and a guess: which workflows are this client's, which of them
6
+ // are published (and is the published version the saved one), and are the
7
+ // exports and the `## Builds` rows in the repo still true. This is that read.
8
+ //
9
+ // STRICTLY READ-ONLY. One GET /workflows read (`fetchLiveWorkflows`, shared
10
+ // with client-drift and agent-mirror), file reads in the checkout, `git log`
11
+ // for each export's commit time. It never writes to n8n and never writes a file.
12
+ //
13
+ // NO CREDENTIAL DATA. A node's credentials come back from n8n as
14
+ // `{ <slot>: { id, name } }`. `fetchLiveWorkflows` keeps the slot names only,
15
+ // so an id or a credential's display name (which can hold a mailbox address)
16
+ // is not in memory when this module builds its result.
17
+ import { existsSync, readFileSync } from "node:fs";
18
+ import { join, resolve } from "node:path";
19
+ import { checkAgentMirror, fetchLiveWorkflows, } from "./agent-mirror.js";
20
+ import { readManifestKey } from "./client-manifest.js";
21
+ import { parseBuildsManifest, } from "./portal-sync-builds.js";
22
+ import { selectClientSlugs } from "./template-sync.js";
23
+ const stateOf = (w) => w.archived ? "archived" : w.active ? "active" : "draft";
24
+ /**
25
+ * One client's n8n workflows and how they compare with the client checkout.
26
+ *
27
+ * A workflow is the client's when one of these is true (nothing else on a
28
+ * workflow says whose it is): it has the tag CLIENT.md's `n8n_tag` names; a
29
+ * `## Builds` row names its id; an export in workflows/ records its id. Most
30
+ * workflows on the instance have no tag, so an untagged helper that no row and
31
+ * no export names is NOT listed: tag it in n8n, or export it.
32
+ */
33
+ export async function n8nDrafts(options) {
34
+ const workspaceDir = resolve(options.workspaceDir ?? ".");
35
+ const { slugs: [slug], } = selectClientSlugs(workspaceDir, { slug: options.slug }, "n8n drafts");
36
+ const dir = join(workspaceDir, "clients", `client-${slug}`);
37
+ const now = (options.now ?? (() => new Date()))();
38
+ const live = options.liveWorkflows ?? (await fetchLiveWorkflows(options));
39
+ const byId = new Map(live.map((w) => [w.id, w]));
40
+ const clientMdPath = join(dir, "CLIENT.md");
41
+ const clientMd = existsSync(clientMdPath) ? readFileSync(clientMdPath, "utf8") : null;
42
+ const tagValue = clientMd ? readManifestKey(clientMd, "n8n_tag")?.split(/\s+/)[0] : undefined;
43
+ const n8nTag = tagValue && !/[<>]|_HERE/.test(tagValue) ? tagValue : null;
44
+ const manifest = clientMd === null ? null : parseBuildsManifest(clientMd);
45
+ const buildsState = manifest?.state ?? "no-client-md";
46
+ const agentRows = (manifest?.state === "ok" ? manifest.rows : []).filter((row) => row.type === "agent" && Boolean(row.workflowId));
47
+ const rowByWorkflow = new Map(agentRows.map((row) => [row.workflowId, row]));
48
+ const mirror = await checkAgentMirror({
49
+ workspaceDir,
50
+ client: slug,
51
+ liveWorkflows: live,
52
+ execFileImpl: options.execFileImpl,
53
+ });
54
+ const repoFile = (file) => (file ?? "").replace(`clients/client-${slug}/`, "");
55
+ const exportByWorkflow = new Map();
56
+ const diff = {
57
+ staleExports: [],
58
+ missingExports: [],
59
+ orphanExports: [],
60
+ buildsWithoutWorkflow: [],
61
+ activeWithoutBuild: [],
62
+ };
63
+ for (const row of mirror.rows) {
64
+ const file = repoFile(row.file);
65
+ // Joined by id, or not joined: a name match is a guess (agent-mirror lesson 2).
66
+ if (row.matchedBy !== "id" || !row.workflowId) {
67
+ diff.orphanExports.push({
68
+ file,
69
+ name: row.workflowName,
70
+ reason: row.matchedBy === "name" ? "no-recorded-id" : "no-live-workflow",
71
+ });
72
+ continue;
73
+ }
74
+ const stale = row.state === "needs-diff";
75
+ exportByWorkflow.set(row.workflowId, { file, state: stale ? "stale" : "current" });
76
+ if (stale) {
77
+ diff.staleExports.push({
78
+ file,
79
+ workflowId: row.workflowId,
80
+ name: row.workflowName,
81
+ exportedAt: row.exportedAt,
82
+ liveUpdatedAt: row.liveUpdatedAt,
83
+ });
84
+ }
85
+ }
86
+ const tag = n8nTag?.toLowerCase();
87
+ const workflows = [];
88
+ for (const w of live) {
89
+ const selectedBy = [];
90
+ if (tag && w.tags.some((name) => name.toLowerCase() === tag))
91
+ selectedBy.push("tag");
92
+ if (rowByWorkflow.has(w.id))
93
+ selectedBy.push("builds");
94
+ if (exportByWorkflow.has(w.id))
95
+ selectedBy.push("export");
96
+ if (selectedBy.length === 0)
97
+ continue;
98
+ const row = rowByWorkflow.get(w.id);
99
+ workflows.push({
100
+ id: w.id,
101
+ name: w.name,
102
+ state: stateOf(w),
103
+ hasUnpublishedChanges: w.hasUnpublishedChanges,
104
+ tags: w.tags,
105
+ credentialSlots: w.credentialSlots,
106
+ updatedAt: w.updatedAt,
107
+ selectedBy,
108
+ build: row?.build ?? null,
109
+ buildStatus: row?.status ?? null,
110
+ export: exportByWorkflow.get(w.id) ?? null,
111
+ });
112
+ }
113
+ workflows.sort((a, b) => a.name.localeCompare(b.name, "en") || a.id.localeCompare(b.id, "en"));
114
+ for (const w of workflows) {
115
+ if (w.state !== "archived" && !w.export) {
116
+ diff.missingExports.push({ workflowId: w.id, name: w.name });
117
+ }
118
+ if (buildsState === "ok" && w.state === "active" && !w.build) {
119
+ diff.activeWithoutBuild.push({ workflowId: w.id, name: w.name });
120
+ }
121
+ }
122
+ for (const row of agentRows) {
123
+ if (!byId.has(row.workflowId) && row.status !== "retired") {
124
+ diff.buildsWithoutWorkflow.push({
125
+ build: row.build,
126
+ workflowId: row.workflowId,
127
+ status: row.status,
128
+ });
129
+ }
130
+ }
131
+ const notes = [
132
+ "Read-only: one GET /workflows read, file reads in the checkout, `git log` per export. Nothing was written to n8n or to the repo.",
133
+ `A workflow is listed when it has the CLIENT.md n8n_tag (${n8nTag ?? "none set"}), a ## Builds row names its id, or an export records its id. An untagged workflow that no row and no export names is not listed.`,
134
+ "`stale` means the instance changed after the last commit of the export: compare them. A newer time alone is not proof (deactivating a workflow changes it).",
135
+ "Credential slots are slot names only. Credential ids and credential names are never read into the result.",
136
+ ];
137
+ if (buildsState !== "ok") {
138
+ notes.push(`The Builds diff did not run: the CLIENT.md ## Builds block is ${buildsState}${manifest?.errors[0] ? ` (${manifest.errors[0]})` : ""}.`);
139
+ }
140
+ else if (diff.activeWithoutBuild.length > 0) {
141
+ notes.push("An active workflow with no Builds row is expected for a helper or a tool workflow (one row per agent). It is a prompt to look, not a fault.");
142
+ }
143
+ if (mirror.rows.length > 0 && !mirror.commitTimesAvailable) {
144
+ notes.push("No commit time could be read for any export (not a git checkout), so `stale` was NOT checked.");
145
+ }
146
+ return {
147
+ workspaceDir,
148
+ generatedAt: now.toISOString(),
149
+ slug,
150
+ n8nTag,
151
+ workflows,
152
+ diff,
153
+ buildsState,
154
+ commitTimesAvailable: mirror.commitTimesAvailable,
155
+ notes,
156
+ };
157
+ }
@@ -0,0 +1,75 @@
1
+ import type { ExecFileFn } from "./exec.js";
2
+ import { type N8nDraftWorkflow } from "./n8n-drafts.js";
3
+ export interface ClientWorkflowExport {
4
+ /** The live n8n workflow id: what every drift check joins on. */
5
+ id: string;
6
+ name: string;
7
+ nodes: Array<Record<string, unknown>>;
8
+ connections: Record<string, unknown>;
9
+ settings: Record<string, unknown>;
10
+ }
11
+ /**
12
+ * A raw n8n workflow reduced to a client export. The node strip is the bank's
13
+ * (`sanitizeN8nWorkflow`: credentials and webhook ids removed; pinData,
14
+ * staticData, versions, tags and sharing never copied). Two differences from
15
+ * a bank template: the settings stay the LIVE ones (an export says what runs
16
+ * for this client, error workflow included), and each credential slot comes
17
+ * back as a placeholder so a reader sees which node needs which credential type.
18
+ */
19
+ export declare function sanitizeClientExport(raw: Record<string, unknown>): ClientWorkflowExport;
20
+ export interface N8nExportItem {
21
+ workflowId: string;
22
+ name: string;
23
+ state: N8nDraftWorkflow["state"];
24
+ /** Path in the client repo, for example workflows/acme-triage-reader.json. */
25
+ file: string;
26
+ /** `unchanged` = the file already holds exactly this export. */
27
+ action: "create" | "update" | "unchanged";
28
+ /**
29
+ * How an existing file was found. `name` = the file records no id and is the
30
+ * only export with this workflow name; the new content records the id.
31
+ */
32
+ joinedBy: "id" | "name" | null;
33
+ /** How many credential slots got a placeholder. */
34
+ credentialSlots: number;
35
+ written: boolean;
36
+ /** The workflow could not be read. Nothing was written for it. */
37
+ error?: string;
38
+ }
39
+ export interface N8nExportResult {
40
+ workspaceDir: string;
41
+ generatedAt: string;
42
+ slug: string;
43
+ /** False = a plan only. */
44
+ write: boolean;
45
+ /** By workflow name. */
46
+ items: N8nExportItem[];
47
+ notes: string[];
48
+ }
49
+ export interface N8nExportOptions {
50
+ /** The installagent/ workspace root (contains clients/). */
51
+ workspaceDir?: string;
52
+ /** The client, without the `client-` prefix. */
53
+ slug: string;
54
+ /** Only this workflow id (it must be one of the client's). */
55
+ workflowId?: string;
56
+ /** Write the files. Default false: plan only. */
57
+ write?: boolean;
58
+ /** n8n API base incl. /api/v1; defaults to $N8N_API_URL. */
59
+ baseUrl?: string;
60
+ /** Defaults to $N8N_API_KEY. */
61
+ apiKey?: string;
62
+ env?: NodeJS.ProcessEnv;
63
+ fetchImpl?: typeof fetch;
64
+ /** `git log` (through n8nDrafts). Injectable for tests. */
65
+ execFileImpl?: ExecFileFn;
66
+ now?: () => Date;
67
+ }
68
+ /**
69
+ * Plan (and with `write`, write) the exports of one client's live workflows.
70
+ * The client's workflows are the ones `n8nDrafts` lists (the CLIENT.md
71
+ * n8n_tag, a Builds row, or an export that records the id), archived ones left
72
+ * out. An existing export is found by its recorded id; a file with no id is
73
+ * taken over only when it is the one export with exactly the workflow's name.
74
+ */
75
+ export declare function n8nExport(options: N8nExportOptions): Promise<N8nExportResult>;
@@ -0,0 +1,176 @@
1
+ // `ia n8n export <slug>` — write a client's live n8n workflows into its
2
+ // checkout as reviewed exports.
3
+ //
4
+ // `ia n8n drafts` and `ia client-drift` say which exports are stale, missing
5
+ // or cannot be joined (no recorded id). Until now the fix was a browser
6
+ // download and a hand scrub of credential ids. This is that step as one
7
+ // command, with the two rules the drift checks depend on:
8
+ //
9
+ // 1. THE EXPORT RECORDS ITS LIVE ID (`"id"`), so every later check joins by
10
+ // id and a rename on the instance never reads as a deletion.
11
+ // 2. NO CREDENTIAL ID AND NO CREDENTIAL NAME reaches the file. Each slot
12
+ // keeps its type with a `__SET_IN_N8N__<type>__` placeholder id, the form
13
+ // client-template's repo-lint accepts.
14
+ //
15
+ // It reads n8n (GET only), and it writes ONLY inside clients/client-<slug>/
16
+ // workflows/, and only with `write`. It never commits, never pushes, and
17
+ // never changes anything on the instance. Node parameters are kept as they
18
+ // are (that is the point of an export), and they can hold a client address:
19
+ // a person reads the diff before the commit, as CADENCE.md says.
20
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
21
+ import { writeFile } from "node:fs/promises";
22
+ import { join, resolve } from "node:path";
23
+ import { fetchLiveWorkflows } from "./agent-mirror.js";
24
+ import { N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError, sanitizeN8nWorkflow, } from "./agent-templates.js";
25
+ import { n8nDrafts } from "./n8n-drafts.js";
26
+ /** A placeholder id that client-template's repo-lint accepts (`PLACEHOLDER_ID`). */
27
+ const credentialPlaceholder = (type) => `__SET_IN_N8N__${type}__`;
28
+ const CREDENTIAL_NAME_PLACEHOLDER = "__SET_IN_N8N__";
29
+ /**
30
+ * A raw n8n workflow reduced to a client export. The node strip is the bank's
31
+ * (`sanitizeN8nWorkflow`: credentials and webhook ids removed; pinData,
32
+ * staticData, versions, tags and sharing never copied). Two differences from
33
+ * a bank template: the settings stay the LIVE ones (an export says what runs
34
+ * for this client, error workflow included), and each credential slot comes
35
+ * back as a placeholder so a reader sees which node needs which credential type.
36
+ */
37
+ export function sanitizeClientExport(raw) {
38
+ const { workflow, strippedCredentials } = sanitizeN8nWorkflow(raw);
39
+ const slotsByNode = new Map();
40
+ for (const { node, type } of strippedCredentials) {
41
+ slotsByNode.set(node, [...(slotsByNode.get(node) ?? []), type]);
42
+ }
43
+ const nodes = workflow.nodes.map((node) => {
44
+ const slots = slotsByNode.get(String(node.name));
45
+ if (!slots)
46
+ return node;
47
+ return {
48
+ ...node,
49
+ credentials: Object.fromEntries(slots.map((type) => [
50
+ type,
51
+ { id: credentialPlaceholder(type), name: CREDENTIAL_NAME_PLACEHOLDER },
52
+ ])),
53
+ };
54
+ });
55
+ const settings = raw.settings && typeof raw.settings === "object"
56
+ ? raw.settings
57
+ : {};
58
+ return {
59
+ id: String(raw.id ?? ""),
60
+ name: workflow.name,
61
+ nodes,
62
+ connections: workflow.connections,
63
+ settings,
64
+ };
65
+ }
66
+ const fileSlug = (name) => name
67
+ .toLowerCase()
68
+ .replace(/[^a-z0-9]+/g, "-")
69
+ .replace(/^-+|-+$/g, "") || "workflow";
70
+ const message = (error) => (error instanceof Error ? error.message : String(error));
71
+ /**
72
+ * Plan (and with `write`, write) the exports of one client's live workflows.
73
+ * The client's workflows are the ones `n8nDrafts` lists (the CLIENT.md
74
+ * n8n_tag, a Builds row, or an export that records the id), archived ones left
75
+ * out. An existing export is found by its recorded id; a file with no id is
76
+ * taken over only when it is the one export with exactly the workflow's name.
77
+ */
78
+ export async function n8nExport(options) {
79
+ const workspaceDir = resolve(options.workspaceDir ?? ".");
80
+ const env = options.env ?? process.env;
81
+ const baseUrl = (options.baseUrl ?? env[N8N_API_URL_ENV])?.replace(/\/+$/, "");
82
+ const apiKey = options.apiKey ?? env[N8N_API_KEY_ENV];
83
+ if (!baseUrl || !apiKey) {
84
+ throw new N8nAuthError(`n8n API not configured — set $${N8N_API_URL_ENV} (incl. /api/v1) and $${N8N_API_KEY_ENV} (1Password).`);
85
+ }
86
+ const fetchImpl = options.fetchImpl ?? fetch;
87
+ const now = (options.now ?? (() => new Date()))();
88
+ const liveWorkflows = await fetchLiveWorkflows({ baseUrl, apiKey, fetchImpl });
89
+ const drafts = await n8nDrafts({
90
+ workspaceDir,
91
+ slug: options.slug,
92
+ liveWorkflows,
93
+ execFileImpl: options.execFileImpl,
94
+ now: () => now,
95
+ });
96
+ const slug = drafts.slug;
97
+ const repoDir = join(workspaceDir, "clients", `client-${slug}`);
98
+ let targets = drafts.workflows.filter((w) => w.state !== "archived");
99
+ if (options.workflowId) {
100
+ targets = targets.filter((w) => w.id === options.workflowId);
101
+ if (targets.length === 0) {
102
+ throw new Error(`"${options.workflowId}" is not one of ${slug}'s workflows (run \`ia n8n drafts ${slug}\` for the list; an archived workflow is not exported).`);
103
+ }
104
+ }
105
+ // A file with no recorded id may be taken over only when its name is unique among them.
106
+ const unjoined = new Map();
107
+ for (const orphan of drafts.diff.orphanExports) {
108
+ if (orphan.reason !== "no-recorded-id")
109
+ continue;
110
+ unjoined.set(orphan.name, [...(unjoined.get(orphan.name) ?? []), orphan.file]);
111
+ }
112
+ const workflowsDir = join(repoDir, "workflows");
113
+ const taken = new Set(existsSync(workflowsDir) ? readdirSync(workflowsDir).map((file) => `workflows/${file}`) : []);
114
+ const items = [];
115
+ for (const target of targets) {
116
+ const byName = unjoined.get(target.name);
117
+ const existing = target.export
118
+ ? { file: target.export.file, joinedBy: "id" }
119
+ : byName?.length === 1
120
+ ? { file: byName[0], joinedBy: "name" }
121
+ : null;
122
+ let file = existing?.file ?? `workflows/${fileSlug(target.name)}.json`;
123
+ if (!existing && taken.has(file))
124
+ file = `workflows/${fileSlug(target.name)}-${target.id}.json`;
125
+ taken.add(file);
126
+ const item = {
127
+ workflowId: target.id,
128
+ name: target.name,
129
+ state: target.state,
130
+ file,
131
+ action: existing ? "update" : "create",
132
+ joinedBy: existing?.joinedBy ?? null,
133
+ credentialSlots: 0,
134
+ written: false,
135
+ };
136
+ items.push(item);
137
+ try {
138
+ const response = await fetchImpl(`${baseUrl}/workflows/${encodeURIComponent(target.id)}`, {
139
+ headers: { "X-N8N-API-KEY": apiKey, accept: "application/json" },
140
+ });
141
+ if (!response.ok)
142
+ throw new Error(`n8n API ${response.status} reading the workflow`);
143
+ const exported = sanitizeClientExport((await response.json()));
144
+ item.credentialSlots = exported.nodes.reduce((sum, node) => sum + Object.keys(node.credentials ?? {}).length, 0);
145
+ const text = `${JSON.stringify(exported, null, 2)}\n`;
146
+ const path = join(repoDir, file);
147
+ if (existing && existsSync(path) && readFileSync(path, "utf8") === text) {
148
+ item.action = "unchanged";
149
+ }
150
+ else if (options.write) {
151
+ await writeFile(path, text);
152
+ item.written = true;
153
+ }
154
+ }
155
+ catch (error) {
156
+ item.error = message(error).split("\n")[0];
157
+ }
158
+ }
159
+ const notes = [
160
+ options.write
161
+ ? "Files were written in workflows/ only. Nothing was committed, and nothing on n8n was changed."
162
+ : "Plan only: nothing was written. Add --write to write the files.",
163
+ "Each export records the live workflow id and has a placeholder for each credential id and name. Node parameters are kept as they are and can hold a client address: read the diff, run `node ci/repo-lint.mjs .`, then commit the export with its other surfaces (CADENCE.md).",
164
+ ];
165
+ if (items.some((item) => item.joinedBy === "name")) {
166
+ notes.push("Some files were found by name: they record no id, and each is the only export with that workflow name. Check that each one is the same workflow before you commit.");
167
+ }
168
+ return {
169
+ workspaceDir,
170
+ generatedAt: now.toISOString(),
171
+ slug,
172
+ write: options.write ?? false,
173
+ items,
174
+ notes,
175
+ };
176
+ }
package/dist/standup.d.ts CHANGED
@@ -41,7 +41,7 @@ export interface StandupRepo {
41
41
  /** null when the repo has no ci/repo-lint.mjs to run. */
42
42
  repoLint: StandupRepoLint | null;
43
43
  hooksInstalled: boolean;
44
- /** Newest ISO date found in docs/00-delivery-log.md, or null. */
44
+ /** Newest entry-heading date (`## YYYY-MM-DD`) in docs/00-delivery-log.md, or null. */
45
45
  lastShipped: string | null;
46
46
  lastShippedAgeDays: number | null;
47
47
  callPrep: StandupCallPrep;
@@ -76,6 +76,8 @@ export interface StandupOptions {
76
76
  env?: NodeJS.ProcessEnv;
77
77
  now?: () => Date;
78
78
  }
79
+ /** The dates of a delivery log's entry headings, in file order. Fenced examples are skipped. */
80
+ export declare function deliveryLogEntryDates(log: string): string[];
79
81
  /**
80
82
  * Cross-client morning report: for every clients/client-* checkout — git
81
83
  * state, repo-lint, lefthook hooks, delivery-log recency, call-prep
package/dist/standup.js CHANGED
@@ -13,7 +13,13 @@ import { createLogger } from "./log.js";
13
13
  const LINEAR_PROJECT_FIELD_PATTERN = /^linear_project:\s*(\S+)\s*$/m;
14
14
  /** Call-note files are ISO-dated: YYYY-MM-DD.md or YYYY-MM-DD-<hint>.md. */
15
15
  const CALL_DATE_PATTERN = /^(\d{4}-\d{2}-\d{2})/;
16
- const DATE_PATTERN = /\b20\d{2}-\d{2}-\d{2}\b/g;
16
+ /**
17
+ * A delivery-log entry heading: `## YYYY-MM-DD — <what shipped>`. The same rule
18
+ * as client-template's ci/log-progress.mjs (ENTRY_HEADING) and client-drift's
19
+ * LOG_HEADING. Only a heading dates an entry: body text names contract ends,
20
+ * review dates and renewals, which are not shipping dates.
21
+ */
22
+ const LOG_ENTRY_HEADING = /^##\s+(\d{4}-\d{2}-\d{2})\b/;
17
23
  const DAY_MS = 24 * 60 * 60 * 1000;
18
24
  /** Fetch enough open issues that the counts are honest, then summarize. */
19
25
  const LINEAR_COUNT_LIMIT = 250;
@@ -41,14 +47,29 @@ function ageDays(isoDate, now) {
41
47
  const then = Date.parse(`${isoDate}T00:00:00Z`);
42
48
  return Math.max(0, Math.floor((now.getTime() - then) / DAY_MS));
43
49
  }
50
+ /** The dates of a delivery log's entry headings, in file order. Fenced examples are skipped. */
51
+ export function deliveryLogEntryDates(log) {
52
+ const dates = [];
53
+ let fenced = false;
54
+ for (const line of log.split("\n")) {
55
+ if (/^\s*```/.test(line)) {
56
+ fenced = !fenced;
57
+ continue;
58
+ }
59
+ if (fenced)
60
+ continue;
61
+ const date = LOG_ENTRY_HEADING.exec(line)?.[1];
62
+ if (date)
63
+ dates.push(date);
64
+ }
65
+ return dates;
66
+ }
44
67
  function lastShippedDate(repoDir) {
45
68
  const logPath = join(repoDir, "docs", "00-delivery-log.md");
46
69
  if (!existsSync(logPath))
47
70
  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;
71
+ // Newest entry heading, wherever it is in the file (logs are written both ways).
72
+ return deliveryLogEntryDates(readFileSync(logPath, "utf8")).sort().at(-1) ?? null;
52
73
  }
53
74
  /**
54
75
  * Registry read, deliberately minimal: call file NAMES (for their ISO date
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@installagent/sdk",
3
- "version": "0.16.1",
3
+ "version": "0.18.0",
4
4
  "description": "Install Agent's shared SDK for internal team operations (client repos, n8n workflows, docs search, and more).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",