@installagent/sdk 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/agent-mirror.d.ts +69 -0
  2. package/dist/agent-mirror.js +275 -0
  3. package/dist/claude-hours.d.ts +134 -0
  4. package/dist/claude-hours.js +638 -0
  5. package/dist/client-drive.d.ts +3 -0
  6. package/dist/client-drive.js +2 -2
  7. package/dist/client-linear-create.d.ts +10 -0
  8. package/dist/client-linear-create.js +30 -3
  9. package/dist/env-fill.js +21 -4
  10. package/dist/env-registry.d.ts +4 -0
  11. package/dist/env-registry.js +54 -2
  12. package/dist/git.d.ts +31 -0
  13. package/dist/git.js +59 -0
  14. package/dist/google-service-account.d.ts +20 -0
  15. package/dist/google-service-account.js +49 -0
  16. package/dist/hours-estimate.d.ts +43 -0
  17. package/dist/hours-estimate.js +159 -0
  18. package/dist/hours-export-schedule.d.ts +35 -0
  19. package/dist/hours-export-schedule.js +188 -0
  20. package/dist/hours-ledger.d.ts +137 -0
  21. package/dist/hours-ledger.js +926 -0
  22. package/dist/index.d.ts +14 -3
  23. package/dist/index.js +14 -3
  24. package/dist/portal-admin.d.ts +68 -0
  25. package/dist/portal-admin.js +64 -1
  26. package/dist/sync-repos.d.ts +7 -0
  27. package/dist/sync-repos.js +10 -1
  28. package/dist/template-sync.d.ts +10 -9
  29. package/dist/template-sync.js +14 -9
  30. package/dist/triage-backfill.d.ts +37 -0
  31. package/dist/triage-backfill.js +211 -0
  32. package/dist/triage-enable.d.ts +90 -0
  33. package/dist/triage-enable.js +428 -0
  34. package/dist/triage-gates.d.ts +252 -0
  35. package/dist/triage-gates.js +951 -0
  36. package/dist/workspace-push.d.ts +39 -0
  37. package/dist/workspace-push.js +78 -0
  38. package/dist/workspace-status.d.ts +37 -0
  39. package/dist/workspace-status.js +114 -0
  40. package/package.json +1 -1
  41. package/templates/env.example +6 -2
  42. package/templates/workspace-root/.claude/settings.json +12 -1
  43. package/templates/workspace-root/skills/.github/workflows/pr-to-slack.yml +53 -28
  44. package/templates/workspace-root/skills/CLAUDE.md +6 -1
  45. package/templates/workspace-root/skills/README.md +17 -2
  46. package/templates/workspace-root/skills/ad-machine/SKILL.md +140 -0
  47. package/templates/workspace-root/skills/client-deliverables/SKILL.md +1 -1
  48. package/templates/workspace-root/skills/client-deliverables/references/package-layout.md +3 -2
  49. package/templates/workspace-root/skills/client-latest/SKILL.md +124 -82
  50. package/templates/workspace-root/skills/client-latest/catchup.command.md +5 -4
  51. package/templates/workspace-root/skills/email-triage-rollout/SKILL.md +90 -13
  52. package/templates/workspace-root/skills/engagement-spec/SKILL.md +51 -18
  53. package/templates/workspace-root/skills/engagement-spec/references/spec-templates.md +10 -4
  54. package/templates/workspace-root/skills/github-profile/SKILL.md +106 -0
  55. package/templates/workspace-root/skills/ia-cli/SKILL.md +30 -1
  56. package/templates/workspace-root/skills/init_repo/SKILL.md +188 -0
