@installagent/sdk 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) 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 +118 -0
  4. package/dist/claude-hours.js +523 -0
  5. package/dist/client-drive.d.ts +3 -0
  6. package/dist/client-drive.js +2 -2
  7. package/dist/env-fill.js +21 -4
  8. package/dist/env-registry.d.ts +4 -0
  9. package/dist/env-registry.js +54 -2
  10. package/dist/git.d.ts +31 -0
  11. package/dist/git.js +59 -0
  12. package/dist/google-service-account.d.ts +20 -0
  13. package/dist/google-service-account.js +49 -0
  14. package/dist/hours-estimate.d.ts +43 -0
  15. package/dist/hours-estimate.js +159 -0
  16. package/dist/hours-export-schedule.d.ts +35 -0
  17. package/dist/hours-export-schedule.js +188 -0
  18. package/dist/hours-ledger.d.ts +129 -0
  19. package/dist/hours-ledger.js +882 -0
  20. package/dist/index.d.ts +13 -2
  21. package/dist/index.js +13 -2
  22. package/dist/portal-admin.d.ts +68 -0
  23. package/dist/portal-admin.js +64 -1
  24. package/dist/sync-repos.d.ts +7 -0
  25. package/dist/sync-repos.js +10 -1
  26. package/dist/template-sync.d.ts +10 -9
  27. package/dist/template-sync.js +14 -9
  28. package/dist/triage-backfill.d.ts +37 -0
  29. package/dist/triage-backfill.js +211 -0
  30. package/dist/triage-enable.d.ts +90 -0
  31. package/dist/triage-enable.js +428 -0
  32. package/dist/triage-gates.d.ts +252 -0
  33. package/dist/triage-gates.js +951 -0
  34. package/dist/workspace-push.d.ts +39 -0
  35. package/dist/workspace-push.js +78 -0
  36. package/dist/workspace-status.d.ts +37 -0
  37. package/dist/workspace-status.js +114 -0
  38. package/package.json +1 -1
  39. package/templates/env.example +6 -2
  40. package/templates/workspace-root/.claude/settings.json +12 -1
  41. package/templates/workspace-root/skills/.github/workflows/pr-to-slack.yml +53 -28
  42. package/templates/workspace-root/skills/CLAUDE.md +6 -1
  43. package/templates/workspace-root/skills/README.md +17 -2
  44. package/templates/workspace-root/skills/ad-machine/SKILL.md +140 -0
  45. package/templates/workspace-root/skills/client-deliverables/SKILL.md +1 -1
  46. package/templates/workspace-root/skills/client-deliverables/references/package-layout.md +3 -2
  47. package/templates/workspace-root/skills/client-latest/SKILL.md +124 -82
  48. package/templates/workspace-root/skills/client-latest/catchup.command.md +5 -4
  49. package/templates/workspace-root/skills/email-triage-rollout/SKILL.md +90 -13
  50. package/templates/workspace-root/skills/engagement-spec/SKILL.md +51 -18
  51. package/templates/workspace-root/skills/engagement-spec/references/spec-templates.md +10 -4
  52. package/templates/workspace-root/skills/github-profile/SKILL.md +106 -0
  53. package/templates/workspace-root/skills/ia-cli/SKILL.md +30 -1
  54. package/templates/workspace-root/skills/init_repo/SKILL.md +188 -0
