@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
@@ -7,11 +7,18 @@ const PROJECT_TEAMS_QUERY = `
7
7
  }
8
8
  }
9
9
  `;
10
+ const LABELS_QUERY = `
11
+ query IssueLabelsByName($names: [String!]!) {
12
+ issueLabels(filter: { name: { in: $names } }, first: 50) {
13
+ nodes { id name }
14
+ }
15
+ }
16
+ `;
10
17
  const CREATE_ISSUE_MUTATION = `
11
18
  mutation CreateIssue($input: IssueCreateInput!) {
12
19
  issueCreate(input: $input) {
13
20
  success
14
- issue { identifier title url }
21
+ issue { id identifier title url }
15
22
  }
16
23
  }
17
24
  `;
@@ -36,11 +43,31 @@ export async function clientLinearCreateIssue(slug, input, options = {}) {
36
43
  if (!teamId) {
37
44
  throw new Error(`Linear project "${project.name}" has no team — can't create an issue without one.`);
38
45
  }
46
+ const labelIds = await resolveLabelIds(fetchImpl, linearToken, input.labelNames ?? []);
39
47
  const created = await linearRequest(fetchImpl, linearToken, CREATE_ISSUE_MUTATION, {
40
- input: { teamId, projectId: project.id, title, ...(description ? { description } : {}) },
48
+ input: {
49
+ teamId,
50
+ projectId: project.id,
51
+ title,
52
+ ...(description ? { description } : {}),
53
+ ...(labelIds.length ? { labelIds } : {}),
54
+ },
41
55
  });
42
56
  if (!created.issueCreate.success || !created.issueCreate.issue) {
43
57
  throw new Error(`Linear did not create the issue in "${project.name}" (success=false).`);
44
58
  }
45
- return { project, issue: created.issueCreate.issue };
59
+ return { project, teamId, issue: created.issueCreate.issue };
60
+ }
61
+ /** Label names → ids. Empty in, empty out (no request). Any unresolved name throws. */
62
+ async function resolveLabelIds(fetchImpl, token, names) {
63
+ const wanted = names.map((n) => n.trim()).filter(Boolean);
64
+ if (wanted.length === 0)
65
+ return [];
66
+ const result = await linearRequest(fetchImpl, token, LABELS_QUERY, { names: wanted });
67
+ const byName = new Map(result.issueLabels.nodes.map((n) => [n.name.toLowerCase(), n.id]));
68
+ const missing = wanted.filter((n) => !byName.has(n.toLowerCase()));
69
+ if (missing.length) {
70
+ throw new Error(`Linear has no label named ${missing.map((m) => `"${m}"`).join(", ")}.`);
71
+ }
72
+ return wanted.map((n) => byName.get(n.toLowerCase()));
46
73
  }
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
@@ -1,4 +1,5 @@
1
1
  import { N8N_API_KEY_ENV, N8N_API_URL_ENV } from "./agent-templates.js";
2
+ import { HOURS_EXPORT_SECRET_ENV } from "./claude-hours.js";
2
3
  import { GITHUB_API_TOKEN_ENV } from "./client-build.js";
3
4
  import { AIRTABLE_API_TOKEN_ENV, GOOGLE_SERVICE_ACCOUNT_KEY_ENV } from "./client-drive.js";
4
5
  import { LINEAR_CLIENT_TEAM_ID_ENV } from "./client-intake.js";
@@ -13,6 +14,10 @@ export const INFRA_VAULT = "team-admin";
13
14
  const OP_DEFAULT_FIELD = "value";
14
15
  /** Only `ia secrets mint gemini-api-key` reads it, so it has no owning module. */
15
16
  export const GEMINI_API_KEY_ENV = "GEMINI_API_KEY";
17
+ /** Read by apps/slack-agent (relay.ts, feedback.ts) — an app, so it has no SDK module. */
18
+ export const SLACK_RELAY_SECRET_ENV = "SLACK_RELAY_SECRET";
19
+ /** Read by nothing; registered so every team-techs item is accounted for. */
20
+ export const N8N_OAUTH_CALLBACK_URL_ENV = "N8N_OAUTH_CALLBACK_URL";
16
21
  const SECTION_DRIVERS = "ia CLI: technician daily drivers";
17
22
  const SECTION_INFRA = "shared infra (n8n workflows, team-infra scripts)";
18
23
  const SECTION_PORTAL = "portal / team-web local dev (prod values live in Vercel, never here)";
