@installagent/sdk 0.1.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 (114) hide show
  1. package/dist/agent-mirror.d.ts +69 -0
  2. package/dist/agent-mirror.js +275 -0
  3. package/dist/agent-templates.d.ts +36 -2
  4. package/dist/agent-templates.js +173 -3
  5. package/dist/claude-hours.d.ts +118 -0
  6. package/dist/claude-hours.js +523 -0
  7. package/dist/client-drive.d.ts +3 -0
  8. package/dist/client-drive.js +2 -2
  9. package/dist/client-linear-create.d.ts +26 -0
  10. package/dist/client-linear-create.js +46 -0
  11. package/dist/client-linear.d.ts +28 -9
  12. package/dist/client-linear.js +36 -14
  13. package/dist/docs-search.d.ts +19 -6
  14. package/dist/docs-search.js +32 -11
  15. package/dist/doctor.d.ts +9 -0
  16. package/dist/doctor.js +126 -23
  17. package/dist/env-fill.d.ts +13 -0
  18. package/dist/env-fill.js +55 -13
  19. package/dist/env-push.d.ts +3 -0
  20. package/dist/env-push.js +11 -6
  21. package/dist/env-registry.d.ts +29 -0
  22. package/dist/env-registry.js +123 -9
  23. package/dist/exec.js +15 -2
  24. package/dist/git.d.ts +31 -0
  25. package/dist/git.js +59 -0
  26. package/dist/google-service-account.d.ts +20 -0
  27. package/dist/google-service-account.js +49 -0
  28. package/dist/hours-estimate.d.ts +43 -0
  29. package/dist/hours-estimate.js +159 -0
  30. package/dist/hours-export-schedule.d.ts +35 -0
  31. package/dist/hours-export-schedule.js +188 -0
  32. package/dist/hours-ledger.d.ts +129 -0
  33. package/dist/hours-ledger.js +882 -0
  34. package/dist/index.d.ts +25 -6
  35. package/dist/index.js +25 -6
  36. package/dist/linear-project.d.ts +2 -2
  37. package/dist/linear-project.js +2 -2
  38. package/dist/log.d.ts +28 -0
  39. package/dist/log.js +73 -0
  40. package/dist/n8n-executions.d.ts +85 -0
  41. package/dist/n8n-executions.js +259 -0
  42. package/dist/op-cli.d.ts +29 -0
  43. package/dist/op-cli.js +52 -0
  44. package/dist/platform.d.ts +35 -0
  45. package/dist/platform.js +39 -0
  46. package/dist/portal-admin.d.ts +108 -0
  47. package/dist/portal-admin.js +94 -1
  48. package/dist/standup.d.ts +88 -0
  49. package/dist/standup.js +235 -0
  50. package/dist/sync-repos.d.ts +54 -0
  51. package/dist/sync-repos.js +89 -0
  52. package/dist/template-sync.d.ts +11 -0
  53. package/dist/template-sync.js +16 -0
  54. package/dist/triage-backfill.d.ts +37 -0
  55. package/dist/triage-backfill.js +211 -0
  56. package/dist/triage-enable.d.ts +90 -0
  57. package/dist/triage-enable.js +428 -0
  58. package/dist/triage-gates.d.ts +252 -0
  59. package/dist/triage-gates.js +951 -0
  60. package/dist/wizard.d.ts +15 -0
  61. package/dist/wizard.js +35 -56
  62. package/dist/workspace-docs.d.ts +44 -0
  63. package/dist/workspace-docs.js +73 -0
  64. package/dist/workspace-push.d.ts +39 -0
  65. package/dist/workspace-push.js +78 -0
  66. package/dist/workspace-status.d.ts +37 -0
  67. package/dist/workspace-status.js +114 -0
  68. package/package.json +2 -2
  69. package/templates/env.example +37 -23
  70. package/templates/workspace-root/.claude/settings.json +12 -1
  71. package/templates/workspace-root/AGENT.md +7 -5
  72. package/templates/workspace-root/ONBOARDING.md +65 -8
  73. package/templates/workspace-root/skills/.github/workflows/pr-to-slack.yml +127 -0
  74. package/templates/workspace-root/skills/CLAUDE.md +29 -6
  75. package/templates/workspace-root/skills/README.md +171 -0
  76. package/templates/workspace-root/skills/ad-machine/SKILL.md +140 -0
  77. package/templates/workspace-root/skills/backtest-acceptance-gates/SKILL.md +293 -0
  78. package/templates/workspace-root/skills/backtest-acceptance-gates/backtest-acceptance-gates-guide.pdf +0 -0
  79. package/templates/workspace-root/skills/backtest-acceptance-gates/references/evidence-record-template.md +128 -0
  80. package/templates/workspace-root/skills/backtest-acceptance-gates/references/harness-checklist.md +90 -0
  81. package/templates/workspace-root/skills/client-deliverables/SKILL.md +1 -1
  82. package/templates/workspace-root/skills/client-deliverables/references/package-layout.md +3 -2
  83. package/templates/workspace-root/skills/client-latest/SKILL.md +343 -0
  84. package/templates/workspace-root/skills/client-latest/catchup.command.md +18 -0
  85. package/templates/workspace-root/skills/cloud-devops/SKILL.md +235 -0
  86. package/templates/workspace-root/skills/email-triage-rollout/SKILL.md +258 -0
  87. package/templates/workspace-root/skills/engagement-spec/SKILL.md +51 -18
  88. package/templates/workspace-root/skills/engagement-spec/references/spec-templates.md +10 -4
  89. package/templates/workspace-root/skills/gcloud-cli-setup/SKILL.md +100 -0
  90. package/templates/workspace-root/skills/github-profile/SKILL.md +106 -0
  91. package/templates/workspace-root/skills/google-chat-app-setup/SKILL.md +136 -0
  92. package/templates/workspace-root/skills/google-chat-app-setup/google-chat-app-setup-guide.pdf +0 -0
  93. package/templates/workspace-root/skills/house-voice/SKILL.md +80 -4
  94. package/templates/workspace-root/skills/ia-cli/SKILL.md +49 -7
  95. package/templates/workspace-root/skills/init_repo/SKILL.md +188 -0
  96. package/templates/workspace-root/skills/installagent-brand-kit/SKILL.md +59 -10
  97. package/templates/workspace-root/skills/installagent-brand-kit/assets/installagent-deck-template.pptx +0 -0
  98. package/templates/workspace-root/skills/installagent-brand-kit/references/deck-guide.md +181 -0
  99. package/templates/workspace-root/skills/installagent-brand-kit/scripts/deck.py +652 -0
  100. package/templates/workspace-root/skills/installagent-brand-kit/scripts/deck_lint.py +201 -0
  101. package/templates/workspace-root/skills/installagent-brand-kit/scripts/logo_raster.py +102 -0
  102. package/templates/workspace-root/skills/installagent-brand-kit/scripts/make_deck_template.py +290 -0
  103. package/templates/workspace-root/skills/salesforce-api-snapshot/SKILL.md +379 -0
  104. package/templates/workspace-root/skills/salesforce-api-snapshot/references/schema-discovery-soql.md +153 -0
  105. package/templates/workspace-root/skills/salesforce-api-snapshot/references/snapshot-storage.md +122 -0
  106. package/templates/workspace-root/skills/salesforce-api-snapshot/salesforce-api-snapshot-guide.pdf +0 -0
  107. package/templates/workspace-root/skills/slack-voice/SKILL.md +158 -0
  108. package/templates/workspace-root/skills/sso-gated-client-app/SKILL.md +337 -0
  109. package/templates/workspace-root/skills/sso-gated-client-app/sso-gated-client-app-guide.pdf +0 -0
  110. package/templates/workspace-root/skills/tech-call-prep/SKILL.md +146 -47
  111. package/templates/workspace-root/skills/vendor-feed-ingestion/SKILL.md +323 -0
  112. package/templates/workspace-root/skills/vendor-feed-ingestion/references/delivery-contract-template.md +110 -0
  113. package/templates/workspace-root/skills/vendor-feed-ingestion/references/feed-guards.md +134 -0
  114. package/templates/workspace-root/skills/vendor-feed-ingestion/vendor-feed-ingestion-guide.pdf +0 -0