@@ -0,0 +1,523 @@
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
+ // What is inspected, per session-log line: its `type`, `timestamp`,
20
+ // `isSidechain` flag, `cwd`, and — on assistant lines — only the
21
+ // path/command fields of `tool_use` inputs (TOOL_INPUT_PATH_KEYS), with
22
+ // heredoc bodies cut out of commands. Never message text, `tool_result`
23
+ // output, file contents a tool writes (Write/Edit), or prompts sent to
24
+ // subagents. Each line is parsed whole to reach those fields, but nothing
25
+ // else is examined and only a client slug plus a minute survives into the
26
+ // result. Other inline text in a command (a commit message, say) can still
27
+ // match a `clients/client-<slug>` path; that is the documented limit.
28
+ //
29
+ // Attribution, per session file (ported from the ledger's original export):
30
+ // each line's matches vote, the most-mentioned slug wins the line, lines
31
+ // with no match inherit the previous line's slug, and the lines before the
32
+ // first match take the first slug. A session that never names a client counts
33
+ // as `unattributed` when it ran inside the Install Agent workspace, and is
34
+ // skipped otherwise (other work on the same machine).
35
+ const log = createLogger("sdk.claude-hours");
36
+ export const HOURS_EXPORT_SCHEMA = "ia-hours-export/2";
37
+ /** Claude Code's own config-dir override; scanned in addition to the defaults. */
38
+ export const CLAUDE_CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR";
39
+ /**
40
+ * Every existing one is scanned, plus $CLAUDE_CONFIG_DIR. Deliberately an
41
+ * explicit list, not a `~/.claude*` glob: a technician can keep other
42
+ * employers' Claude Code data beside ours.
43
+ */
44
+ const DEFAULT_CONFIG_DIR_NAMES = [".claude-installagent", ".claude"];
45
+ /** The pseudo-slug for Install Agent work that named no client. */
46
+ export const UNATTRIBUTED_SLUG = "unattributed";
47
+ /**
48
+ * Never a client: the scaffold repo, the house diagram exemplar every
49
+ * diagram session reads, and placeholder words from docs and templates.
50
+ */
51
+ const IGNORED_SLUGS = new Set([
52
+ "template",
53
+ "kingdom",
54
+ "slug",
55
+ "name",
56
+ "x",
57
+ "facing",
58
+ "side",
59
+ "repo",
60
+ "repos",
61
+ ]);
62
+ /** The only tool_use input fields read — where a working path or a command lives. */
63
+ export const TOOL_INPUT_PATH_KEYS = [
64
+ "file_path",
65
+ "path",
66
+ "notebook_path",
67
+ "command",
68
+ "pattern",
69
+ "glob",
70
+ ];
71
+ /** Any client, known here or not. The slug is validated in code (see `strongSlugs`). */
72
+ const STRONG_PATTERNS = [/clients\/client-([a-z0-9-]+)/g, /team-clients\/clients\/([a-z0-9-]+)/g];
73
+ /** A bare `client-<slug>` (repo, Linear project, Slack channel) — only for a known client. */
74
+ const WEAK_PATTERN = /\bclient-([a-z0-9][a-z0-9-]*[a-z0-9])\b/g;
75
+ /** A folder name followed by `/` — for client code outside clients/ (see `folderSlugs`). */
76
+ const FOLDER_PATTERN = /(?:^|[\s/"'=:])([A-Za-z0-9][A-Za-z0-9_.-]*)(?=\/)/g;
77
+ const GLOB_CHARS = new Set(["*", "?", "[", "{"]);
78
+ const HEREDOC_PATTERN = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n[\s\S]*?\n\s*\2\s*(?=\n|$)/g;
79
+ const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
80
+ /** Reject anything but a real YYYY-MM-DD calendar date. */
81
+ export function parseLedgerDate(value, flag) {
82
+ const ms = Date.parse(`${value}T00:00:00.000Z`);
83
+ if (!DATE_PATTERN.test(value) ||
84
+ Number.isNaN(ms) ||
85
+ new Date(ms).toISOString().slice(0, 10) !== value) {
86
+ throw new Error(`${flag} must be a real date as YYYY-MM-DD (got "${value}")`);
87
+ }
88
+ return ms;
89
+ }
90
+ function realOrResolved(dir) {
91
+ try {
92
+ return realpathSync(dir);
93
+ }
94
+ catch {
95
+ return resolve(dir);
96
+ }
97
+ }
98
+ function resolveConfigDirs(homeDirValue, env) {
99
+ const candidates = [];
100
+ const configured = env[CLAUDE_CONFIG_DIR_ENV];
101
+ if (configured)
102
+ candidates.push(configured.replace(/^~(?=$|[\\/])/, homeDirValue));
103
+ for (const name of DEFAULT_CONFIG_DIR_NAMES)
104
+ candidates.push(join(homeDirValue, name));
105
+ const seen = new Set();
106
+ const dirs = [];
107
+ for (const candidate of candidates) {
108
+ if (!existsSync(join(candidate, "projects")))
109
+ continue;
110
+ const real = realOrResolved(candidate);
111
+ if (seen.has(real))
112
+ continue;
113
+ seen.add(real);
114
+ dirs.push(resolve(candidate));
115
+ }
116
+ return dirs;
117
+ }
118
+ /** Top-level session files only — subagent logs are left out, as in the ledger. */
119
+ function listSessionFiles(configDirs) {
120
+ const files = [];
121
+ for (const configDir of configDirs) {
122
+ const projectsDir = join(configDir, "projects");
123
+ if (!existsSync(projectsDir))
124
+ continue;
125
+ for (const projectEntry of readdirSync(projectsDir, { withFileTypes: true })) {
126
+ if (!projectEntry.isDirectory())
127
+ continue;
128
+ const projectDir = join(projectsDir, projectEntry.name);
129
+ for (const entry of readdirSync(projectDir, { withFileTypes: true })) {
130
+ if (entry.isFile() && entry.name.endsWith(".jsonl"))
131
+ files.push(join(projectDir, entry.name));
132
+ }
133
+ }
134
+ }
135
+ return files;
136
+ }
137
+ /** Build-repo slugs on this machine: clients/client-<slug>, minus the ignored words. */
138
+ function knownSlugsIn(workspaceRoot) {
139
+ const slugs = new Set();
140
+ if (!workspaceRoot)
141
+ return slugs;
142
+ const clientsDir = join(workspaceRoot, "clients");
143
+ if (!existsSync(clientsDir))
144
+ return slugs;
145
+ for (const entry of readdirSync(clientsDir, { withFileTypes: true })) {
146
+ if (!entry.isDirectory() || !entry.name.startsWith("client-"))
147
+ continue;
148
+ const slug = entry.name.slice("client-".length);
149
+ if (!IGNORED_SLUGS.has(slug))
150
+ slugs.add(slug);
151
+ }
152
+ return slugs;
153
+ }
154
+ function stripHeredocs(command) {
155
+ return command.replace(HEREDOC_PATTERN, "");
156
+ }
157
+ /** `clients/client-<slug>` / `team-clients/clients/<slug>` — skipping globs and ignored words. */
158
+ function strongSlugs(text, out) {
159
+ for (const pattern of STRONG_PATTERNS) {
160
+ for (const match of text.matchAll(pattern)) {
161
+ const next = text[(match.index ?? 0) + match[0].length];
162
+ if (next !== undefined && GLOB_CHARS.has(next))
163
+ continue; // a glob, not a path
164
+ const slug = (match[1] ?? "").replace(/-+$/, "");
165
+ if (slug.length < 2 || !/^[a-z0-9]/.test(slug) || IGNORED_SLUGS.has(slug))
166
+ continue;
167
+ out.push(slug);
168
+ }
169
+ }
170
+ }
171
+ function weakSlugs(text, known, out) {
172
+ for (const match of text.matchAll(WEAK_PATTERN)) {
173
+ const slug = match[1] ?? "";
174
+ if (known.has(slug))
175
+ out.push(slug);
176
+ }
177
+ }
178
+ /**
179
+ * Client code kept outside clients/ — e.g. a deploy clone at
180
+ * `~/dev/behavia/behaviatherapy-scheduling/web`. A folder whose name, with
181
+ * dashes and underscores dropped, starts with a known slug (also dash-free)
182
+ * counts for that slug. Folders only (a segment followed by `/`), never file
183
+ * names, and never a folder directly under `clients/` (the strong patterns
184
+ * already cover those).
185
+ */
186
+ function folderSlugs(text, known, out) {
187
+ if (known.size === 0)
188
+ return;
189
+ for (const match of text.matchAll(FOLDER_PATTERN)) {
190
+ const segment = match[1] ?? "";
191
+ const before = text.slice(0, match.index ?? 0);
192
+ if (/(^|\/)clients\/?$/.test(before) || segment.startsWith("client-"))
193
+ continue;
194
+ const flat = segment.toLowerCase().replace(/[-_]/g, "");
195
+ for (const slug of known) {
196
+ const slugFlat = slug.replace(/-/g, "");
197
+ if (slugFlat.length >= 4 && flat.startsWith(slugFlat)) {
198
+ out.push(slug);
199
+ break;
200
+ }
201
+ }
202
+ }
203
+ }
204
+ /** The path/command text a line exposes: its cwd plus allow-listed tool_use input fields. */
205
+ function lineTexts(line) {
206
+ // Windows paths use backslashes; every pattern here is written with "/".
207
+ const texts = [];
208
+ const push = (value) => {
209
+ texts.push(value.replace(/\\/g, "/"));
210
+ };
211
+ if (typeof line.cwd === "string")
212
+ push(line.cwd);
213
+ if (line.type !== "assistant" || !line.message || typeof line.message !== "object")
214
+ return texts;
215
+ const content = line.message.content;
216
+ if (!Array.isArray(content))
217
+ return texts;
218
+ for (const block of content) {
219
+ if (!block || typeof block !== "object" || block.type !== "tool_use") {
220
+ continue;
221
+ }
222
+ const input = block.input;
223
+ if (!input || typeof input !== "object")
224
+ continue;
225
+ for (const key of TOOL_INPUT_PATH_KEYS) {
226
+ const value = input[key];
227
+ if (typeof value !== "string")
228
+ continue;
229
+ push(key === "command" ? stripHeredocs(value) : value);
230
+ }
231
+ }
232
+ return texts;
233
+ }
234
+ /** Every slug mention in a line, in the ledger's order (strong, then weak, then folders). */
235
+ function slugsInLine(line, known) {
236
+ const text = lineTexts(line).join("\n");
237
+ if (!text)
238
+ return [];
239
+ const found = [];
240
+ strongSlugs(text, found);
241
+ weakSlugs(text, known, found);
242
+ folderSlugs(text, known, found);
243
+ return found;
244
+ }
245
+ /** Most-mentioned slug; a tie goes to the one mentioned first (cwd comes first). */
246
+ function mostMentioned(slugs) {
247
+ const counts = new Map();
248
+ for (const slug of slugs)
249
+ counts.set(slug, (counts.get(slug) ?? 0) + 1);
250
+ let best = null;
251
+ let bestCount = 0;
252
+ for (const [slug, count] of counts) {
253
+ if (count > bestCount) {
254
+ best = slug;
255
+ bestCount = count;
256
+ }
257
+ }
258
+ return best;
259
+ }
260
+ /**
261
+ * One spelling per folder, whatever wrote it: forward slashes, Git Bash's
262
+ * `/c/Users/...` as `c:/users/...`, and Windows drive paths lower-cased
263
+ * (Windows paths are case-insensitive, and Claude Code, Git Bash and Node
264
+ * do not agree on the drive letter's case).
265
+ */
266
+ function comparablePath(path) {
267
+ let value = path.replace(/\\/g, "/");
268
+ const gitBash = /^\/([a-zA-Z])\//.exec(value);
269
+ if (gitBash)
270
+ value = `${gitBash[1]}:/${value.slice(3)}`;
271
+ if (/^[a-zA-Z]:\//.test(value))
272
+ value = value.toLowerCase();
273
+ return value.replace(/\/+$/, "");
274
+ }
275
+ function isInsideWorkspace(cwd, workspaceRoot) {
276
+ if (workspaceRoot) {
277
+ const here = comparablePath(cwd);
278
+ const root = comparablePath(workspaceRoot);
279
+ if (here === root || here.startsWith(`${root}/`))
280
+ return true;
281
+ }
282
+ return cwd.toLowerCase().includes("installagent");
283
+ }
284
+ function sessionPoints(raw, known, workspaceRoot, sinceMs, untilMs) {
285
+ const events = [];
286
+ let insideWorkspace = false;
287
+ let lines = 0;
288
+ let first = null;
289
+ let last = null;
290
+ for (const rawLine of raw.split("\n")) {
291
+ const trimmed = rawLine.trim();
292
+ if (!trimmed)
293
+ continue;
294
+ let line;
295
+ try {
296
+ line = JSON.parse(trimmed);
297
+ }
298
+ catch {
299
+ continue; // A session still being written can end in a partial line.
300
+ }
301
+ if (line.type !== "user" && line.type !== "assistant")
302
+ continue;
303
+ if (line.isSidechain === true)
304
+ continue;
305
+ const ts = typeof line.timestamp === "string" ? Date.parse(line.timestamp) : Number.NaN;
306
+ if (Number.isNaN(ts))
307
+ continue;
308
+ if (typeof line.cwd === "string" && isInsideWorkspace(line.cwd, workspaceRoot)) {
309
+ insideWorkspace = true;
310
+ }
311
+ events.push({ ts, slug: mostMentioned(slugsInLine(line, known)) });
312
+ if ((sinceMs === null || ts >= sinceMs) && (untilMs === null || ts <= untilMs)) {
313
+ lines += 1;
314
+ if (first === null || ts < first)
315
+ first = ts;
316
+ if (last === null || ts > last)
317
+ last = ts;
318
+ }
319
+ }
320
+ events.sort((a, b) => a.ts - b.ts);
321
+ const firstSlug = events.find((event) => event.slug !== null)?.slug ?? null;
322
+ if (firstSlug === null && !insideWorkspace) {
323
+ return { points: [], skipped: events.length > 0, lines, first, last };
324
+ }
325
+ // Carry the last-seen client forward; the lines before the first mention take the first one.
326
+ let current = firstSlug ?? UNATTRIBUTED_SLUG;
327
+ const points = [];
328
+ for (const event of events) {
329
+ current = event.slug ?? current;
330
+ if (sinceMs !== null && event.ts < sinceMs)
331
+ continue;
332
+ if (untilMs !== null && event.ts > untilMs)
333
+ continue;
334
+ points.push({ ts: event.ts, slug: current });
335
+ }
336
+ return { points, skipped: false, lines, first, last };
337
+ }
338
+ function minuteIso(minute) {
339
+ return `${new Date(minute * 60_000).toISOString().slice(0, 16)}Z`;
340
+ }
341
+ /** Parse a "YYYY-MM-DDTHH:MMZ" minute from an export back to epoch ms. */
342
+ export function parseMinuteIso(value) {
343
+ return Date.parse(`${value.slice(0, 16)}:00.000Z`);
344
+ }
345
+ /** Where exports are kept on the technician's machine (and where the weekly job writes). */
346
+ export const HOURS_EXPORT_DIR = join(".config", "installagent", "hours-export");
347
+ /**
348
+ * Write an export to disk. The default location is this command's own folder
349
+ * and keeps one file per person per (Eastern) day: a rerun the same day
350
+ * replaces it, since the newer export covers everything the older one did. An
351
+ * explicit `out` path is the caller's file and is never overwritten without
352
+ * `force`. Returns the path written.
353
+ */
354
+ export function saveClaudeHoursExport(result, options = {}) {
355
+ const date = ledgerDay(Date.parse(result.generatedAt));
356
+ const name = `ia-hours-export-${result.person.toLowerCase()}-${date}.json`;
357
+ const outPath = options.out
358
+ ? resolve(options.cwd ?? process.cwd(), options.out)
359
+ : join(options.homeDir ?? homedir(), HOURS_EXPORT_DIR, name);
360
+ if (options.out && existsSync(outPath) && !options.force) {
361
+ throw new Error(`${outPath} already exists — pass --force to overwrite, or another --out`);
362
+ }
363
+ mkdirSync(dirname(outPath), { recursive: true, mode: 0o700 });
364
+ writeFileSync(outPath, `${JSON.stringify(result, null, 2)}\n`);
365
+ return outPath;
366
+ }
367
+ /** The ledger keeper's n8n intake: it DMs the file to them on Slack. Not a secret. */
368
+ export const HOURS_EXPORT_WEBHOOK_URL = "https://n8n.installagent.com/webhook/hours-export";
369
+ /** Shared secret the intake webhook checks, sent as HOURS_EXPORT_SECRET_HEADER. */
370
+ export const HOURS_EXPORT_SECRET_ENV = "HOURS_EXPORT_SECRET";
371
+ export const HOURS_EXPORT_SECRET_HEADER = "x-hours-export-secret";
372
+ /**
373
+ * Send an export to the ledger keeper through the n8n intake webhook, which
374
+ * DMs them the file on Slack. Throws with a plain reason on any failure — the
375
+ * caller keeps the file on disk either way.
376
+ */
377
+ export async function sendClaudeHoursExport(result, options = {}) {
378
+ const env = options.env ?? process.env;
379
+ const secret = env[HOURS_EXPORT_SECRET_ENV];
380
+ if (!secret) {
381
+ throw new Error(`not sent: ${HOURS_EXPORT_SECRET_ENV} is not set in the workspace .env — ask whoever keeps ` +
382
+ "the hours ledger for it");
383
+ }
384
+ const url = options.webhookUrl ?? HOURS_EXPORT_WEBHOOK_URL;
385
+ let res;
386
+ try {
387
+ res = await (options.fetchImpl ?? fetch)(url, {
388
+ method: "POST",
389
+ headers: { "Content-Type": "application/json", [HOURS_EXPORT_SECRET_HEADER]: secret },
390
+ body: JSON.stringify(result),
391
+ });
392
+ }
393
+ catch (error) {
394
+ throw new Error(`not sent: could not reach n8n (${error instanceof Error ? error.message : error})`);
395
+ }
396
+ if (res.status === 401 || res.status === 403) {
397
+ throw new Error(`not sent: the intake rejected ${HOURS_EXPORT_SECRET_ENV} — check its value`);
398
+ }
399
+ if (res.status === 404) {
400
+ throw new Error("not sent: the hours-export intake is not live yet (n8n workflow not published)");
401
+ }
402
+ if (!res.ok)
403
+ throw new Error(`not sent: the hours-export intake answered HTTP ${res.status}`);
404
+ }
405
+ /** Save the export, then send it unless `send` is false. A failed send never loses the file. */
406
+ export async function deliverClaudeHoursExport(result, options = {}) {
407
+ const outPath = saveClaudeHoursExport(result, options);
408
+ if (options.send === false)
409
+ return { outPath, sent: false, sendError: null };
410
+ try {
411
+ await sendClaudeHoursExport(result, options);
412
+ return { outPath, sent: true, sendError: null };
413
+ }
414
+ catch (error) {
415
+ return {
416
+ outPath,
417
+ sent: false,
418
+ sendError: error instanceof Error ? error.message : String(error),
419
+ };
420
+ }
421
+ }
422
+ /** The export minus its per-minute lists (replaced by counts) — for showing to a person or an agent. */
423
+ export function compactClaudeHoursExport(result) {
424
+ const { minutes, ...rest } = result;
425
+ const minuteCounts = {};
426
+ for (const [slug, list] of Object.entries(minutes))
427
+ minuteCounts[slug] = list.length;
428
+ return { ...rest, minuteCounts };
429
+ }
430
+ /**
431
+ * Read this machine's Claude Code session logs and return one person's
432
+ * per-client activity minutes (plus a Claude-only hours summary), for
433
+ * handing to whoever maintains the ledger. Read-only: never writes
434
+ * anywhere, never transmits anything itself.
435
+ */
436
+ export async function exportClaudeHours(options) {
437
+ const person = options.person?.trim();
438
+ if (!person) {
439
+ throw new Error("person is required — the name the hours ledger knows you by, e.g. Ian");
440
+ }
441
+ const homeDirValue = options.homeDir ?? homedir();
442
+ const env = options.env ?? process.env;
443
+ const now = (options.now ?? (() => new Date()))();
444
+ const sinceMs = options.since ? parseLedgerDate(options.since, "--since") : null;
445
+ const untilMs = options.until ? parseLedgerDate(options.until, "--until") + 86_400_000 - 1 : null;
446
+ if (sinceMs !== null && untilMs !== null && sinceMs > untilMs) {
447
+ throw new Error(`--since (${options.since}) is after --until (${options.until})`);
448
+ }
449
+ const configDirs = options.configDirs ?? resolveConfigDirs(homeDirValue, env);
450
+ const workspaceRoot = options.workspaceRoot === undefined ? findWorkspaceRoot() : options.workspaceRoot;
451
+ const known = knownSlugsIn(workspaceRoot);
452
+ const unreadableSessions = [];
453
+ const minuteSets = new Map();
454
+ let skippedSessions = 0;
455
+ let lines = 0;
456
+ let firstMs = null;
457
+ let lastMs = null;
458
+ for (const file of listSessionFiles(configDirs)) {
459
+ let raw;
460
+ try {
461
+ raw = readFileSync(file, "utf8");
462
+ }
463
+ catch {
464
+ unreadableSessions.push(file);
465
+ log.debug("session-read-failed", { file });
466
+ continue;
467
+ }
468
+ const session = sessionPoints(raw, known, workspaceRoot, sinceMs, untilMs);
469
+ lines += session.lines;
470
+ if (session.first !== null && (firstMs === null || session.first < firstMs)) {
471
+ firstMs = session.first;
472
+ }
473
+ if (session.last !== null && (lastMs === null || session.last > lastMs))
474
+ lastMs = session.last;
475
+ if (session.skipped)
476
+ skippedSessions += 1;
477
+ for (const point of session.points) {
478
+ const set = minuteSets.get(point.slug) ?? new Set();
479
+ set.add(minuteOf(point.ts));
480
+ minuteSets.set(point.slug, set);
481
+ }
482
+ }
483
+ const minutes = {};
484
+ const events = [];
485
+ for (const slug of [...minuteSets.keys()].sort()) {
486
+ const sorted = [...(minuteSets.get(slug) ?? [])].sort((a, b) => a - b);
487
+ minutes[slug] = sorted.map(minuteIso);
488
+ for (const minute of sorted) {
489
+ events.push({ source: "claude", person, slug, ts: minute * 60_000, durationMin: null });
490
+ }
491
+ }
492
+ const estimate = estimateHours(events).hours[person] ?? {};
493
+ const summary = Object.keys(minutes)
494
+ .map((slug) => {
495
+ const { byMonth, total } = roundMonths(estimate[slug]);
496
+ return {
497
+ slug,
498
+ known: known.has(slug) || slug === UNATTRIBUTED_SLUG,
499
+ activeMinutes: minutes[slug]?.length ?? 0,
500
+ hoursByMonth: byMonth,
501
+ hoursTotal: total,
502
+ };
503
+ })
504
+ .sort((a, b) => b.hoursTotal - a.hoursTotal || a.slug.localeCompare(b.slug));
505
+ return {
506
+ schema: HOURS_EXPORT_SCHEMA,
507
+ person,
508
+ generatedAt: now.toISOString(),
509
+ windowSince: options.since ?? null,
510
+ windowUntil: options.until ?? null,
511
+ configDirsUsed: configDirs,
512
+ workspaceRoot,
513
+ events: {
514
+ first: firstMs !== null ? new Date(firstMs).toISOString() : null,
515
+ last: lastMs !== null ? new Date(lastMs).toISOString() : null,
516
+ lines,
517
+ },
518
+ minutes,
519
+ summary,
520
+ skippedSessions,
521
+ unreadableSessions,
522
+ };
523
+ }
@@ -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";
package/dist/env-fill.js CHANGED
@@ -166,18 +166,35 @@ function writableValue(value) {
166
166
  return `'${value}'`;
167
167
  return null;
168
168
  }
169
- /** Replace only the empty `NAME=` lines being filled; leave everything else byte-for-byte. */
169
+ /**
170
+ * Replace only the empty `NAME=` lines being filled; leave everything else
171
+ * byte-for-byte. A var with no line at all (a `.env` made before the var was
172
+ * added to the registry) is appended at the end — without this it was reported
173
+ * "filled" and silently never written.
174
+ */
170
175
  function applyFills(content, fills) {
171
- return content
176
+ const pending = new Map(fills);
177
+ let out = content
172
178
  .split("\n")
173
179
  .map((line) => {
174
180
  const match = line.match(/^(export\s+)?([A-Za-z_][A-Za-z0-9_]*)=\s*$/);
175
181
  if (!match)
176
182
  return line;
177
- const value = fills.get(match[2]);
178
- return value === undefined ? line : `${match[1] ?? ""}${match[2]}=${value}`;
183
+ const name = match[2] ?? "";
184
+ const value = pending.get(name);
185
+ if (value === undefined)
186
+ return line;
187
+ pending.delete(name);
188
+ return `${match[1] ?? ""}${name}=${value}`;
179
189
  })
180
190
  .join("\n");
191
+ if (pending.size === 0)
192
+ return out;
193
+ if (out.length > 0 && !out.endsWith("\n"))
194
+ out += "\n";
195
+ for (const [name, value] of pending)
196
+ out += `${name}=${value}\n`;
197
+ return out;
181
198
  }
182
199
  function personalHomework(existing) {
183
200
  return TECH_ENV_VARS.filter((spec) => spec.source === "personal" &&
@@ -50,6 +50,10 @@ export declare const DEFAULT_TECH_VAULT = "team-techs";
50
50
  export declare const INFRA_VAULT = "team-admin";
51
51
  /** Only `ia secrets mint gemini-api-key` reads it, so it has no owning module. */
52
52
  export declare const GEMINI_API_KEY_ENV = "GEMINI_API_KEY";
53
+ /** Read by apps/slack-agent (relay.ts, feedback.ts) — an app, so it has no SDK module. */
54
+ export declare const SLACK_RELAY_SECRET_ENV = "SLACK_RELAY_SECRET";
55
+ /** Read by nothing; registered so every team-techs item is accounted for. */
56
+ export declare const N8N_OAUTH_CALLBACK_URL_ENV = "N8N_OAUTH_CALLBACK_URL";
53
57
  /**
54
58
  * Single source of truth for every workspace-root .env var: doctor derives
55
59
  * its env checks from it, `ia env fill` knows which vars 1Password can