@@ -104,7 +109,7 @@ export const ENV_VARS = [
104
109
  source: "vault",
105
110
  doctor: true,
106
111
  vault: DEFAULT_TECH_VAULT,
107
- neededBy: "ia portal",
112
+ neededBy: "ia portal, ia triage",
108
113
  howToGet: `the portal admin API bearer — ${inTechVault}`,
109
114
  section: SECTION_DRIVERS,
110
115
  comment: "portal.installagent.com admin API bearer — filled by `ia env fill`",
@@ -126,7 +131,7 @@ export const ENV_VARS = [
126
131
  source: "vault",
127
132
  doctor: true,
128
133
  vault: DEFAULT_TECH_VAULT,
129
- neededBy: "ia client-drive",
134
+ neededBy: "ia client-drive, ia triage",
130
135
  howToGet: `the Drive service-account key JSON — ${inTechVault}`,
131
136
  section: SECTION_DRIVERS,
132
137
  comment: "the Drive service-account key JSON, single line — filled by `ia env fill`",
@@ -164,6 +169,17 @@ export const ENV_VARS = [
164
169
  section: SECTION_DRIVERS,
165
170
  comment: "n8n → Settings → API — filled by `ia env fill`",
166
171
  },
172
+ {
173
+ name: HOURS_EXPORT_SECRET_ENV,
174
+ tier: "optional",
175
+ source: "vault",
176
+ doctor: true,
177
+ vault: DEFAULT_TECH_VAULT,
178
+ neededBy: "ia hours-export",
179
+ howToGet: `the hours-export intake secret — ${inTechVault}`,
180
+ section: SECTION_DRIVERS,
181
+ comment: "lets `ia hours-export` send your file to the ledger keeper — filled by `ia env fill`",
182
+ },
167
183
  {
168
184
  name: GEMINI_API_KEY_ENV,
169
185
  tier: "optional",
@@ -174,6 +190,37 @@ export const ENV_VARS = [
174
190
  howToGet: inTechVault,
175
191
  section: SECTION_DRIVERS,
176
192
  },
193
+ {
194
+ // Kept in team-techs by the account owner's choice (2026-09-24), under its
195
+ // header name. No `ia` command reads it; the deployed box gets its own copy
196
+ // from SSM (team-infra/agent-hosting).
197
+ name: SLACK_RELAY_SECRET_ENV,
198
+ tier: "optional",
199
+ source: "vault",
200
+ doctor: false,
201
+ vault: DEFAULT_TECH_VAULT,
202
+ item: "x-relay-secret",
203
+ neededBy: "slack-agent (local runs) and the n8n relay / feedback webhooks",
204
+ howToGet: `the Agent Zero relay secret, sent as the x-relay-secret header — ${inTechVault}`,
205
+ section: SECTION_INFRA,
206
+ comment: "Agent Zero relay secret (x-relay-secret header) — filled by `ia env fill`",
207
+ },
208
+ {
209
+ // A public URL, not a secret: the redirect URL n8n shows when an OAuth
210
+ // credential is created, kept in team-techs for pasting into provider consoles.
211
+ name: N8N_OAUTH_CALLBACK_URL_ENV,
212
+ tier: "optional",
213
+ source: "vault",
214
+ doctor: false,
215
+ vault: DEFAULT_TECH_VAULT,
216
+ item: "n8n Install Agent Callback URL",
217
+ // A Secure Note: the URL is the note text, not a `value` field.
218
+ field: "notesPlain",
219
+ neededBy: "setting up OAuth credentials in n8n",
220
+ howToGet: `the n8n OAuth redirect URL — ${inTechVault}`,
221
+ section: SECTION_INFRA,
222
+ comment: "n8n OAuth redirect URL (paste into a provider's OAuth app) — filled by `ia env fill`",
223
+ },
177
224
  infraVar("AIRTABLE_BASE_ID", "n8n workflows, team-infra scripts"),
178
225
  infraVar("AIRTABLE_CLIENTS_TABLE_ID", "n8n workflows, team-infra scripts"),
179
226
  infraVar("N8N_WEBHOOK_URL", "n8n workflows, team-infra scripts"),
@@ -220,6 +267,11 @@ const TECH_ROLE_VAR_NAMES = new Set([
220
267
  N8N_API_URL_ENV,
221
268
  N8N_API_KEY_ENV,
222
269
  GEMINI_API_KEY_ENV,
270
+ // Every technician's `ia hours-export` sends with it (2026-09-24).
271
+ HOURS_EXPORT_SECRET_ENV,
272
+ // In team-techs by the account owner's choice (2026-09-24); no `ia` command reads them.
273
+ SLACK_RELAY_SECRET_ENV,
274
+ N8N_OAUTH_CALLBACK_URL_ENV,
223
275
  ]);
224
276
  export function envVarRole(spec) {
225
277
  return TECH_ROLE_VAR_NAMES.has(spec.name) ? "tech" : "admin";
package/dist/git.d.ts CHANGED
@@ -14,3 +14,34 @@ export declare const gitClone: CloneFn;
14
14
  export type PullFn = (dir: string) => Promise<void>;
15
15
  export declare const gitPullFfOnly: PullFn;
16
16
  export declare function gitInit(dir: string): Promise<void>;
17
+ /**
18
+ * Injectable fetch function — read-only (`git fetch` never touches the
19
+ * working tree or local branches), so it's always safe to run before a
20
+ * status check.
21
+ */
22
+ export type FetchFn = (dir: string) => Promise<void>;
23
+ export declare const gitFetchAll: FetchFn;
24
+ export interface RepoStatusInfo {
25
+ branch: string | null;
26
+ upstream: string | null;
27
+ /** Local commits not yet on the upstream branch. 0 if no upstream. */
28
+ ahead: number;
29
+ /** Upstream commits not yet merged locally. 0 if no upstream. */
30
+ behind: number;
31
+ /** True if the working tree has staged or unstaged changes to tracked files. */
32
+ dirty: boolean;
33
+ /** Count of untracked files/paths. */
34
+ untracked: number;
35
+ }
36
+ /**
37
+ * Injectable status function — reads `git status --porcelain=v2 --branch`,
38
+ * never mutates anything.
39
+ */
40
+ export type StatusFn = (dir: string) => Promise<RepoStatusInfo>;
41
+ export declare const gitStatus: StatusFn;
42
+ /**
43
+ * Injectable push function — plain `git push` on the current branch
44
+ * (relies on an already-configured upstream). Never force-pushes.
45
+ */
46
+ export type PushFn = (dir: string) => Promise<void>;
47
+ export declare const gitPush: PushFn;
package/dist/git.js CHANGED
@@ -27,3 +27,62 @@ export const gitPullFfOnly = async (dir) => {
27
27
  export async function gitInit(dir) {
28
28
  await execFileAsync("git", ["init"], { cwd: dir });
29
29
  }
30
+ export const gitFetchAll = async (dir) => {
31
+ try {
32
+ await execFileAsync("git", ["fetch", "--all", "--prune"], { cwd: dir });
33
+ }
34
+ catch (error) {
35
+ const detail = error instanceof Error ? error.message : String(error);
36
+ throw new Error(`git fetch failed in ${dir}: ${detail}`);
37
+ }
38
+ };
39
+ export const gitStatus = async (dir) => {
40
+ let stdout;
41
+ try {
42
+ ({ stdout } = await execFileAsync("git", ["status", "--porcelain=v2", "--branch"], {
43
+ cwd: dir,
44
+ }));
45
+ }
46
+ catch (error) {
47
+ const detail = error instanceof Error ? error.message : String(error);
48
+ throw new Error(`git status failed in ${dir}: ${detail}`);
49
+ }
50
+ let branch = null;
51
+ let upstream = null;
52
+ let ahead = 0;
53
+ let behind = 0;
54
+ let dirty = false;
55
+ let untracked = 0;
56
+ for (const line of stdout.split("\n")) {
57
+ if (line.startsWith("# branch.head ")) {
58
+ const head = line.slice("# branch.head ".length).trim();
59
+ branch = head === "(detached)" ? null : head;
60
+ }
61
+ else if (line.startsWith("# branch.upstream ")) {
62
+ upstream = line.slice("# branch.upstream ".length).trim();
63
+ }
64
+ else if (line.startsWith("# branch.ab ")) {
65
+ const match = line.match(/\+(\d+) -(\d+)/);
66
+ if (match) {
67
+ ahead = Number(match[1]);
68
+ behind = Number(match[2]);
69
+ }
70
+ }
71
+ else if (line.startsWith("?")) {
72
+ untracked += 1;
73
+ }
74
+ else if (line.startsWith("1") || line.startsWith("2") || line.startsWith("u")) {
75
+ dirty = true;
76
+ }
77
+ }
78
+ return { branch, upstream, ahead, behind, dirty, untracked };
79
+ };
80
+ export const gitPush = async (dir) => {
81
+ try {
82
+ await execFileAsync("git", ["push"], { cwd: dir });
83
+ }
84
+ catch (error) {
85
+ const detail = error instanceof Error ? error.message : String(error);
86
+ throw new Error(`git push failed in ${dir}: ${detail}`);
87
+ }
88
+ };
@@ -0,0 +1,20 @@
1
+ export declare const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
2
+ /** Thrown when the service-account key is missing, malformed, or rejected by Google. */
3
+ export declare class GoogleServiceAccountAuthError extends Error {
4
+ }
5
+ export declare function buildServiceAccountClaims(clientEmail: string, scope: string, nowMs: number): {
6
+ iss: string;
7
+ scope: string;
8
+ aud: string;
9
+ iat: number;
10
+ exp: number;
11
+ };
12
+ /**
13
+ * Exchange a service-account key for a short-lived access token carrying
14
+ * exactly `scope`. The caller decides the scope — keep it the narrowest that
15
+ * works (`*.readonly` wherever the operation only reads).
16
+ */
17
+ export declare function getServiceAccountAccessToken(serviceAccountKeyRaw: string, scope: string, fetchImpl: typeof fetch, now: () => number): Promise<{
18
+ accessToken: string;
19
+ clientEmail: string;
20
+ }>;
@@ -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
+ }>;