@@ -0,0 +1,638 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync, } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { findWorkspaceRoot } from "./env-file.js";
5
+ import { estimateHours, ledgerDay, minuteOf, roundMonths, } from "./hours-estimate.js";
6
+ import { createLogger } from "./log.js";
7
+ // `ia hours-export` — one technician's Claude Code activity, per client, for
8
+ // the internal hours ledger. Claude Code session logs live only on the
9
+ // machine that made them, so this runs locally and hands a small JSON file to
10
+ // whoever maintains the ledger, who merges it with every other source
11
+ // (`ia hours-ledger`).
12
+ //
13
+ // The output is the ledger's own raw unit: per client, the set of minutes
14
+ // that had Claude Code activity. Not pre-summed hours — the ledger has to
15
+ // line these minutes up against the same person's calls, commits, Slack and
16
+ // Linear activity so a minute counts once, and monthly totals cannot be
17
+ // lined up. A small hours summary rides along for the person running it.
18
+ //
19
+ // Only time a person started counts (schema /3, 2026-10-05). A minute of
20
+ // activity counts when it falls within PROMPT_WINDOW_MINUTES after that
21
+ // person's own action in the SAME session: a prompt Claude Code marks as
22
+ // human (`origin.kind` / `turnOrigin`), or their answer to a question or a
23
+ // plan (the tool_result of a HUMAN_ANSWER_TOOLS call). Everything else — a
24
+ // loop or scheduled wake-up, a background task finishing, a subagent's
25
+ // message — is exported as `automationMinutes`: kept for review, never
26
+ // counted. Before this, an unattended check loop that woke Claude every 30
27
+ // minutes held one weekend session open for 55 hours.
28
+ //
29
+ // What is inspected, per session-log line: its `type`, `timestamp`,
30
+ // `isSidechain` flag, `cwd`, its prompt-origin marks (`origin.kind`,
31
+ // `turnOrigin`), the `id`/`name` of `tool_use` blocks and the `tool_use_id`
32
+ // of `tool_result` blocks (to spot an answer), and — on assistant lines — the
33
+ // path/command fields of `tool_use` inputs (TOOL_INPUT_PATH_KEYS), with
34
+ // heredoc bodies cut out of commands. Never message text, `tool_result`
35
+ // output, file contents a tool writes (Write/Edit), or prompts sent to
36
+ // subagents. Each line is parsed whole to reach those fields, but nothing
37
+ // else is examined and only a client slug plus a minute survives into the
38
+ // result. Other inline text in a command (a commit message, say) can still
39
+ // match a `clients/client-<slug>` path; that is the documented limit.
40
+ //
41
+ // Attribution, per session file (ported from the ledger's original export):
42
+ // each line's matches vote, the most-mentioned slug wins the line, lines
43
+ // with no match inherit the previous line's slug, and the lines before the
44
+ // first match take the first slug. A session that never names a client counts
45
+ // as `unattributed` when it ran inside the Install Agent workspace, and is
46
+ // skipped otherwise (other work on the same machine).
47
+ const log = createLogger("sdk.claude-hours");
48
+ export const HOURS_EXPORT_SCHEMA = "ia-hours-export/3";
49
+ /** Activity counts this long after the person's own action in the same session. */
50
+ export const PROMPT_WINDOW_MINUTES = 30;
51
+ /** Tools whose result is the person's own answer: a question answered, a plan approved. */
52
+ const HUMAN_ANSWER_TOOLS = new Set(["AskUserQuestion", "ExitPlanMode"]);
53
+ /** Claude Code's own config-dir override; scanned in addition to the defaults. */
54
+ export const CLAUDE_CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR";
55
+ /**
56
+ * Every existing one is scanned, plus $CLAUDE_CONFIG_DIR. Deliberately an
57
+ * explicit list, not a `~/.claude*` glob: a technician can keep other
58
+ * employers' Claude Code data beside ours.
59
+ */
60
+ const DEFAULT_CONFIG_DIR_NAMES = [".claude-installagent", ".claude"];
61
+ /** The pseudo-slug for Install Agent work that named no client. */
62
+ export const UNATTRIBUTED_SLUG = "unattributed";
63
+ /**
64
+ * Never a client: the scaffold repo, the house diagram exemplar every
65
+ * diagram session reads, and placeholder words from docs and templates.
66
+ */
67
+ const IGNORED_SLUGS = new Set([
68
+ "template",
69
+ "kingdom",
70
+ "slug",
71
+ "name",
72
+ "x",
73
+ "facing",
74
+ "side",
75
+ "repo",
76
+ "repos",
77
+ ]);
78
+ /** The only tool_use input fields read — where a working path or a command lives. */
79
+ export const TOOL_INPUT_PATH_KEYS = [
80
+ "file_path",
81
+ "path",
82
+ "notebook_path",
83
+ "command",
84
+ "pattern",
85
+ "glob",
86
+ ];
87
+ /** Any client, known here or not. The slug is validated in code (see `strongSlugs`). */
88
+ const STRONG_PATTERNS = [/clients\/client-([a-z0-9-]+)/g, /team-clients\/clients\/([a-z0-9-]+)/g];
89
+ /** A bare `client-<slug>` (repo, Linear project, Slack channel) — only for a known client. */
90
+ const WEAK_PATTERN = /\bclient-([a-z0-9][a-z0-9-]*[a-z0-9])\b/g;
91
+ /** A folder name followed by `/` — for client code outside clients/ (see `folderSlugs`). */
92
+ const FOLDER_PATTERN = /(?:^|[\s/"'=:])([A-Za-z0-9][A-Za-z0-9_.-]*)(?=\/)/g;
93
+ const GLOB_CHARS = new Set(["*", "?", "[", "{"]);
94
+ const HEREDOC_PATTERN = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n[\s\S]*?\n\s*\2\s*(?=\n|$)/g;
95
+ const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
96
+ /** Reject anything but a real YYYY-MM-DD calendar date. */
97
+ export function parseLedgerDate(value, flag) {
98
+ const ms = Date.parse(`${value}T00:00:00.000Z`);
99
+ if (!DATE_PATTERN.test(value) ||
100
+ Number.isNaN(ms) ||
101
+ new Date(ms).toISOString().slice(0, 10) !== value) {
102
+ throw new Error(`${flag} must be a real date as YYYY-MM-DD (got "${value}")`);
103
+ }
104
+ return ms;
105
+ }
106
+ function realOrResolved(dir) {
107
+ try {
108
+ return realpathSync(dir);
109
+ }
110
+ catch {
111
+ return resolve(dir);
112
+ }
113
+ }
114
+ function resolveConfigDirs(homeDirValue, env) {
115
+ const candidates = [];
116
+ const configured = env[CLAUDE_CONFIG_DIR_ENV];
117
+ if (configured)
118
+ candidates.push(configured.replace(/^~(?=$|[\\/])/, homeDirValue));
119
+ for (const name of DEFAULT_CONFIG_DIR_NAMES)
120
+ candidates.push(join(homeDirValue, name));
121
+ const seen = new Set();
122
+ const dirs = [];
123
+ for (const candidate of candidates) {
124
+ if (!existsSync(join(candidate, "projects")))
125
+ continue;
126
+ const real = realOrResolved(candidate);
127
+ if (seen.has(real))
128
+ continue;
129
+ seen.add(real);
130
+ dirs.push(resolve(candidate));
131
+ }
132
+ return dirs;
133
+ }
134
+ /** Top-level session files only — subagent logs are left out, as in the ledger. */
135
+ function listSessionFiles(configDirs) {
136
+ const files = [];
137
+ for (const configDir of configDirs) {
138
+ const projectsDir = join(configDir, "projects");
139
+ if (!existsSync(projectsDir))
140
+ continue;
141
+ for (const projectEntry of readdirSync(projectsDir, { withFileTypes: true })) {
142
+ if (!projectEntry.isDirectory())
143
+ continue;
144
+ const projectDir = join(projectsDir, projectEntry.name);
145
+ for (const entry of readdirSync(projectDir, { withFileTypes: true })) {
146
+ if (entry.isFile() && entry.name.endsWith(".jsonl"))
147
+ files.push(join(projectDir, entry.name));
148
+ }
149
+ }
150
+ }
151
+ return files;
152
+ }
153
+ /** Build-repo slugs on this machine: clients/client-<slug>, minus the ignored words. */
154
+ function knownSlugsIn(workspaceRoot) {
155
+ const slugs = new Set();
156
+ if (!workspaceRoot)
157
+ return slugs;
158
+ const clientsDir = join(workspaceRoot, "clients");
159
+ if (!existsSync(clientsDir))
160
+ return slugs;
161
+ for (const entry of readdirSync(clientsDir, { withFileTypes: true })) {
162
+ if (!entry.isDirectory() || !entry.name.startsWith("client-"))
163
+ continue;
164
+ const slug = entry.name.slice("client-".length);
165
+ if (!IGNORED_SLUGS.has(slug))
166
+ slugs.add(slug);
167
+ }
168
+ return slugs;
169
+ }
170
+ function stripHeredocs(command) {
171
+ return command.replace(HEREDOC_PATTERN, "");
172
+ }
173
+ /** `clients/client-<slug>` / `team-clients/clients/<slug>` — skipping globs and ignored words. */
174
+ function strongSlugs(text, out) {
175
+ for (const pattern of STRONG_PATTERNS) {
176
+ for (const match of text.matchAll(pattern)) {
177
+ const next = text[(match.index ?? 0) + match[0].length];
178
+ if (next !== undefined && GLOB_CHARS.has(next))
179
+ continue; // a glob, not a path
180
+ const slug = (match[1] ?? "").replace(/-+$/, "");
181
+ if (slug.length < 2 || !/^[a-z0-9]/.test(slug) || IGNORED_SLUGS.has(slug))
182
+ continue;
183
+ out.push(slug);
184
+ }
185
+ }
186
+ }
187
+ function weakSlugs(text, known, out) {
188
+ for (const match of text.matchAll(WEAK_PATTERN)) {
189
+ const slug = match[1] ?? "";
190
+ if (known.has(slug))
191
+ out.push(slug);
192
+ }
193
+ }
194
+ /**
195
+ * Client code kept outside clients/ — e.g. a deploy clone at
196
+ * `~/dev/behavia/behaviatherapy-scheduling/web`. A folder whose name, with
197
+ * dashes and underscores dropped, starts with a known slug (also dash-free)
198
+ * counts for that slug. Folders only (a segment followed by `/`), never file
199
+ * names, and never a folder directly under `clients/` (the strong patterns
200
+ * already cover those).
201
+ */
202
+ function folderSlugs(text, known, out) {
203
+ if (known.size === 0)
204
+ return;
205
+ for (const match of text.matchAll(FOLDER_PATTERN)) {
206
+ const segment = match[1] ?? "";
207
+ const before = text.slice(0, match.index ?? 0);
208
+ if (/(^|\/)clients\/?$/.test(before) || segment.startsWith("client-"))
209
+ continue;
210
+ const flat = segment.toLowerCase().replace(/[-_]/g, "");
211
+ for (const slug of known) {
212
+ const slugFlat = slug.replace(/-/g, "");
213
+ if (slugFlat.length >= 4 && flat.startsWith(slugFlat)) {
214
+ out.push(slug);
215
+ break;
216
+ }
217
+ }
218
+ }
219
+ }
220
+ /** The path/command text a line exposes: its cwd plus allow-listed tool_use input fields. */
221
+ function lineTexts(line) {
222
+ // Windows paths use backslashes; every pattern here is written with "/".
223
+ const texts = [];
224
+ const push = (value) => {
225
+ texts.push(value.replace(/\\/g, "/"));
226
+ };
227
+ if (typeof line.cwd === "string")
228
+ push(line.cwd);
229
+ if (line.type !== "assistant" || !line.message || typeof line.message !== "object")
230
+ return texts;
231
+ const content = line.message.content;
232
+ if (!Array.isArray(content))
233
+ return texts;
234
+ for (const block of content) {
235
+ if (!block || typeof block !== "object" || block.type !== "tool_use") {
236
+ continue;
237
+ }
238
+ const input = block.input;
239
+ if (!input || typeof input !== "object")
240
+ continue;
241
+ for (const key of TOOL_INPUT_PATH_KEYS) {
242
+ const value = input[key];
243
+ if (typeof value !== "string")
244
+ continue;
245
+ push(key === "command" ? stripHeredocs(value) : value);
246
+ }
247
+ }
248
+ return texts;
249
+ }
250
+ /** Every slug mention in a line, in the ledger's order (strong, then weak, then folders). */
251
+ function slugsInLine(line, known) {
252
+ const text = lineTexts(line).join("\n");
253
+ if (!text)
254
+ return [];
255
+ const found = [];
256
+ strongSlugs(text, found);
257
+ weakSlugs(text, known, found);
258
+ folderSlugs(text, known, found);
259
+ return found;
260
+ }
261
+ /** Most-mentioned slug; a tie goes to the one mentioned first (cwd comes first). */
262
+ function mostMentioned(slugs) {
263
+ const counts = new Map();
264
+ for (const slug of slugs)
265
+ counts.set(slug, (counts.get(slug) ?? 0) + 1);
266
+ let best = null;
267
+ let bestCount = 0;
268
+ for (const [slug, count] of counts) {
269
+ if (count > bestCount) {
270
+ best = slug;
271
+ bestCount = count;
272
+ }
273
+ }
274
+ return best;
275
+ }
276
+ /**
277
+ * One spelling per folder, whatever wrote it: forward slashes, Git Bash's
278
+ * `/c/Users/...` as `c:/users/...`, and Windows drive paths lower-cased
279
+ * (Windows paths are case-insensitive, and Claude Code, Git Bash and Node
280
+ * do not agree on the drive letter's case).
281
+ */
282
+ function comparablePath(path) {
283
+ let value = path.replace(/\\/g, "/");
284
+ const gitBash = /^\/([a-zA-Z])\//.exec(value);
285
+ if (gitBash)
286
+ value = `${gitBash[1]}:/${value.slice(3)}`;
287
+ if (/^[a-zA-Z]:\//.test(value))
288
+ value = value.toLowerCase();
289
+ return value.replace(/\/+$/, "");
290
+ }
291
+ function isInsideWorkspace(cwd, workspaceRoot) {
292
+ if (workspaceRoot) {
293
+ const here = comparablePath(cwd);
294
+ const root = comparablePath(workspaceRoot);
295
+ if (here === root || here.startsWith(`${root}/`))
296
+ return true;
297
+ }
298
+ return cwd.toLowerCase().includes("installagent");
299
+ }
300
+ /** The `tool_use` ids in an assistant line whose result will be the person's own answer. */
301
+ function answerToolIds(line, out) {
302
+ if (line.type !== "assistant" || !line.message || typeof line.message !== "object")
303
+ return;
304
+ const content = line.message.content;
305
+ if (!Array.isArray(content))
306
+ return;
307
+ for (const block of content) {
308
+ if (!block || typeof block !== "object")
309
+ continue;
310
+ const { type, id, name } = block;
311
+ if (type === "tool_use" && typeof id === "string" && typeof name === "string") {
312
+ if (HUMAN_ANSWER_TOOLS.has(name))
313
+ out.add(id);
314
+ }
315
+ }
316
+ }
317
+ /**
318
+ * Did the person act on this line? Claude Code marks every prompt with who
319
+ * started it: `origin.kind` ("human", "task-notification", "peer",
320
+ * "auto-continuation", …) and, on some lines, `turnOrigin`. When `origin` is
321
+ * there it decides; `turnOrigin` covers the lines that carry only that (a
322
+ * typed `!` command's output). An answer to a question or a plan approval
323
+ * arrives as a tool_result instead, matched by its tool_use id.
324
+ */
325
+ function isHumanAction(line, answerIds) {
326
+ if (line.type !== "user")
327
+ return false;
328
+ const origin = line.origin;
329
+ if (origin && typeof origin === "object")
330
+ return origin.kind === "human";
331
+ if (line.turnOrigin === "human")
332
+ return true;
333
+ const content = line.message && typeof line.message === "object"
334
+ ? line.message.content
335
+ : undefined;
336
+ if (!Array.isArray(content))
337
+ return false;
338
+ return content.some((block) => {
339
+ if (!block || typeof block !== "object")
340
+ return false;
341
+ const { type, tool_use_id } = block;
342
+ return type === "tool_result" && typeof tool_use_id === "string" && answerIds.has(tool_use_id);
343
+ });
344
+ }
345
+ function sessionPoints(raw, known, workspaceRoot, sinceMs, untilMs) {
346
+ const events = [];
347
+ const answerIds = new Set();
348
+ let insideWorkspace = false;
349
+ let marked = false;
350
+ let worked = false;
351
+ let lines = 0;
352
+ let first = null;
353
+ let last = null;
354
+ for (const rawLine of raw.split("\n")) {
355
+ const trimmed = rawLine.trim();
356
+ if (!trimmed)
357
+ continue;
358
+ let line;
359
+ try {
360
+ line = JSON.parse(trimmed);
361
+ }
362
+ catch {
363
+ continue; // A session still being written can end in a partial line.
364
+ }
365
+ if (line.type !== "user" && line.type !== "assistant")
366
+ continue;
367
+ if (line.isSidechain === true)
368
+ continue;
369
+ const ts = typeof line.timestamp === "string" ? Date.parse(line.timestamp) : Number.NaN;
370
+ if (Number.isNaN(ts))
371
+ continue;
372
+ if (typeof line.cwd === "string" && isInsideWorkspace(line.cwd, workspaceRoot)) {
373
+ insideWorkspace = true;
374
+ }
375
+ if ("origin" in line || "turnOrigin" in line)
376
+ marked = true;
377
+ answerToolIds(line, answerIds);
378
+ events.push({
379
+ ts,
380
+ slug: mostMentioned(slugsInLine(line, known)),
381
+ human: isHumanAction(line, answerIds),
382
+ });
383
+ if ((sinceMs === null || ts >= sinceMs) && (untilMs === null || ts <= untilMs)) {
384
+ lines += 1;
385
+ if (line.type === "assistant")
386
+ worked = true;
387
+ if (first === null || ts < first)
388
+ first = ts;
389
+ if (last === null || ts > last)
390
+ last = ts;
391
+ }
392
+ }
393
+ events.sort((a, b) => a.ts - b.ts);
394
+ const firstSlug = events.find((event) => event.slug !== null)?.slug ?? null;
395
+ if (firstSlug === null && !insideWorkspace) {
396
+ return { points: [], skipped: events.length > 0, unmarked: false, lines, first, last };
397
+ }
398
+ // Carry the last-seen client forward; the lines before the first mention take the first one.
399
+ // The person's last action is tracked over the whole file, so a prompt just before --since
400
+ // still counts the minutes it started inside the window.
401
+ let current = firstSlug ?? UNATTRIBUTED_SLUG;
402
+ let lastHuman = null;
403
+ const points = [];
404
+ for (const event of events) {
405
+ current = event.slug ?? current;
406
+ const minute = minuteOf(event.ts);
407
+ if (event.human)
408
+ lastHuman = minute;
409
+ if (sinceMs !== null && event.ts < sinceMs)
410
+ continue;
411
+ if (untilMs !== null && event.ts > untilMs)
412
+ continue;
413
+ const counted = lastHuman !== null && minute - lastHuman < PROMPT_WINDOW_MINUTES;
414
+ points.push({ ts: event.ts, slug: current, counted });
415
+ }
416
+ return { points, skipped: false, unmarked: !marked && worked, lines, first, last };
417
+ }
418
+ function minuteIso(minute) {
419
+ return `${new Date(minute * 60_000).toISOString().slice(0, 16)}Z`;
420
+ }
421
+ /** Parse a "YYYY-MM-DDTHH:MMZ" minute from an export back to epoch ms. */
422
+ export function parseMinuteIso(value) {
423
+ return Date.parse(`${value.slice(0, 16)}:00.000Z`);
424
+ }
425
+ /** Where exports are kept on the technician's machine (and where the weekly job writes). */
426
+ export const HOURS_EXPORT_DIR = join(".config", "installagent", "hours-export");
427
+ /**
428
+ * Write an export to disk. The default location is this command's own folder
429
+ * and keeps one file per person per (Eastern) day: a rerun the same day
430
+ * replaces it, since the newer export covers everything the older one did. An
431
+ * explicit `out` path is the caller's file and is never overwritten without
432
+ * `force`. Returns the path written.
433
+ */
434
+ export function saveClaudeHoursExport(result, options = {}) {
435
+ const date = ledgerDay(Date.parse(result.generatedAt));
436
+ const name = `ia-hours-export-${result.person.toLowerCase()}-${date}.json`;
437
+ const outPath = options.out
438
+ ? resolve(options.cwd ?? process.cwd(), options.out)
439
+ : join(options.homeDir ?? homedir(), HOURS_EXPORT_DIR, name);
440
+ if (options.out && existsSync(outPath) && !options.force) {
441
+ throw new Error(`${outPath} already exists — pass --force to overwrite, or another --out`);
442
+ }
443
+ mkdirSync(dirname(outPath), { recursive: true, mode: 0o700 });
444
+ writeFileSync(outPath, `${JSON.stringify(result, null, 2)}\n`);
445
+ return outPath;
446
+ }
447
+ /** The ledger keeper's n8n intake: it DMs the file to them on Slack. Not a secret. */
448
+ export const HOURS_EXPORT_WEBHOOK_URL = "https://n8n.installagent.com/webhook/hours-export";
449
+ /** Shared secret the intake webhook checks, sent as HOURS_EXPORT_SECRET_HEADER. */
450
+ export const HOURS_EXPORT_SECRET_ENV = "HOURS_EXPORT_SECRET";
451
+ export const HOURS_EXPORT_SECRET_HEADER = "x-hours-export-secret";
452
+ /**
453
+ * Send an export to the ledger keeper through the n8n intake webhook, which
454
+ * DMs them the file on Slack. Throws with a plain reason on any failure — the
455
+ * caller keeps the file on disk either way.
456
+ */
457
+ export async function sendClaudeHoursExport(result, options = {}) {
458
+ const env = options.env ?? process.env;
459
+ const secret = env[HOURS_EXPORT_SECRET_ENV];
460
+ if (!secret) {
461
+ throw new Error(`not sent: ${HOURS_EXPORT_SECRET_ENV} is not set in the workspace .env — ask whoever keeps ` +
462
+ "the hours ledger for it");
463
+ }
464
+ const url = options.webhookUrl ?? HOURS_EXPORT_WEBHOOK_URL;
465
+ let res;
466
+ try {
467
+ res = await (options.fetchImpl ?? fetch)(url, {
468
+ method: "POST",
469
+ headers: { "Content-Type": "application/json", [HOURS_EXPORT_SECRET_HEADER]: secret },
470
+ body: JSON.stringify(result),
471
+ });
472
+ }
473
+ catch (error) {
474
+ throw new Error(`not sent: could not reach n8n (${error instanceof Error ? error.message : error})`);
475
+ }
476
+ if (res.status === 401 || res.status === 403) {
477
+ throw new Error(`not sent: the intake rejected ${HOURS_EXPORT_SECRET_ENV} — check its value`);
478
+ }
479
+ if (res.status === 404) {
480
+ throw new Error("not sent: the hours-export intake is not live yet (n8n workflow not published)");
481
+ }
482
+ if (!res.ok)
483
+ throw new Error(`not sent: the hours-export intake answered HTTP ${res.status}`);
484
+ }
485
+ /** Save the export, then send it unless `send` is false. A failed send never loses the file. */
486
+ export async function deliverClaudeHoursExport(result, options = {}) {
487
+ const outPath = saveClaudeHoursExport(result, options);
488
+ if (options.send === false)
489
+ return { outPath, sent: false, sendError: null };
490
+ try {
491
+ await sendClaudeHoursExport(result, options);
492
+ return { outPath, sent: true, sendError: null };
493
+ }
494
+ catch (error) {
495
+ return {
496
+ outPath,
497
+ sent: false,
498
+ sendError: error instanceof Error ? error.message : String(error),
499
+ };
500
+ }
501
+ }
502
+ /** The export minus its per-minute lists (replaced by counts) — for showing to a person or an agent. */
503
+ export function compactClaudeHoursExport(result) {
504
+ const { minutes, automationMinutes, ...rest } = result;
505
+ const counts = (lists) => Object.fromEntries(Object.entries(lists).map(([slug, list]) => [slug, list.length]));
506
+ return {
507
+ ...rest,
508
+ minuteCounts: counts(minutes),
509
+ automationMinuteCounts: counts(automationMinutes),
510
+ };
511
+ }
512
+ /**
513
+ * Read this machine's Claude Code session logs and return one person's
514
+ * per-client activity minutes (plus a Claude-only hours summary), for
515
+ * handing to whoever maintains the ledger. Read-only: never writes
516
+ * anywhere, never transmits anything itself.
517
+ */
518
+ export async function exportClaudeHours(options) {
519
+ const person = options.person?.trim();
520
+ if (!person) {
521
+ throw new Error("person is required — the name the hours ledger knows you by, e.g. Ian");
522
+ }
523
+ const homeDirValue = options.homeDir ?? homedir();
524
+ const env = options.env ?? process.env;
525
+ const now = (options.now ?? (() => new Date()))();
526
+ const sinceMs = options.since ? parseLedgerDate(options.since, "--since") : null;
527
+ const untilMs = options.until ? parseLedgerDate(options.until, "--until") + 86_400_000 - 1 : null;
528
+ if (sinceMs !== null && untilMs !== null && sinceMs > untilMs) {
529
+ throw new Error(`--since (${options.since}) is after --until (${options.until})`);
530
+ }
531
+ const configDirs = options.configDirs ?? resolveConfigDirs(homeDirValue, env);
532
+ const workspaceRoot = options.workspaceRoot === undefined ? findWorkspaceRoot() : options.workspaceRoot;
533
+ const known = knownSlugsIn(workspaceRoot);
534
+ const unreadableSessions = [];
535
+ const countedSets = new Map();
536
+ const activitySets = new Map();
537
+ const addMinute = (sets, slug, minute) => {
538
+ const set = sets.get(slug) ?? new Set();
539
+ set.add(minute);
540
+ sets.set(slug, set);
541
+ };
542
+ let skippedSessions = 0;
543
+ let unmarkedSessions = 0;
544
+ let lines = 0;
545
+ let firstMs = null;
546
+ let lastMs = null;
547
+ for (const file of listSessionFiles(configDirs)) {
548
+ let raw;
549
+ try {
550
+ raw = readFileSync(file, "utf8");
551
+ }
552
+ catch {
553
+ unreadableSessions.push(file);
554
+ log.debug("session-read-failed", { file });
555
+ continue;
556
+ }
557
+ const session = sessionPoints(raw, known, workspaceRoot, sinceMs, untilMs);
558
+ lines += session.lines;
559
+ if (session.first !== null && (firstMs === null || session.first < firstMs)) {
560
+ firstMs = session.first;
561
+ }
562
+ if (session.last !== null && (lastMs === null || session.last > lastMs))
563
+ lastMs = session.last;
564
+ if (session.skipped)
565
+ skippedSessions += 1;
566
+ if (session.unmarked)
567
+ unmarkedSessions += 1;
568
+ for (const point of session.points) {
569
+ const minute = minuteOf(point.ts);
570
+ addMinute(activitySets, point.slug, minute);
571
+ if (point.counted)
572
+ addMinute(countedSets, point.slug, minute);
573
+ }
574
+ }
575
+ // A minute another session counted is not automation, even if a loop also ran in it.
576
+ const minutes = {};
577
+ const automationMinutes = {};
578
+ const countedEvents = [];
579
+ const activityEvents = [];
580
+ const slugs = [...activitySets.keys()].sort();
581
+ for (const slug of slugs) {
582
+ const counted = countedSets.get(slug) ?? new Set();
583
+ const all = [...(activitySets.get(slug) ?? [])].sort((a, b) => a - b);
584
+ const kept = all.filter((minute) => counted.has(minute));
585
+ const automation = all.filter((minute) => !counted.has(minute));
586
+ if (kept.length > 0)
587
+ minutes[slug] = kept.map(minuteIso);
588
+ if (automation.length > 0)
589
+ automationMinutes[slug] = automation.map(minuteIso);
590
+ const event = (minute) => ({
591
+ source: "claude",
592
+ person,
593
+ slug,
594
+ ts: minute * 60_000,
595
+ durationMin: null,
596
+ });
597
+ countedEvents.push(...kept.map(event));
598
+ activityEvents.push(...all.map(event));
599
+ }
600
+ const estimate = estimateHours(countedEvents).hours[person] ?? {};
601
+ const allActivity = estimateHours(activityEvents).hours[person] ?? {};
602
+ const summary = slugs
603
+ .map((slug) => {
604
+ const { byMonth, total } = roundMonths(estimate[slug]);
605
+ return {
606
+ slug,
607
+ known: known.has(slug) || slug === UNATTRIBUTED_SLUG,
608
+ activeMinutes: minutes[slug]?.length ?? 0,
609
+ automationMinutes: automationMinutes[slug]?.length ?? 0,
610
+ hoursByMonth: byMonth,
611
+ hoursTotal: total,
612
+ hoursAllActivity: roundMonths(allActivity[slug]).total,
613
+ };
614
+ })
615
+ .sort((a, b) => b.hoursTotal - a.hoursTotal ||
616
+ b.hoursAllActivity - a.hoursAllActivity ||
617
+ a.slug.localeCompare(b.slug));
618
+ return {
619
+ schema: HOURS_EXPORT_SCHEMA,
620
+ person,
621
+ generatedAt: now.toISOString(),
622
+ windowSince: options.since ?? null,
623
+ windowUntil: options.until ?? null,
624
+ configDirsUsed: configDirs,
625
+ workspaceRoot,
626
+ events: {
627
+ first: firstMs !== null ? new Date(firstMs).toISOString() : null,
628
+ last: lastMs !== null ? new Date(lastMs).toISOString() : null,
629
+ lines,
630
+ },
631
+ minutes,
632
+ automationMinutes,
633
+ summary,
634
+ skippedSessions,
635
+ unmarkedSessions,
636
+ unreadableSessions,
637
+ };
638
+ }
@@ -1,5 +1,8 @@
1
1
  export declare const AIRTABLE_API_TOKEN_ENV = "AIRTABLE_API_TOKEN";
2
2
  export declare const GOOGLE_SERVICE_ACCOUNT_KEY_ENV = "GOOGLE_SERVICE_ACCOUNT_KEY";
3
+ /** "Clients - Master" — verified 2026-07-11 against the live base. */
4
+ export declare const DEFAULT_AIRTABLE_BASE_ID = "appceZOwAY5Hktx56";
5
+ export declare const DEFAULT_AIRTABLE_TABLE_ID = "tblqyf5OpOSKddvl2";
3
6
  /** Thrown when the Airtable token or Google service-account key is missing or rejected. */
4
7
  export declare class ClientDriveAuthError extends Error {
5
8
  }
@@ -7,8 +7,8 @@ export const AIRTABLE_API_TOKEN_ENV = "AIRTABLE_API_TOKEN";
7
7
  export const GOOGLE_SERVICE_ACCOUNT_KEY_ENV = "GOOGLE_SERVICE_ACCOUNT_KEY";
8
8
  const AIRTABLE_API_BASE_URL = "https://api.airtable.com/v0";
9
9
  /** "Clients - Master" — verified 2026-07-11 against the live base. */
10
- const DEFAULT_AIRTABLE_BASE_ID = "appceZOwAY5Hktx56";
11
- const DEFAULT_AIRTABLE_TABLE_ID = "tblqyf5OpOSKddvl2";
10
+ export const DEFAULT_AIRTABLE_BASE_ID = "appceZOwAY5Hktx56";
11
+ export const DEFAULT_AIRTABLE_TABLE_ID = "tblqyf5OpOSKddvl2";
12
12
  /** Field names, not IDs — Airtable's list-records API accepts either. */
13
13
  const SLUG_FIELD = "Slug";
14
14
  const DRIVE_FIELD = "Google Drive";
@@ -5,10 +5,20 @@ export interface ClientLinearCreateIssueInput {
5
5
  title: string;
6
6
  /** Optional markdown body. */
7
7
  description?: string;
8
+ /**
9
+ * Optional workspace/team label NAMES to attach (exact, case-insensitive).
10
+ * Resolved to ids before the create; an unknown name fails the whole call
11
+ * rather than silently filing an unlabeled issue — a caller that asks for
12
+ * "Waiting on client" is relying on that label to drive a follow-up loop.
13
+ */
14
+ labelNames?: string[];
8
15
  }
9
16
  export interface ClientLinearCreateIssueResult {
10
17
  project: ProjectNode;
18
+ /** The team the issue landed in (the project's first team). */
19
+ teamId: string;
11
20
  issue: {
21
+ id: string;
12
22
  identifier: string;
13
23
  title: string;
14
24
  url: string;