@@ -0,0 +1,49 @@
1
+ import { createSign } from "node:crypto";
2
+ import { GOOGLE_SERVICE_ACCOUNT_KEY_ENV, parseServiceAccountKey } from "./client-drive.js";
3
+ // Shared JWT-bearer grant for Google service accounts. client-drive.ts grew
4
+ // its own copy first (Drive read-only); this helper generalises the scope so
5
+ // later readers (Sheets, …) do not each re-implement RS256 signing.
6
+ export const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
7
+ const JWT_LIFETIME_SECONDS = 3600;
8
+ /** Thrown when the service-account key is missing, malformed, or rejected by Google. */
9
+ export class GoogleServiceAccountAuthError extends Error {
10
+ }
11
+ export function buildServiceAccountClaims(clientEmail, scope, nowMs) {
12
+ const iat = Math.floor(nowMs / 1000);
13
+ return { iss: clientEmail, scope, aud: GOOGLE_TOKEN_URL, iat, exp: iat + JWT_LIFETIME_SECONDS };
14
+ }
15
+ function base64url(input) {
16
+ return Buffer.from(input).toString("base64url");
17
+ }
18
+ function signAssertion(claims, privateKeyPem) {
19
+ const header = { alg: "RS256", typ: "JWT" };
20
+ const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(claims))}`;
21
+ const signature = createSign("RSA-SHA256").update(signingInput).end().sign(privateKeyPem);
22
+ return `${signingInput}.${base64url(signature)}`;
23
+ }
24
+ /**
25
+ * Exchange a service-account key for a short-lived access token carrying
26
+ * exactly `scope`. The caller decides the scope — keep it the narrowest that
27
+ * works (`*.readonly` wherever the operation only reads).
28
+ */
29
+ export async function getServiceAccountAccessToken(serviceAccountKeyRaw, scope, fetchImpl, now) {
30
+ const { clientEmail, privateKey } = parseServiceAccountKey(serviceAccountKeyRaw);
31
+ const assertion = signAssertion(buildServiceAccountClaims(clientEmail, scope, now()), privateKey);
32
+ const res = await fetchImpl(GOOGLE_TOKEN_URL, {
33
+ method: "POST",
34
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
35
+ body: new URLSearchParams({
36
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
37
+ assertion,
38
+ }),
39
+ });
40
+ if (!res.ok) {
41
+ throw new GoogleServiceAccountAuthError(`Google rejected the service-account assertion for ${clientEmail} (HTTP ${res.status}) — ` +
42
+ `check ${GOOGLE_SERVICE_ACCOUNT_KEY_ENV} is current. ${await res.text()}`);
43
+ }
44
+ const body = (await res.json());
45
+ if (!body.access_token) {
46
+ throw new GoogleServiceAccountAuthError("Google's token response had no access_token");
47
+ }
48
+ return { accessToken: body.access_token, clientEmail };
49
+ }
@@ -0,0 +1,43 @@
1
+ export type HoursSource = "call" | "claude" | "git" | "linear" | "slack";
2
+ export declare const HOURS_SOURCES: readonly HoursSource[];
3
+ export declare const SESSION_GAP_MINUTES = 30;
4
+ export declare const LEAD_HEAVY_MINUTES = 15;
5
+ export declare const LEAD_LIGHT_MINUTES = 5;
6
+ export declare const LEDGER_TIME_ZONE = "America/New_York";
7
+ export interface ActivityEvent {
8
+ source: HoursSource;
9
+ /** Ledger person name, e.g. "Ian". */
10
+ person: string;
11
+ /** Client slug, or a pseudo-slug such as "unattributed" / "other-lead". */
12
+ slug: string;
13
+ /** Epoch milliseconds (UTC). */
14
+ ts: number;
15
+ /** Fixed length in minutes (a call); null for a point event. */
16
+ durationMin: number | null;
17
+ }
18
+ /** person → slug → month (YYYY-MM) → hours. Unrounded. */
19
+ export type HoursByPersonSlugMonth = Record<string, Record<string, Record<string, number>>>;
20
+ export interface HoursEstimate {
21
+ hours: HoursByPersonSlugMonth;
22
+ /** person → slug → hours on days before that slug's tech start date. Unrounded. */
23
+ beforeStart: Record<string, Record<string, number>>;
24
+ }
25
+ export interface EstimateHoursOptions {
26
+ /** Count only these sources (e.g. one source, for the per-source columns). Default: all. */
27
+ sources?: ReadonlySet<HoursSource>;
28
+ /** A client's tech start date (YYYY-MM-DD), for `beforeStart`; null when it has none. */
29
+ techStart?: (slug: string) => string | null;
30
+ }
31
+ /** Calendar day (YYYY-MM-DD) of an instant, in the ledger's time zone. */
32
+ export declare function ledgerDay(ms: number): string;
33
+ /** Calendar month (YYYY-MM) of an instant, in the ledger's time zone. */
34
+ export declare function ledgerMonth(ms: number): string;
35
+ export declare function minuteOf(ms: number): number;
36
+ /** Apply the ledger's rules to a set of events. */
37
+ export declare function estimateHours(events: ActivityEvent[], options?: EstimateHoursOptions): HoursEstimate;
38
+ export declare function round2(value: number): number;
39
+ /** Round every month and sum the rounded months — the ledger's own totals convention. */
40
+ export declare function roundMonths(months: Record<string, number> | undefined): {
41
+ byMonth: Record<string, number>;
42
+ total: number;
43
+ };
@@ -0,0 +1,159 @@
1
+ // The internal hours ledger's estimate rules, in one place: `ia hours-export`
2
+ // (one technician's Claude Code time, computed on their own machine) and
3
+ // `ia hours-ledger` (every source merged, computed centrally) both call this,
4
+ // so the two can never drift apart the way the first TypeScript port of the
5
+ // Claude Code export did. Ported from the ledger's original estimate script:
6
+ //
7
+ // - A call counts as its real length and gets no lead time.
8
+ // - Point events (a Claude Code minute, a commit, a Slack message, a Linear
9
+ // event) for one person and one client join one work session while each
10
+ // is less than SESSION_GAP_MINUTES after the previous one. A session also
11
+ // gets lead time before its first event: LEAD_HEAVY_MINUTES when it holds
12
+ // a commit or Claude Code activity, LEAD_LIGHT_MINUTES when it is only
13
+ // Slack or Linear.
14
+ // - Each person's minute counts once: a minute covered by a call and a
15
+ // session, or by two sources, counts one time. A minute covered for two
16
+ // clients (parallel sessions) is split between them.
17
+ // - Months and days are calendar months and days in LEDGER_TIME_ZONE.
18
+ //
19
+ // Everything here is pure: no I/O, no clock.
20
+ export const HOURS_SOURCES = ["call", "claude", "git", "linear", "slack"];
21
+ /** Sources whose sessions get the long lead time. */
22
+ const HEAVY_SOURCES = new Set(["claude", "git"]);
23
+ export const SESSION_GAP_MINUTES = 30;
24
+ export const LEAD_HEAVY_MINUTES = 15;
25
+ export const LEAD_LIGHT_MINUTES = 5;
26
+ export const LEDGER_TIME_ZONE = "America/New_York";
27
+ const MINUTE_MS = 60_000;
28
+ const HOUR_MS = 3_600_000;
29
+ // ET offsets are whole hours, so one lookup per UTC hour is exact — and
30
+ // cheap enough to run for every covered minute of every person.
31
+ const dayCache = new Map();
32
+ const dayFormatter = new Intl.DateTimeFormat("en-CA", {
33
+ timeZone: LEDGER_TIME_ZONE,
34
+ year: "numeric",
35
+ month: "2-digit",
36
+ day: "2-digit",
37
+ });
38
+ /** Calendar day (YYYY-MM-DD) of an instant, in the ledger's time zone. */
39
+ export function ledgerDay(ms) {
40
+ const hour = Math.floor(ms / HOUR_MS);
41
+ let day = dayCache.get(hour);
42
+ if (day === undefined) {
43
+ // en-CA formats as YYYY-MM-DD.
44
+ day = dayFormatter.format(new Date(hour * HOUR_MS));
45
+ dayCache.set(hour, day);
46
+ }
47
+ return day;
48
+ }
49
+ /** Calendar month (YYYY-MM) of an instant, in the ledger's time zone. */
50
+ export function ledgerMonth(ms) {
51
+ return ledgerDay(ms).slice(0, 7);
52
+ }
53
+ export function minuteOf(ms) {
54
+ return Math.floor(ms / MINUTE_MS);
55
+ }
56
+ /** One person's events on one client → covered [start, end) minute intervals. */
57
+ function intervals(events) {
58
+ const out = [];
59
+ const points = [];
60
+ for (const event of events) {
61
+ if (event.durationMin === null) {
62
+ points.push(event);
63
+ continue;
64
+ }
65
+ const start = minuteOf(event.ts);
66
+ out.push({
67
+ start,
68
+ end: start + Math.max(event.durationMin, 1),
69
+ sources: new Set([event.source]),
70
+ });
71
+ }
72
+ points.sort((a, b) => a.ts - b.ts);
73
+ let session = null;
74
+ for (const event of points) {
75
+ const minute = minuteOf(event.ts);
76
+ if (session && minute - session.end < SESSION_GAP_MINUTES) {
77
+ session.end = Math.max(session.end, minute + 1);
78
+ session.sources.add(event.source);
79
+ }
80
+ else {
81
+ if (session)
82
+ out.push(session);
83
+ session = { start: minute, end: minute + 1, sources: new Set([event.source]) };
84
+ }
85
+ }
86
+ if (session)
87
+ out.push(session);
88
+ for (const interval of out) {
89
+ const onlyCalls = [...interval.sources].every((source) => source === "call");
90
+ if (onlyCalls)
91
+ continue; // a call keeps its real length; no lead time
92
+ const heavy = [...interval.sources].some((source) => HEAVY_SOURCES.has(source));
93
+ interval.start -= heavy ? LEAD_HEAVY_MINUTES : LEAD_LIGHT_MINUTES;
94
+ }
95
+ return out;
96
+ }
97
+ /** Apply the ledger's rules to a set of events. */
98
+ export function estimateHours(events, options = {}) {
99
+ const byPerson = new Map();
100
+ for (const event of events) {
101
+ if (options.sources && !options.sources.has(event.source))
102
+ continue;
103
+ let bySlug = byPerson.get(event.person);
104
+ if (!bySlug) {
105
+ bySlug = new Map();
106
+ byPerson.set(event.person, bySlug);
107
+ }
108
+ const list = bySlug.get(event.slug) ?? [];
109
+ list.push(event);
110
+ bySlug.set(event.slug, list);
111
+ }
112
+ const hours = {};
113
+ const beforeStart = {};
114
+ for (const [person, bySlug] of byPerson) {
115
+ const cover = new Map();
116
+ for (const [slug, slugEvents] of bySlug) {
117
+ for (const { start, end } of intervals(slugEvents)) {
118
+ for (let minute = start; minute < end; minute += 1) {
119
+ let slugs = cover.get(minute);
120
+ if (!slugs) {
121
+ slugs = new Set();
122
+ cover.set(minute, slugs);
123
+ }
124
+ slugs.add(slug);
125
+ }
126
+ }
127
+ }
128
+ const personHours = {};
129
+ const personBefore = {};
130
+ for (const [minute, slugs] of cover) {
131
+ const day = ledgerDay(minute * MINUTE_MS);
132
+ const month = day.slice(0, 7);
133
+ const share = 1 / 60 / slugs.size;
134
+ for (const slug of slugs) {
135
+ const months = personHours[slug] ?? {};
136
+ months[month] = (months[month] ?? 0) + share;
137
+ personHours[slug] = months;
138
+ const start = options.techStart?.(slug);
139
+ if (start && day < start)
140
+ personBefore[slug] = (personBefore[slug] ?? 0) + share;
141
+ }
142
+ }
143
+ hours[person] = personHours;
144
+ beforeStart[person] = personBefore;
145
+ }
146
+ return { hours, beforeStart };
147
+ }
148
+ export function round2(value) {
149
+ return Math.round(value * 100) / 100;
150
+ }
151
+ /** Round every month and sum the rounded months — the ledger's own totals convention. */
152
+ export function roundMonths(months) {
153
+ const byMonth = {};
154
+ for (const month of Object.keys(months ?? {}).sort()) {
155
+ byMonth[month] = round2(months?.[month] ?? 0);
156
+ }
157
+ const total = round2(Object.values(byMonth).reduce((sum, value) => sum + value, 0));
158
+ return { byMonth, total };
159
+ }
@@ -0,0 +1,35 @@
1
+ import type { ExecFileFn } from "./exec.js";
2
+ import { type Platform } from "./platform.js";
3
+ export interface HoursExportScheduleOptions {
4
+ /** Ledger name, e.g. "Ian". */
5
+ person: string;
6
+ workspaceRoot: string;
7
+ /** The Node binary to run (the CLI passes process.execPath). */
8
+ nodePath: string;
9
+ /** The `ia` entry script (the CLI passes process.argv[1]). */
10
+ iaScript: string;
11
+ platform?: Platform;
12
+ homeDir?: string;
13
+ exec?: ExecFileFn;
14
+ uid?: number;
15
+ }
16
+ export interface HoursExportScheduleResult {
17
+ platform: Platform;
18
+ runner: string;
19
+ /** The plist, the Windows task name, or "user crontab". */
20
+ scheduler: string;
21
+ when: string;
22
+ logPath: string;
23
+ }
24
+ /** Install (or replace) the weekly export job for this user. */
25
+ export declare function installHoursExportSchedule(options: HoursExportScheduleOptions): Promise<HoursExportScheduleResult>;
26
+ export interface UninstallHoursExportScheduleOptions {
27
+ platform?: Platform;
28
+ homeDir?: string;
29
+ exec?: ExecFileFn;
30
+ uid?: number;
31
+ }
32
+ /** Remove the weekly export job. Exports already written stay where they are. */
33
+ export declare function uninstallHoursExportSchedule(options?: UninstallHoursExportScheduleOptions): Promise<{
34
+ removed: string[];
35
+ }>;
@@ -0,0 +1,188 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir, tmpdir, userInfo } from "node:os";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { HOURS_EXPORT_DIR } from "./claude-hours.js";
7
+ import { detectPlatform } from "./platform.js";
8
+ // `ia hours-export --install-schedule` — run the export once a week on a
9
+ // technician's own machine, so nobody has to remember it and no Claude Code
10
+ // history is lost to its ~30-day log cleanup. One small runner script (cd into
11
+ // the workspace so the root .env loads, then run the export) plus the
12
+ // platform's own scheduler: launchd on macOS, Task Scheduler on Windows, the
13
+ // user crontab on Linux. Everything lives in the user's account; nothing needs
14
+ // admin rights.
15
+ const LAUNCHD_LABEL = "com.installagent.hours-export";
16
+ const WINDOWS_TASK = "InstallAgent hours export";
17
+ const CRON_MARKER = "# ia-hours-export";
18
+ /** Monday, 10:00 local time. */
19
+ const WEEKDAY = 1;
20
+ const HOUR = 10;
21
+ const defaultExec = async (file, args) => {
22
+ const { stdout, stderr } = await promisify(execFile)(file, [...args]);
23
+ return { stdout: String(stdout), stderr: String(stderr) };
24
+ };
25
+ /** Reject anything that could break out of the quoted runner script. */
26
+ function checkSafe(label, value) {
27
+ if (!value || /["\r\n`$%]/.test(value)) {
28
+ throw new Error(`${label} contains characters the scheduled job can't quote safely: ${value}`);
29
+ }
30
+ }
31
+ function paths(homeDir, platform) {
32
+ const dir = join(homeDir, HOURS_EXPORT_DIR);
33
+ return {
34
+ dir,
35
+ runner: join(dir, platform === "win32" ? "run-weekly.cmd" : "run-weekly.sh"),
36
+ logPath: join(dir, "weekly.log"),
37
+ plist: join(homeDir, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`),
38
+ };
39
+ }
40
+ function runnerScript(platform, options, logPath) {
41
+ const { workspaceRoot, nodePath, iaScript, person } = options;
42
+ if (platform === "win32") {
43
+ return [
44
+ "@echo off",
45
+ "rem Written by `ia hours-export --install-schedule` — weekly Claude Code export for the hours ledger.",
46
+ `cd /d "${workspaceRoot}" || exit /b 1`,
47
+ `"${nodePath}" "${iaScript}" hours-export --person "${person}" --force >> "${logPath}" 2>&1`,
48
+ "",
49
+ ].join("\r\n");
50
+ }
51
+ return [
52
+ "#!/bin/sh",
53
+ "# Written by `ia hours-export --install-schedule` — weekly Claude Code export for the hours ledger.",
54
+ `cd "${workspaceRoot}" || exit 1`,
55
+ `exec "${nodePath}" "${iaScript}" hours-export --person "${person}" --force`,
56
+ "",
57
+ ].join("\n");
58
+ }
59
+ function launchdPlist(runner, logPath) {
60
+ return `<?xml version="1.0" encoding="UTF-8"?>
61
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
62
+ <plist version="1.0">
63
+ <dict>
64
+ <key>Label</key><string>${LAUNCHD_LABEL}</string>
65
+ <key>ProgramArguments</key>
66
+ <array><string>/bin/sh</string><string>${runner}</string></array>
67
+ <key>StartCalendarInterval</key>
68
+ <dict><key>Weekday</key><integer>${WEEKDAY}</integer><key>Hour</key><integer>${HOUR}</integer><key>Minute</key><integer>0</integer></dict>
69
+ <key>StandardOutPath</key><string>${logPath}</string>
70
+ <key>StandardErrorPath</key><string>${logPath}</string>
71
+ </dict>
72
+ </plist>
73
+ `;
74
+ }
75
+ async function readCrontab(exec) {
76
+ try {
77
+ return (await exec("crontab", ["-l"])).stdout;
78
+ }
79
+ catch {
80
+ return ""; // no crontab yet
81
+ }
82
+ }
83
+ async function writeCrontab(exec, content) {
84
+ const file = join(tmpdir(), `ia-crontab-${process.pid}`);
85
+ writeFileSync(file, content);
86
+ try {
87
+ await exec("crontab", [file]);
88
+ }
89
+ finally {
90
+ rmSync(file, { force: true });
91
+ }
92
+ }
93
+ /** Install (or replace) the weekly export job for this user. */
94
+ export async function installHoursExportSchedule(options) {
95
+ const platform = options.platform ?? detectPlatform();
96
+ const exec = options.exec ?? defaultExec;
97
+ for (const [label, value] of [
98
+ ["--person", options.person],
99
+ ["workspace path", options.workspaceRoot],
100
+ ["node path", options.nodePath],
101
+ ["ia path", options.iaScript],
102
+ ]) {
103
+ checkSafe(label, value);
104
+ }
105
+ const p = paths(options.homeDir ?? homedir(), platform);
106
+ mkdirSync(p.dir, { recursive: true, mode: 0o700 });
107
+ writeFileSync(p.runner, runnerScript(platform, options, p.logPath), { mode: 0o700 });
108
+ const when = "every Monday at 10:00 (runs at next wake if the computer was off)";
109
+ if (platform === "darwin") {
110
+ const uid = options.uid ?? userInfo().uid;
111
+ mkdirSync(join(p.plist, ".."), { recursive: true });
112
+ writeFileSync(p.plist, launchdPlist(p.runner, p.logPath));
113
+ await exec("launchctl", ["bootout", `gui/${uid}/${LAUNCHD_LABEL}`]).catch(() => undefined);
114
+ await exec("launchctl", ["bootstrap", `gui/${uid}`, p.plist]);
115
+ return { platform, runner: p.runner, scheduler: p.plist, when, logPath: p.logPath };
116
+ }
117
+ if (platform === "win32") {
118
+ await exec("schtasks", [
119
+ "/Create",
120
+ "/F",
121
+ "/SC",
122
+ "WEEKLY",
123
+ "/D",
124
+ "MON",
125
+ "/ST",
126
+ `${String(HOUR).padStart(2, "0")}:00`,
127
+ "/TN",
128
+ WINDOWS_TASK,
129
+ "/TR",
130
+ `"${p.runner}"`,
131
+ ]);
132
+ return {
133
+ platform,
134
+ runner: p.runner,
135
+ scheduler: `Task Scheduler: ${WINDOWS_TASK}`,
136
+ when: "every Monday at 10:00",
137
+ logPath: p.logPath,
138
+ };
139
+ }
140
+ const current = await readCrontab(exec);
141
+ const kept = current.split("\n").filter((line) => line.trim() && !line.includes(CRON_MARKER));
142
+ kept.push(`0 ${HOUR} * * ${WEEKDAY} /bin/sh "${p.runner}" >> "${p.logPath}" 2>&1 ${CRON_MARKER}`);
143
+ await writeCrontab(exec, `${kept.join("\n")}\n`);
144
+ return {
145
+ platform,
146
+ runner: p.runner,
147
+ scheduler: "user crontab",
148
+ when: "every Monday at 10:00 (skipped if the computer is off)",
149
+ logPath: p.logPath,
150
+ };
151
+ }
152
+ /** Remove the weekly export job. Exports already written stay where they are. */
153
+ export async function uninstallHoursExportSchedule(options = {}) {
154
+ const platform = options.platform ?? detectPlatform();
155
+ const exec = options.exec ?? defaultExec;
156
+ const p = paths(options.homeDir ?? homedir(), platform);
157
+ const removed = [];
158
+ if (platform === "darwin") {
159
+ const uid = options.uid ?? userInfo().uid;
160
+ await exec("launchctl", ["bootout", `gui/${uid}/${LAUNCHD_LABEL}`]).catch(() => undefined);
161
+ if (existsSync(p.plist)) {
162
+ rmSync(p.plist);
163
+ removed.push(p.plist);
164
+ }
165
+ }
166
+ else if (platform === "win32") {
167
+ try {
168
+ await exec("schtasks", ["/Delete", "/F", "/TN", WINDOWS_TASK]);
169
+ removed.push(`Task Scheduler: ${WINDOWS_TASK}`);
170
+ }
171
+ catch {
172
+ // no such task
173
+ }
174
+ }
175
+ else {
176
+ const current = await readCrontab(exec);
177
+ if (current.includes(CRON_MARKER)) {
178
+ const kept = current.split("\n").filter((line) => line.trim() && !line.includes(CRON_MARKER));
179
+ await writeCrontab(exec, kept.length ? `${kept.join("\n")}\n` : "");
180
+ removed.push("user crontab line");
181
+ }
182
+ }
183
+ if (existsSync(p.runner)) {
184
+ rmSync(p.runner);
185
+ removed.push(p.runner);
186
+ }
187
+ return { removed };
188
+ }
@@ -0,0 +1,129 @@
1
+ import { type ClaudeHoursExportOptions, type ClaudeHoursExportResult } from "./claude-hours.js";
2
+ import type { ExecFileFn } from "./exec.js";
3
+ import { type HoursSource } from "./hours-estimate.js";
4
+ export declare const HOURS_LEDGER_SCHEMA = "ia-hours-ledger/1";
5
+ /** Where the ledger keeps its config, inbox, frozen sources, Claude store and output. */
6
+ export declare const DEFAULT_HOURS_LEDGER_DIR: string;
7
+ /** The ledger's window starts here unless --since says otherwise. */
8
+ export declare const LEDGER_WINDOW_START = "2026-06-01";
9
+ /** Activity on a slug that is neither an engagement in the CRM nor a build repo. */
10
+ export declare const OTHER_LEAD_SLUG = "other-lead";
11
+ /**
12
+ * The only Clients - Master fields ever requested. No package, contract value or MRR — on
13
+ * purpose — and no Name either: for some records it holds a contact person, not the business.
14
+ * The display name comes from the registry profile's `dba` / `legal_name` (`registryName`).
15
+ */
16
+ export declare const CLIENT_FIELDS: readonly ["Slug", "Status", "Technician", "Tech Start Date"];
17
+ /** The only Team - Master fields ever requested. No pay — on purpose. */
18
+ export declare const TEAM_FIELDS: readonly ["Name", "Email"];
19
+ export interface HoursLedgerConfig {
20
+ /** Ledger name → identities in git and Linear (see `identityMatches`). Order = page order. */
21
+ people: Record<string, {
22
+ emails: string[];
23
+ }>;
24
+ /** Client code outside clients/client-<slug>, e.g. a deploy clone. `~` is expanded. */
25
+ extraRepos?: Array<{
26
+ slug: string;
27
+ path: string;
28
+ }>;
29
+ }
30
+ export interface HoursLedgerRow {
31
+ person: string;
32
+ slug: string;
33
+ client: string;
34
+ crm_tech: string | null;
35
+ is_technician: boolean;
36
+ status: string | null;
37
+ tech_start: string | null;
38
+ hours_by_month: Record<string, number>;
39
+ hours_total: number;
40
+ hours_before_start: number;
41
+ hours_by_source: Partial<Record<HoursSource, number>>;
42
+ event_counts: Partial<Record<HoursSource, number>>;
43
+ }
44
+ export interface HoursLedgerData {
45
+ schema: typeof HOURS_LEDGER_SCHEMA;
46
+ generated: string;
47
+ window_start: string;
48
+ window_end: string;
49
+ people: string[];
50
+ /** People with no Claude Code data at all yet. */
51
+ claude_missing: string[];
52
+ /** person → last day their Claude Code data reaches. */
53
+ claude_through: Record<string, string>;
54
+ /** source → last day of a source that only comes from frozen files. */
55
+ frozen_sources: Record<string, string>;
56
+ first_event: string | null;
57
+ rules: {
58
+ gap_min: number;
59
+ lead_heavy_min: number;
60
+ lead_light_min: number;
61
+ time_zone: string;
62
+ };
63
+ /** source → person → [first day, last day, event count]. */
64
+ source_ranges: Partial<Record<HoursSource, Record<string, [string, string, number]>>>;
65
+ rows: HoursLedgerRow[];
66
+ }
67
+ export interface HoursLedgerIngest {
68
+ person: string;
69
+ file: string;
70
+ from: string;
71
+ to: string;
72
+ minutes: number;
73
+ }
74
+ export interface HoursLedgerPersonTotal {
75
+ person: string;
76
+ ownClients: number;
77
+ helping: number;
78
+ unattributed: number;
79
+ bySource: Partial<Record<HoursSource, number>>;
80
+ }
81
+ export interface HoursLedgerResult {
82
+ outPath: string;
83
+ ledgerDir: string;
84
+ data: HoursLedgerData;
85
+ ingested: HoursLedgerIngest[];
86
+ totals: HoursLedgerPersonTotal[];
87
+ warnings: string[];
88
+ }
89
+ export interface HoursLedgerOptions {
90
+ /** Default: ~/.config/installagent/hours-ledger. */
91
+ ledgerDir?: string;
92
+ /** Default: found by walking up from the cwd. */
93
+ workspaceRoot?: string;
94
+ /** YYYY-MM-DD, inclusive. Default: LEDGER_WINDOW_START. */
95
+ since?: string;
96
+ /** YYYY-MM-DD, inclusive. Default: now. */
97
+ until?: string;
98
+ /** Also read THIS machine's Claude Code logs, as this ledger person. */
99
+ self?: string;
100
+ /** Extra `ia hours-export` files, besides everything in <ledgerDir>/inbox/. */
101
+ claudeExports?: string[];
102
+ /** `git fetch --all` each repo first (default true) — without it, others' pushed commits are missing. */
103
+ fetch?: boolean;
104
+ /** Output path. Default: <ledgerDir>/out/ledger-data-<generated>.json. */
105
+ out?: string;
106
+ /** Overwrite the output file if it exists. */
107
+ force?: boolean;
108
+ now?: () => Date;
109
+ env?: NodeJS.ProcessEnv;
110
+ homeDir?: string;
111
+ fetchImpl?: typeof fetch;
112
+ execFileImpl?: ExecFileFn;
113
+ exportClaude?: (options: ClaudeHoursExportOptions) => Promise<ClaudeHoursExportResult>;
114
+ }
115
+ /** Map an email to a ledger person by the config's address fragments. */
116
+ /**
117
+ * One config identity against one email, case-insensitive:
118
+ * - "ian@installagent.com" — that exact address (never "brian@installagent.com");
119
+ * - "jdoe-dev@" — that local part at any domain, also as a GitHub
120
+ * noreply "<id>+jdoe-dev@users.noreply.github.com";
121
+ * - "jdoehacks" — any local part containing it.
122
+ */
123
+ export declare function identityMatches(identity: string, email: string): boolean;
124
+ /**
125
+ * Rebuild the hours ledger's data: every source, the ledger's rules, hours
126
+ * and dates only. Reads git, Linear and Airtable; writes only inside the
127
+ * ledger dir (the Claude store and the output file).
128
+ */
129
+ export declare function buildHoursLedger(options?: HoursLedgerOptions): Promise<HoursLedgerResult>;