@installagent/sdk 0.14.0 → 0.16.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.
@@ -0,0 +1,460 @@
1
+ // `ia tech-call prep <slug>` — the machine half of "am I ready for this call?".
2
+ // The tech-call-prep skill's come-prepared checklist used to be checked by a
3
+ // person, by hand, the night before: is the technician on the invite, does the
4
+ // vault open, does the client have a portal login, do the Linear issues exist,
5
+ // is there ONE agenda Doc. Each of those is a lookup. This command does the
6
+ // lookups and writes the result into the PREP GAPS block of
7
+ // docs/05-call-agenda.md. What only a person can do stays a fixed list.
8
+ //
9
+ // Read-only on every outside system. `write` changes ONE block of ONE file in
10
+ // the working tree and never commits. A check that cannot run (a missing
11
+ // token, no network, a calendar nobody shared) is `skipped` with the reason —
12
+ // never `pass`. That rule is the point: a skipped check that reads as green is
13
+ // how a gap reaches the call.
14
+ import { existsSync } from "node:fs";
15
+ import { readdir, readFile, writeFile } from "node:fs/promises";
16
+ import { join, resolve } from "node:path";
17
+ import { AIRTABLE_API_TOKEN_ENV, clientDriveSearch, DEFAULT_AIRTABLE_BASE_ID, DEFAULT_AIRTABLE_TABLE_ID, GOOGLE_SERVICE_ACCOUNT_KEY_ENV, } from "./client-drive.js";
18
+ import { clientLinearProject } from "./client-linear.js";
19
+ import { readManifestKey } from "./client-manifest.js";
20
+ import { execFailureDetail, execFileAsync } from "./exec.js";
21
+ import { getServiceAccountAccessToken } from "./google-service-account.js";
22
+ import { SLUG_PATTERN } from "./new-client.js";
23
+ import { portalListOrgs } from "./portal-admin.js";
24
+ import { AGENDA_FILE, PREP_GAPS_END, PREP_GAPS_START } from "./tech-call-agenda.js";
25
+ export const PREP_CALENDAR_ID_ENV = "IA_PREP_CALENDAR_ID";
26
+ export const AGENDA_DOC_MARKER = "tech-discovery-agenda";
27
+ export const PORTAL_LOGIN_ITEM_TITLE = "Install Agent client portal";
28
+ const CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar.readonly";
29
+ const INTERNAL_DOMAINS = ["installagent.com", "rebarlabs.io"];
30
+ const SKELETON = ["docs", "workflows", "data", "evidence", "onboarding.html", "CLIENT.md"];
31
+ const DOCS = [
32
+ "01-overview.md",
33
+ "02-tech-spec.md",
34
+ "03-client-onboarding.md",
35
+ "04-access-checklist.md",
36
+ ];
37
+ const pass = (id, detail) => ({ id, status: "pass", detail, fix: "" });
38
+ const gap = (id, detail, fix) => ({
39
+ id,
40
+ status: "gap",
41
+ detail,
42
+ fix,
43
+ });
44
+ const skipped = (id, why, fix) => ({
45
+ id,
46
+ status: "skipped",
47
+ detail: `Not checked: ${why}`,
48
+ fix,
49
+ });
50
+ export function checkScaffold(files) {
51
+ const missing = SKELETON.filter((name) => !files.entries.includes(name));
52
+ if (missing.length > 0) {
53
+ return gap("repo", `The repo lacks ${missing.join(", ")}.`, "Compare with clients/client-template and `ia template-sync`.");
54
+ }
55
+ if (files.onboardingHtml.includes("WAITING_FOR_CALL:START")) {
56
+ return gap("repo", "onboarding.html shows the WAITING FOR CALL banner: the kickoff has no call note yet.", "Merge the sales-call note in team-clients; the kickoff then drafts the docs.");
57
+ }
58
+ return pass("repo", "The repo has the template skeleton and no waiting banner.");
59
+ }
60
+ /** The transcript check whose sources include `call`, newest first; or null. */
61
+ function evidenceFor(files, call) {
62
+ const names = Object.keys(files.evidence).sort().reverse();
63
+ for (const name of names) {
64
+ const text = files.evidence[name] ?? "";
65
+ const sources = /^> Sources: transcripts ([^;]*);/m.exec(text)?.[1] ?? "";
66
+ if (sources.split(",").some((source) => source.trim().startsWith(call)))
67
+ return { name, text };
68
+ }
69
+ return null;
70
+ }
71
+ export function checkDocs(files) {
72
+ const missing = DOCS.filter((name) => !files.docs[name]?.trim());
73
+ if (missing.length > 0) {
74
+ return [
75
+ gap("docs", `docs/ lacks ${missing.join(", ")}.`, "Run the engagement-spec skill, or wait for the kickoff's docs step."),
76
+ ];
77
+ }
78
+ const tokens = new Set();
79
+ for (const text of [files.onboardingHtml, ...DOCS.map((name) => files.docs[name] ?? "")]) {
80
+ for (const token of text.match(/REPLACE_WITH_[A-Z_]+/g) ?? [])
81
+ tokens.add(token);
82
+ }
83
+ const checks = [];
84
+ checks.push(tokens.size === 0
85
+ ? pass("tokens", "No REPLACE_WITH_ token is left in docs 01-04 or onboarding.html.")
86
+ : gap("tokens", `${tokens.size} template token(s) are not filled: ${[...tokens].sort().slice(0, 6).join(", ")}${tokens.size > 6 ? ", ..." : ""}.`, "Fill them from the call, or make each one a question on the agenda."));
87
+ const latest = files.registryCalls.at(-1);
88
+ if (!latest) {
89
+ checks.push(gap("docs", "The registry has no call note for this client.", "Merge the call-notes PR in team-clients."));
90
+ return checks;
91
+ }
92
+ const evidence = evidenceFor(files, latest);
93
+ if (!evidence) {
94
+ checks.push(gap("docs", `Nothing shows that the docs were checked against the latest call (${latest}).`, "Run `ia tech-call verify <slug> --write`."));
95
+ return checks;
96
+ }
97
+ checks.push(pass("docs", `Docs 01-04 were checked against the ${latest} call (${evidence.name}).`));
98
+ const counts = /\*\*(\d+) claims:\*\* (\d+) supported, (\d+) unverified, (\d+) contradicted/.exec(evidence.text);
99
+ const open = counts ? Number(counts[3]) + Number(counts[4]) : 0;
100
+ checks.push(open === 0
101
+ ? pass("claims", "The transcript check found no unverified or contradicted claim.")
102
+ : gap("claims", `${counts?.[3]} unverified and ${counts?.[4]} contradicted claim(s) are in the docs.`, `Read evidence/${evidence.name}; present each one as a question, not as a fact.`));
103
+ return checks;
104
+ }
105
+ export function checkAgendaFile(files, callDate) {
106
+ const agenda = files.docs["05-call-agenda.md"];
107
+ if (!agenda?.trim()) {
108
+ return gap("agenda-file", "docs/05-call-agenda.md does not exist.", "Run `ia tech-call agenda <slug> --write`.");
109
+ }
110
+ if (!agenda.includes(PREP_GAPS_START) || !agenda.includes(PREP_GAPS_END)) {
111
+ return gap("agenda-file", "docs/05-call-agenda.md is in the old format (no prep-gaps block).", "Run `ia tech-call agenda <slug> --write` to replace it.");
112
+ }
113
+ const title = agenda.split("\n")[0] ?? "";
114
+ if (!title.includes(callDate)) {
115
+ return gap("agenda-file", `The agenda is not for ${callDate}: its title is "${title.replace(/^# /, "").slice(0, 80)}".`, `Run \`ia tech-call agenda <slug> --call-date ${callDate} --publish --write\`.`);
116
+ }
117
+ if (/No industry playbook/i.test(agenda)) {
118
+ return gap("agenda-file", "The agenda has no vertical context: no industry playbook matches this client.", "Prepare the vertical context by hand (team hub → Sales → Industry playbooks).");
119
+ }
120
+ return pass("agenda-file", `docs/05-call-agenda.md is the agenda for ${callDate}.`);
121
+ }
122
+ // ---------------------------------------------------------------------------
123
+ // Pure checks: outside systems (from probe results)
124
+ const domainOf = (email) => email.toLowerCase().split("@")[1] ?? "";
125
+ export function checkInvite(events, team, callDate) {
126
+ const share = `Share the calendar read-only with the service account and set ${PREP_CALENDAR_ID_ENV}, or check the invite by hand.`;
127
+ if (typeof events === "string")
128
+ return skipped("invite", events, share);
129
+ if (typeof team === "string")
130
+ return skipped("invite", team, "Check the invite by hand.");
131
+ if (!team.clientDomain) {
132
+ return skipped("invite", "the client's contact has no company email domain, so the event cannot be found by attendee", "Check the invite by hand.");
133
+ }
134
+ const event = events.find((e) => e.attendees.some((email) => domainOf(email) === team.clientDomain));
135
+ if (!event) {
136
+ return gap("invite", `No calendar event on ${callDate} has an attendee at ${team.clientDomain}.`, "Book the call, or pass --call-date with the real date.");
137
+ }
138
+ const on = new Set(event.attendees.map((email) => email.toLowerCase()));
139
+ const problems = [];
140
+ if (team.technicians.length === 0)
141
+ problems.push("no technician is linked on the CRM record");
142
+ for (const person of [...team.technicians, ...team.sales]) {
143
+ if (!on.has(person.email.toLowerCase()))
144
+ problems.push(`${person.name} is not on the invite`);
145
+ }
146
+ const strangers = [
147
+ ...new Set(event.attendees
148
+ .map(domainOf)
149
+ .filter((domain) => domain && domain !== team.clientDomain && !INTERNAL_DOMAINS.includes(domain))),
150
+ ];
151
+ if (strangers.length > 0) {
152
+ problems.push(`attendee(s) from ${strangers.join(", ")} are not in the registry`);
153
+ }
154
+ const clients = event.attendees.filter((email) => domainOf(email) === team.clientDomain).length;
155
+ return problems.length === 0
156
+ ? pass("invite", `The invite has the technician, sales and ${clients} client attendee(s).`)
157
+ : gap("invite", `On the invite "${event.summary.slice(0, 60)}": ${problems.join("; ")}.`, "Fix the invite before the call.");
158
+ }
159
+ export function checkVault(titles, vault) {
160
+ if (typeof titles === "string") {
161
+ const fix = `Run \`op vault get ${vault}\` yourself: the check proves access only for the person who runs it.`;
162
+ return [skipped("vault", titles, fix), skipped("portal-login", titles, fix)];
163
+ }
164
+ return [
165
+ pass("vault", `The 1Password vault "${vault}" exists and you can open it.`),
166
+ titles.includes(PORTAL_LOGIN_ITEM_TITLE)
167
+ ? pass("portal-login", `The vault holds the "${PORTAL_LOGIN_ITEM_TITLE}" login.`)
168
+ : gap("portal-login", `The vault has no "${PORTAL_LOGIN_ITEM_TITLE}" item: the client's portal password is not on file.`, "`ia portal set-password`, store it in the vault, send it by a secure link. Never read it out."),
169
+ ];
170
+ }
171
+ export function checkPortalOrg(exists, slug) {
172
+ if (typeof exists === "string")
173
+ return skipped("portal-org", exists, "Run `ia portal list` yourself.");
174
+ return exists
175
+ ? pass("portal-org", `The portal org "${slug}" exists.`)
176
+ : gap("portal-org", `The portal has no org "${slug}".`, "`ia portal create-org`, or run the kickoff's portal step.");
177
+ }
178
+ /** INS ids under `## Open questions...` of the tech spec. */
179
+ export function openQuestionIds(techSpec) {
180
+ const start = techSpec.search(/^#{2,3} (?:\d+\.\s*)?Open questions/im);
181
+ if (start === -1)
182
+ return [];
183
+ const rest = techSpec.slice(start).split("\n").slice(1);
184
+ const end = rest.findIndex((line) => /^#{1,3} /.test(line));
185
+ const section = (end === -1 ? rest : rest.slice(0, end)).join("\n");
186
+ return [...new Set(section.match(/\bINS-\d+\b/g) ?? [])];
187
+ }
188
+ export function checkLinear(open, techSpec) {
189
+ if (typeof open === "string")
190
+ return skipped("linear", open, "Run `ia client-linear <slug>` yourself.");
191
+ const ids = openQuestionIds(techSpec);
192
+ if (ids.length === 0) {
193
+ return gap("linear", "docs/02-tech-spec.md § Open questions lists no INS id.", "File each open question as a Linear issue (ask first: Linear is shared) and list the ids.");
194
+ }
195
+ const closed = ids.filter((id) => !open.includes(id));
196
+ return closed.length === 0
197
+ ? pass("linear", `All ${ids.length} open-question issue(s) are open in Linear.`)
198
+ : gap("linear", `${closed.join(", ")} ${closed.length === 1 ? "is" : "are"} listed as open in the spec but not open in Linear.`, "Write the answer into the spec and drop the id, or reopen the issue.");
199
+ }
200
+ export function checkAgendaDoc(titles, callDate) {
201
+ if (typeof titles === "string")
202
+ return skipped("agenda-doc", titles, "Open the client's Drive folder yourself.");
203
+ const agendas = titles.filter((title) => title.includes(AGENDA_DOC_MARKER));
204
+ const exact = `${callDate}-${AGENDA_DOC_MARKER}`;
205
+ if (agendas.length === 0) {
206
+ return gap("agenda-doc", "The Drive folder has no agenda Doc.", "`ia tech-call agenda <slug> --publish`.");
207
+ }
208
+ const stale = agendas.filter((title) => title !== exact);
209
+ if (!agendas.includes(exact)) {
210
+ return gap("agenda-doc", `No Doc is named "${exact}". Found: ${agendas.map((t) => `"${t}"`).join(", ")}.`, `\`ia tech-call agenda <slug> --call-date ${callDate} --publish\` renames the newest one in place.`);
211
+ }
212
+ return stale.length === 0
213
+ ? pass("agenda-doc", `The Drive folder has exactly one agenda Doc: "${exact}".`)
214
+ : gap("agenda-doc", `${stale.length} stale agenda Doc(s) are beside "${exact}": ${stale.map((t) => `"${t}"`).join(", ")}.`, "Delete the stale ones by hand, so nobody opens the wrong agenda.");
215
+ }
216
+ // ---------------------------------------------------------------------------
217
+ // Pure: the block
218
+ /** What only a person can do. Fixed text, on every agenda. */
219
+ export const MANUAL_PREP = [
220
+ "Watch the sales-call recording at 2x; check the read-back against the tape, not the notes.",
221
+ "Confirm the signed agreement is filed in the client's Drive folder (sales).",
222
+ "Open what you will share on screen 10 minutes before the call; presenter notes off.",
223
+ "ONE recorder only; red-dot check when the client joins.",
224
+ ];
225
+ export function renderPrepBlock(checks, checkedOn) {
226
+ const count = (status) => checks.filter((check) => check.status === status).length;
227
+ return [
228
+ "",
229
+ `_Checked ${checkedOn} by \`ia tech-call prep\`: ${count("pass")} pass, ${count("gap")} gap(s), ${count("skipped")} not checked._`,
230
+ "",
231
+ ...checks
232
+ .filter((check) => check.status === "gap")
233
+ .map((check) => `- [ ] ${check.detail} → ${check.fix}`),
234
+ ...checks
235
+ .filter((check) => check.status === "skipped")
236
+ .map((check) => `- [ ] NOT CHECKED (${check.id}): ${check.detail.replace(/^Not checked: /, "")} → ${check.fix}`),
237
+ ...(count("gap") + count("skipped") === 0 ? ["- No gap found by the machine checks."] : []),
238
+ "",
239
+ "A person does these:",
240
+ ...MANUAL_PREP.map((line) => `- [ ] ${line}`),
241
+ "",
242
+ ].join("\n");
243
+ }
244
+ /** docs/05 with its prep-gaps block replaced. Throws when the file has no block. */
245
+ export function withPrepBlock(agenda, block) {
246
+ const start = agenda.indexOf(PREP_GAPS_START);
247
+ const end = agenda.indexOf(PREP_GAPS_END);
248
+ if (start === -1 || end === -1 || end < start) {
249
+ throw new Error(`${AGENDA_FILE} has no prep-gaps block — run \`ia tech-call agenda <slug> --write\` first`);
250
+ }
251
+ return `${agenda.slice(0, start + PREP_GAPS_START.length)}${block}${agenda.slice(end)}`;
252
+ }
253
+ // ---------------------------------------------------------------------------
254
+ // IO
255
+ async function airtable(path, token, fetchImpl) {
256
+ const res = await fetchImpl(`https://api.airtable.com/v0/${DEFAULT_AIRTABLE_BASE_ID}/${path}`, {
257
+ headers: { Authorization: `Bearer ${token}` },
258
+ });
259
+ if (!res.ok)
260
+ throw new Error(`Airtable answered HTTP ${res.status}`);
261
+ return (await res.json());
262
+ }
263
+ const FREE_MAIL = [
264
+ "gmail.com",
265
+ "outlook.com",
266
+ "hotmail.com",
267
+ "yahoo.com",
268
+ "icloud.com",
269
+ "aol.com",
270
+ "live.com",
271
+ ];
272
+ export function realProbes(options) {
273
+ const fetchImpl = options.fetchImpl ?? fetch;
274
+ const exec = options.execFileImpl ?? execFileAsync;
275
+ const env = options.env ?? process.env;
276
+ const reason = (error) => (error instanceof Error ? error.message : String(error)).slice(0, 160);
277
+ return {
278
+ async team(slug) {
279
+ const token = env[AIRTABLE_API_TOKEN_ENV];
280
+ if (!token)
281
+ return `${AIRTABLE_API_TOKEN_ENV} is not set`;
282
+ try {
283
+ const formula = encodeURIComponent(`{Slug}='${slug}'`);
284
+ const client = (await airtable(`${DEFAULT_AIRTABLE_TABLE_ID}?filterByFormula=${formula}&maxRecords=1`, token, fetchImpl)).records[0];
285
+ if (!client)
286
+ return `no CRM record has the slug "${slug}"`;
287
+ // Name and Email only. The team table also holds pay: never ask for it.
288
+ const fields = ["Name", "Email"].map((f) => `fields%5B%5D=${f}`).join("&");
289
+ const people = (await airtable(`${encodeURIComponent("Team - Master")}?${fields}`, token, fetchImpl)).records;
290
+ const pick = (ids) => (Array.isArray(ids) ? ids : [])
291
+ .map((id) => people.find((person) => person.id === id))
292
+ .filter((person) => !!person && typeof person.fields.Email === "string")
293
+ .map((person) => ({
294
+ name: String(person.fields.Name ?? "A team member"),
295
+ email: String(person.fields.Email),
296
+ }));
297
+ const domain = domainOf(String(client.fields.Email ?? ""));
298
+ return {
299
+ technicians: pick(client.fields.Technician),
300
+ sales: pick(client.fields.Sales),
301
+ clientDomain: FREE_MAIL.includes(domain) ? "" : domain,
302
+ };
303
+ }
304
+ catch (error) {
305
+ return reason(error);
306
+ }
307
+ },
308
+ async calendarEvents(date) {
309
+ const calendarId = env[PREP_CALENDAR_ID_ENV];
310
+ const key = env[GOOGLE_SERVICE_ACCOUNT_KEY_ENV];
311
+ if (!calendarId)
312
+ return `${PREP_CALENDAR_ID_ENV} is not set (the calendar that holds the client calls)`;
313
+ if (!key)
314
+ return `${GOOGLE_SERVICE_ACCOUNT_KEY_ENV} is not set`;
315
+ try {
316
+ const { accessToken } = await getServiceAccountAccessToken(key, CALENDAR_SCOPE, fetchImpl, Date.now);
317
+ // The whole day in any US time zone: the date at UTC-12 to the date at UTC+14.
318
+ const params = new URLSearchParams({
319
+ timeMin: `${date}T00:00:00-05:00`,
320
+ timeMax: `${date}T23:59:59-08:00`,
321
+ singleEvents: "true",
322
+ maxResults: "50",
323
+ });
324
+ const res = await fetchImpl(`https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events?${params}`, { headers: { Authorization: `Bearer ${accessToken}` } });
325
+ if (res.status === 404 || res.status === 403) {
326
+ return `the service account cannot read the calendar (HTTP ${res.status})`;
327
+ }
328
+ if (!res.ok)
329
+ return `Google Calendar answered HTTP ${res.status}`;
330
+ const body = (await res.json());
331
+ return (body.items ?? [])
332
+ .filter((item) => item.status !== "cancelled")
333
+ .map((item) => ({
334
+ summary: item.summary ?? "(no title)",
335
+ attendees: (item.attendees ?? []).map((a) => a.email ?? "").filter(Boolean),
336
+ }));
337
+ }
338
+ catch (error) {
339
+ return reason(error);
340
+ }
341
+ },
342
+ async vaultItemTitles(vault) {
343
+ try {
344
+ const { stdout } = await exec("op", ["item", "list", "--vault", vault, "--format=json"]);
345
+ return JSON.parse(stdout).map((item) => item.title ?? "");
346
+ }
347
+ catch (error) {
348
+ const failure = execFailureDetail(error);
349
+ if (failure.code === "ENOENT")
350
+ return "the 1Password CLI (`op`) is not installed";
351
+ return `\`op\` could not list the vault "${vault}" (it does not exist, you cannot open it, or op is not signed in)`;
352
+ }
353
+ },
354
+ async portalOrgExists(slug) {
355
+ try {
356
+ return (await portalListOrgs({ fetchImpl })).orgs.some((org) => org.slug === slug);
357
+ }
358
+ catch (error) {
359
+ return reason(error);
360
+ }
361
+ },
362
+ async openLinearIssues(slug) {
363
+ try {
364
+ return (await clientLinearProject(slug, { limit: 250, fetchImpl })).issues.map((issue) => issue.identifier);
365
+ }
366
+ catch (error) {
367
+ return reason(error);
368
+ }
369
+ },
370
+ async driveDocTitles(slug) {
371
+ try {
372
+ return (await clientDriveSearch(slug, { fetchImpl })).docs
373
+ .filter((doc) => !doc.path.includes("/"))
374
+ .map((doc) => doc.title.replace(/\.gdoc$/, ""));
375
+ }
376
+ catch (error) {
377
+ return reason(error);
378
+ }
379
+ },
380
+ };
381
+ }
382
+ async function readDir(dir, keep) {
383
+ const out = {};
384
+ if (!existsSync(dir))
385
+ return out;
386
+ for (const name of (await readdir(dir)).filter(keep)) {
387
+ out[name] = await readFile(join(dir, name), "utf8").catch(() => "");
388
+ }
389
+ return out;
390
+ }
391
+ export async function techCallPrep(slug, options) {
392
+ if (!SLUG_PATTERN.test(slug)) {
393
+ throw new Error(`invalid slug "${slug}" — use lowercase letters, digits, and hyphens`);
394
+ }
395
+ if (options.callDate && !/^\d{4}-\d{2}-\d{2}$/.test(options.callDate)) {
396
+ throw new Error(`--call-date must be YYYY-MM-DD, not "${options.callDate}"`);
397
+ }
398
+ const workspace = resolve(options.workspaceDir);
399
+ const repoDir = join(workspace, "clients", `client-${slug}`);
400
+ if (!existsSync(repoDir)) {
401
+ throw new Error(`${repoDir} not found — scaffolding comes first (the kickoff, or \`ia new-client\`), not a call agenda`);
402
+ }
403
+ const callsDir = join(workspace, "team-clients", "clients", slug, "calls");
404
+ const files = {
405
+ entries: await readdir(repoDir),
406
+ onboardingHtml: await readFile(join(repoDir, "onboarding.html"), "utf8").catch(() => ""),
407
+ docs: await readDir(join(repoDir, "docs"), (name) => /^0[1-5]-.*\.md$/.test(name)),
408
+ evidence: await readDir(join(repoDir, "evidence"), (name) => name.endsWith("-transcript-check.md")),
409
+ registryCalls: existsSync(callsDir)
410
+ ? (await readdir(callsDir))
411
+ .filter((name) => /^\d{4}-\d{2}-\d{2}\.md$/.test(name))
412
+ .map((name) => name.slice(0, 10))
413
+ .sort()
414
+ : [],
415
+ };
416
+ const today = (options.now ?? new Date()).toISOString().slice(0, 10);
417
+ const titleDate = /\d{4}-\d{2}-\d{2}/.exec((files.docs["05-call-agenda.md"] ?? "").split("\n")[0] ?? "")?.[0];
418
+ const callDate = options.callDate ?? titleDate ?? today;
419
+ const clientMd = await readFile(join(repoDir, "CLIENT.md"), "utf8").catch(() => "");
420
+ const vault = readManifestKey(clientMd, "onepassword_vault") ?? `client-${slug}`;
421
+ const probes = options.probes ?? realProbes({ workspaceDir: workspace });
422
+ const [team, events, titles, org, issues, driveDocs] = await Promise.all([
423
+ probes.team(slug),
424
+ probes.calendarEvents(callDate),
425
+ probes.vaultItemTitles(vault),
426
+ probes.portalOrgExists(slug),
427
+ probes.openLinearIssues(slug),
428
+ probes.driveDocTitles(slug),
429
+ ]);
430
+ const checks = [
431
+ checkScaffold(files),
432
+ ...checkDocs(files),
433
+ checkAgendaFile(files, callDate),
434
+ checkAgendaDoc(driveDocs, callDate),
435
+ checkInvite(events, team, callDate),
436
+ ...checkVault(titles, vault),
437
+ checkPortalOrg(org, slug),
438
+ checkLinear(issues, files.docs["02-tech-spec.md"] ?? ""),
439
+ ];
440
+ const block = renderPrepBlock(checks, today);
441
+ let written = null;
442
+ if (options.write) {
443
+ const target = join(repoDir, AGENDA_FILE);
444
+ const agenda = await readFile(target, "utf8").catch(() => "");
445
+ await writeFile(target, withPrepBlock(agenda, block));
446
+ written = target;
447
+ }
448
+ return {
449
+ slug,
450
+ callDate,
451
+ checks,
452
+ counts: {
453
+ pass: checks.filter((c) => c.status === "pass").length,
454
+ gap: checks.filter((c) => c.status === "gap").length,
455
+ skipped: checks.filter((c) => c.status === "skipped").length,
456
+ },
457
+ block,
458
+ written,
459
+ };
460
+ }
@@ -0,0 +1,142 @@
1
+ import { type ExecFileFn } from "./exec.js";
2
+ import { type PrepTeam } from "./tech-call-prep.js";
3
+ import { type CallTranscript, type TechCallVerifyResult, techCallVerify } from "./tech-call-verify.js";
4
+ export declare const UPDATE_PASS_MODEL = "claude-opus-5-5";
5
+ export declare const FALLBACK_SLACK_USER_ENV = "IA_TECH_CALL_FALLBACK_SLACK_USER";
6
+ export declare const BOT_AUTHOR_NAME = "installagent-bot";
7
+ export declare const BOT_AUTHOR_EMAIL = "bot@installagent.com";
8
+ /** The only paths the pass may change. */
9
+ export declare const UPDATE_PASS_ALLOWED: RegExp[];
10
+ export type ChangeKind = "fill" | "update" | "conflict" | "status";
11
+ /** One thing the agent says it changed. The command checks the quote itself. */
12
+ export interface UpdateChange {
13
+ file: string;
14
+ kind: ChangeKind;
15
+ /** What changed, one sentence. */
16
+ summary: string;
17
+ /** The words from the call that the change rests on. */
18
+ quote: string;
19
+ /** Filled by the command: `2026-11-18 [00:49:48]`, or "" when the quote is not in a transcript. */
20
+ at: string;
21
+ }
22
+ export interface LinearDraft {
23
+ title: string;
24
+ /** One line of context. No dollar amount. */
25
+ line: string;
26
+ }
27
+ /** Line numbers (1-based) of a file that a person, not the bot, last wrote. */
28
+ export type HandEdited = Record<string, number[]>;
29
+ export interface GateFailure {
30
+ gate: "paths" | "secret" | "contact" | "tokens" | "hand-edited";
31
+ detail: string;
32
+ }
33
+ /** `git blame --line-porcelain` output → the lines whose author is not the bot. */
34
+ export declare function handEditedLines(blamePorcelain: string): number[];
35
+ /** `[3,4,5,9]` → `3-5, 9` — for the prompt. */
36
+ export declare function lineRanges(lines: number[]): string;
37
+ /** `git diff -U0 <base>` → per file: the BASE line numbers a hunk removed or replaced. */
38
+ export declare function changedBaseLines(diff: string): Record<string, number[]>;
39
+ /** The lines a diff ADDS, per file. */
40
+ export declare function addedLines(diff: string): Record<string, string[]>;
41
+ /**
42
+ * The gates. Empty = the branch may be pushed. Every failure says what and
43
+ * where, so the log alone tells a person what to fix.
44
+ */
45
+ export declare function checkGates(input: {
46
+ changedFiles: string[];
47
+ diff: string;
48
+ baseText: string;
49
+ afterText: string;
50
+ handEdited: HandEdited;
51
+ changes: UpdateChange[];
52
+ }): GateFailure[];
53
+ /** The agent's `changes.json` → changes with the quote checked against the transcripts. */
54
+ export declare function checkChanges(raw: unknown, transcripts: CallTranscript[]): UpdateChange[];
55
+ export declare function checkLinearDrafts(raw: unknown): LinearDraft[];
56
+ /** The one-line DM. No pay text, ever. */
57
+ export declare function updatePassNotice(input: {
58
+ slug: string;
59
+ compareUrl: string;
60
+ /** Set when the DM goes to the fallback person because no technician is linked. */
61
+ noTechnician?: boolean;
62
+ }): string;
63
+ export declare function buildUpdatePrompt(input: {
64
+ slug: string;
65
+ callDate: string;
66
+ contextDir: string;
67
+ handEdited: HandEdited;
68
+ /** Today, YYYY-MM-DD: the date in the names of the two evidence files this run writes. */
69
+ date: string;
70
+ }): string;
71
+ export declare function renderUpdateEvidence(input: {
72
+ slug: string;
73
+ callDate: string;
74
+ date: string;
75
+ branch: string;
76
+ base: string;
77
+ model: string;
78
+ changes: UpdateChange[];
79
+ drafts: LinearDraft[];
80
+ verify: Pick<TechCallVerifyResult, "counts" | "promises"> | null;
81
+ otherBranches: string[];
82
+ gates: GateFailure[];
83
+ }): string;
84
+ export type UpdatePassStatus = "dry-run" | "pushed" | "exists" | "gates-failed";
85
+ export interface TechCallUpdatePassOptions {
86
+ workspaceDir: string;
87
+ /** The tech call's date. Default: the newest note with `type: tech-discovery`. */
88
+ call?: string;
89
+ /** The ref the branch starts from. Default `main`. */
90
+ base?: string;
91
+ /** Clone from here instead of the local checkout (CI: an https URL with a token). */
92
+ cloneUrl?: string;
93
+ /** Read team-clients at this git ref instead of its working tree. */
94
+ registryRef?: string;
95
+ push?: boolean;
96
+ notify?: boolean;
97
+ /** Run again even when the branch is already on the remote. */
98
+ force?: boolean;
99
+ /** Where the scratch clone goes. Default: a new temp folder. */
100
+ scratchDir?: string;
101
+ model?: string;
102
+ /** Test seams. */
103
+ execFileImpl?: ExecFileFn;
104
+ fetchImpl?: typeof fetch;
105
+ runAgent?: (input: {
106
+ prompt: string;
107
+ cwd: string;
108
+ contextDir: string;
109
+ model: string;
110
+ }) => Promise<void>;
111
+ verify?: typeof techCallVerify;
112
+ team?: (slug: string) => Promise<PrepTeam | string>;
113
+ transcripts?: CallTranscript[];
114
+ skillText?: string;
115
+ env?: Record<string, string | undefined>;
116
+ now?: Date;
117
+ }
118
+ export interface TechCallUpdatePassResult {
119
+ slug: string;
120
+ status: UpdatePassStatus;
121
+ callDate: string;
122
+ fathomId: string | null;
123
+ branch: string;
124
+ base: string;
125
+ /** The scratch clone. Kept after the run so a person can read the diff. */
126
+ cloneDir: string;
127
+ changedFiles: string[];
128
+ changes: UpdateChange[];
129
+ drafts: LinearDraft[];
130
+ gates: GateFailure[];
131
+ otherBranches: string[];
132
+ verify: TechCallVerifyResult["counts"] | null;
133
+ compareUrl: string | null;
134
+ /** Who got the DM, by role: "technician", "fallback", or null. */
135
+ notified: "technician" | "fallback" | null;
136
+ notes: string[];
137
+ }
138
+ /** `git@github.com:Org/repo.git` or an https URL → `https://github.com/Org/repo`, tokens dropped. */
139
+ export declare function repoWebUrl(remote: string): string | null;
140
+ /** A clone URL can carry a token; a git error message repeats the URL. Never let it out. */
141
+ export declare function scrubCredentials(text: string): string;
142
+ export declare function techCallUpdatePass(slug: string, options: TechCallUpdatePassOptions): Promise<TechCallUpdatePassResult>;