@davidbyoung/software-factory 0.0.0-stage → 0.1.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 (141) hide show
  1. package/.claude-plugin/plugin.json +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +135 -2
  4. package/actions/factory-agent/action.yml +218 -0
  5. package/agents/factory-test-reviewer.md +129 -0
  6. package/agents/factory-ticket-readiness.md +107 -0
  7. package/agents/factory-ui-reviewer.md +160 -0
  8. package/bin/factory.js +45 -0
  9. package/bin/launch.js +67 -0
  10. package/dist/board.d.mts +128 -0
  11. package/dist/board.mjs +456 -0
  12. package/dist/build.d.mts +18 -0
  13. package/dist/build.mjs +60 -0
  14. package/dist/cli.d.mts +17 -0
  15. package/dist/cli.mjs +264 -0
  16. package/dist/code-host/github.d.mts +118 -0
  17. package/dist/code-host/github.mjs +419 -0
  18. package/dist/code-host/index.d.mts +9 -0
  19. package/dist/code-host/index.mjs +18 -0
  20. package/dist/code-host/types.d.mts +205 -0
  21. package/dist/code-host/types.mjs +12 -0
  22. package/dist/config.d.mts +166 -0
  23. package/dist/config.mjs +548 -0
  24. package/dist/deps.d.mts +32 -0
  25. package/dist/deps.mjs +126 -0
  26. package/dist/doctor.d.mts +34 -0
  27. package/dist/doctor.mjs +188 -0
  28. package/dist/guard-commit.d.mts +41 -0
  29. package/dist/guard-commit.mjs +205 -0
  30. package/dist/guard-permission.d.mts +15 -0
  31. package/dist/guard-permission.mjs +52 -0
  32. package/dist/guard-ticket-text.d.mts +27 -0
  33. package/dist/guard-ticket-text.mjs +288 -0
  34. package/dist/guard.d.mts +4 -0
  35. package/dist/guard.mjs +37 -0
  36. package/dist/init.d.mts +58 -0
  37. package/dist/init.mjs +556 -0
  38. package/dist/lib/clock.d.mts +14 -0
  39. package/dist/lib/clock.mjs +36 -0
  40. package/dist/lib/gh.d.mts +28 -0
  41. package/dist/lib/gh.mjs +92 -0
  42. package/dist/lib/glob.d.mts +2 -0
  43. package/dist/lib/glob.mjs +41 -0
  44. package/dist/lib/pricing.d.mts +25 -0
  45. package/dist/lib/pricing.mjs +77 -0
  46. package/dist/lib/usage.d.mts +34 -0
  47. package/dist/lib/usage.mjs +128 -0
  48. package/dist/lib/work-status.d.mts +251 -0
  49. package/dist/lib/work-status.mjs +510 -0
  50. package/dist/merge-policy.d.mts +66 -0
  51. package/dist/merge-policy.mjs +146 -0
  52. package/dist/parts.d.mts +39 -0
  53. package/dist/parts.mjs +138 -0
  54. package/dist/poller.d.mts +61 -0
  55. package/dist/poller.mjs +247 -0
  56. package/dist/pr-watch.d.mts +45 -0
  57. package/dist/pr-watch.mjs +244 -0
  58. package/dist/pr.d.mts +65 -0
  59. package/dist/pr.mjs +571 -0
  60. package/dist/review-cost.d.mts +18 -0
  61. package/dist/review-cost.mjs +95 -0
  62. package/dist/review-tools.d.mts +5 -0
  63. package/dist/review-tools.mjs +46 -0
  64. package/dist/review-verdict.d.mts +50 -0
  65. package/dist/review-verdict.mjs +171 -0
  66. package/dist/reviewers.d.mts +54 -0
  67. package/dist/reviewers.mjs +312 -0
  68. package/dist/runner/github-actions.d.mts +12 -0
  69. package/dist/runner/github-actions.mjs +97 -0
  70. package/dist/runner/index.d.mts +9 -0
  71. package/dist/runner/index.mjs +22 -0
  72. package/dist/runner/types.d.mts +60 -0
  73. package/dist/runner/types.mjs +7 -0
  74. package/dist/session-start.d.mts +20 -0
  75. package/dist/session-start.mjs +115 -0
  76. package/dist/site/capture.d.mts +44 -0
  77. package/dist/site/capture.mjs +114 -0
  78. package/dist/site/measure.d.mts +83 -0
  79. package/dist/site/measure.mjs +225 -0
  80. package/dist/site/pages.d.mts +10 -0
  81. package/dist/site/pages.mjs +71 -0
  82. package/dist/site/pixels.d.mts +47 -0
  83. package/dist/site/pixels.mjs +157 -0
  84. package/dist/site/servers.d.mts +47 -0
  85. package/dist/site/servers.mjs +141 -0
  86. package/dist/site.d.mts +60 -0
  87. package/dist/site.mjs +341 -0
  88. package/dist/status.d.mts +100 -0
  89. package/dist/status.mjs +514 -0
  90. package/dist/sync.d.mts +59 -0
  91. package/dist/sync.mjs +292 -0
  92. package/dist/ticket.d.mts +61 -0
  93. package/dist/ticket.mjs +562 -0
  94. package/dist/tickets/github.d.mts +128 -0
  95. package/dist/tickets/github.mjs +491 -0
  96. package/dist/tickets/index.d.mts +15 -0
  97. package/dist/tickets/index.mjs +27 -0
  98. package/dist/tickets/transport.d.mts +42 -0
  99. package/dist/tickets/transport.mjs +158 -0
  100. package/dist/tickets/types.d.mts +191 -0
  101. package/dist/tickets/types.mjs +76 -0
  102. package/docs/builds.md +227 -0
  103. package/docs/cli.md +221 -0
  104. package/docs/configuration.md +809 -0
  105. package/docs/design.md +106 -0
  106. package/docs/developing.md +400 -0
  107. package/docs/existing-repo.md +138 -0
  108. package/docs/github/reference.md +288 -0
  109. package/docs/github/setup.md +312 -0
  110. package/docs/glossary.md +106 -0
  111. package/docs/limitations.md +115 -0
  112. package/docs/plugins.md +192 -0
  113. package/docs/quick-start.md +222 -0
  114. package/docs/removing.md +76 -0
  115. package/docs/skills.md +270 -0
  116. package/docs/updating.md +108 -0
  117. package/docs/workflow.md +195 -0
  118. package/package.json +67 -4
  119. package/poller.Dockerfile +21 -0
  120. package/review.md +170 -0
  121. package/rules.md +313 -0
  122. package/settings.schema.json +411 -0
  123. package/skills/factory-address-review/SKILL.md +547 -0
  124. package/skills/factory-address-review/patch-coverage.py +68 -0
  125. package/skills/factory-build/SKILL.md +412 -0
  126. package/skills/factory-deps/SKILL.md +185 -0
  127. package/skills/factory-design/SKILL.md +159 -0
  128. package/skills/factory-diagnose/SKILL.md +93 -0
  129. package/skills/factory-mutate/SKILL.md +76 -0
  130. package/skills/factory-refine/SKILL.md +417 -0
  131. package/skills/factory-resolve-conflicts/SKILL.md +235 -0
  132. package/workflows/factory-board-sync.yml +91 -0
  133. package/workflows/factory-build.yml +72 -0
  134. package/workflows/factory-check.yml +37 -0
  135. package/workflows/factory-claude-review.yml +133 -0
  136. package/workflows/factory-conflicts.yml +69 -0
  137. package/workflows/factory-deps-auto-merge.yml +43 -0
  138. package/workflows/factory-deps.yml +59 -0
  139. package/workflows/factory-merge-policy.yml +121 -0
  140. package/workflows/factory-review-verdict.yml +54 -0
  141. package/workflows/factory-review.yml +75 -0
@@ -0,0 +1,92 @@
1
+ // How the session scripts reach GitHub. Every call goes through a runner that
2
+ // can be swapped in tests, and a failed call rejects, so a failed read is
3
+ // never mistaken for an empty list.
4
+ import { execFile } from "node:child_process";
5
+ /** What GitHub said was wrong beyond its one line: the `errors` in the
6
+ * answer the CLI printed, such as why a pull request could not be opened.
7
+ * The CLI's own message for those is only "Validation Failed". */
8
+ export function refusalsIn(stdout) {
9
+ try {
10
+ const { errors } = JSON.parse(stdout);
11
+ if (!Array.isArray(errors))
12
+ return "";
13
+ return errors
14
+ .map((e) => typeof e === "string" ? e : e?.message)
15
+ .filter((m) => typeof m === "string")
16
+ .join("; ");
17
+ }
18
+ catch {
19
+ return "";
20
+ }
21
+ }
22
+ /** A failed call's error: the call, the CLI's own message, and the reasons
23
+ * in the answer it printed. */
24
+ export function failureOf(args, detail, stdout) {
25
+ const said = refusalsIn(stdout);
26
+ return `gh ${args.slice(0, 4).join(" ")}: ${detail.trim()}${said ? `: ${said}` : ""}`;
27
+ }
28
+ export const gh = (args) => new Promise((resolve, reject) => {
29
+ execFile("gh", args, { maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => {
30
+ if (error)
31
+ reject(new Error(failureOf(args, stderr || error.message, stdout)));
32
+ else
33
+ resolve(stdout);
34
+ });
35
+ });
36
+ export const ghIn = (args, input) => new Promise((resolve, reject) => {
37
+ const child = execFile("gh", args, { maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => {
38
+ if (error)
39
+ reject(new Error(failureOf(args, stderr || error.message, stdout)));
40
+ else
41
+ resolve(stdout);
42
+ });
43
+ child.stdin?.end(input);
44
+ });
45
+ export async function ghJson(run, args) {
46
+ return JSON.parse(await run(["api", ...args]));
47
+ }
48
+ /** Every page of a REST list. */
49
+ export async function ghList(run, path) {
50
+ const pages = await ghJson(run, ["--paginate", "--slurp", path]);
51
+ return pages.flat();
52
+ }
53
+ export async function graphql(run, query, variables = {}) {
54
+ const args = ["graphql", "-f", `query=${query}`];
55
+ for (const [name, value] of Object.entries(variables)) {
56
+ if (value === null)
57
+ continue;
58
+ args.push(typeof value === "string" ? "-f" : "-F", `${name}=${value}`);
59
+ }
60
+ const result = await ghJson(run, args);
61
+ if (result.errors?.length) {
62
+ throw new Error(result.errors.map((e) => e.message).join("; "));
63
+ }
64
+ return result;
65
+ }
66
+ /** Who this session is, for its marker comments. A session in one of the
67
+ * runner's runs goes by the run: its ID, its page, and the account that
68
+ * started it. A local session run in the desktop app goes by the app's
69
+ * `local_…` ID, which its links need; one run in a terminal has only its
70
+ * own. `unknown` when the environment does not say. */
71
+ export function sessionIdentity(env, runner) {
72
+ const run = runner.thisRun(env);
73
+ if (run)
74
+ return {
75
+ where: "actions",
76
+ id: run.id,
77
+ ...(run.page ? { link: run.page } : {}),
78
+ ...(run.startedBy ? { actor: run.startedBy } : {}),
79
+ };
80
+ const app = env.CLAUDE_CODE_HOST_SESSION_ID ?? "";
81
+ if (appSessionLink(app))
82
+ return { where: "local", id: app };
83
+ const id = env.CLAUDE_CODE_SESSION_ID?.slice(0, 8);
84
+ return { where: "local", id: id || "unknown" };
85
+ }
86
+ /** The link that opens a session in the desktop app; null for an ID the app
87
+ * does not know. */
88
+ export function appSessionLink(id) {
89
+ return /^local_[A-Za-z0-9-]{1,64}$/.test(id)
90
+ ? `claude://claude.ai/epitaxy/${id}`
91
+ : null;
92
+ }
@@ -0,0 +1,2 @@
1
+ export declare function matchesGlob(path: string, pattern: string): boolean;
2
+ export declare const matchesAny: (path: string, patterns: readonly string[]) => boolean;
@@ -0,0 +1,41 @@
1
+ // Glob patterns as the factory's settings use them: `*` matches within one
2
+ // folder, `**` across folders including none, both match names that start
3
+ // with a dot, and a pattern with no wildcard matches that one path from the
4
+ // root. Node's own `path.matchesGlob` skips dot names, so this is small and
5
+ // its own. It prints nothing, since the merge-policy workflow parses standard output.
6
+ const cache = new Map();
7
+ function toRegExp(pattern) {
8
+ let source = "";
9
+ for (let i = 0; i < pattern.length; i++) {
10
+ const c = pattern[i];
11
+ if (c === "*" && pattern[i + 1] === "*") {
12
+ const atStart = i === 0 || pattern[i - 1] === "/";
13
+ const slashAfter = pattern[i + 2] === "/";
14
+ if (atStart && slashAfter) {
15
+ // `**/` is any number of folders, including none.
16
+ source += "(?:[^/]*/)*";
17
+ i += 2;
18
+ }
19
+ else {
20
+ source += ".*";
21
+ i += 1;
22
+ }
23
+ }
24
+ else if (c === "*")
25
+ source += "[^/]*";
26
+ else if (c === "?")
27
+ source += "[^/]";
28
+ else
29
+ source += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
30
+ }
31
+ return new RegExp(`^${source}$`);
32
+ }
33
+ export function matchesGlob(path, pattern) {
34
+ let re = cache.get(pattern);
35
+ if (!re) {
36
+ re = toRegExp(pattern);
37
+ cache.set(pattern, re);
38
+ }
39
+ return re.test(path);
40
+ }
41
+ export const matchesAny = (path, patterns) => patterns.some((p) => matchesGlob(path, p));
@@ -0,0 +1,25 @@
1
+ /** One request's tokens, by how they are billed. */
2
+ export type Tokens = {
3
+ input: number;
4
+ cacheWrite5m: number;
5
+ cacheWrite1h: number;
6
+ cacheRead: number;
7
+ output: number;
8
+ };
9
+ type Rates = Tokens;
10
+ export declare const PRICES: Record<string, Rates | {
11
+ short: Rates;
12
+ long: Rates;
13
+ }>;
14
+ /** Subscription dollars per list-price dollar. An estimate from one week:
15
+ * $276.32 of list price used 35% of the Max plan's weekly allowance
16
+ * (2026-11-12), and a week is 12/52 of the $100 monthly fee. No script can
17
+ * read the allowance, so this is recalibrated by hand, and a change to it
18
+ * reprices every card on the board at the next sync. */
19
+ export declare const SUBSCRIPTION_RATE = 0.03;
20
+ /** A list price as its share of the subscription, in dollars. */
21
+ export declare const subscriptionDollars: (listPrice: number) => number;
22
+ export declare const totalTokens: (t: Tokens) => number;
23
+ /** One request's list price in dollars, or null for a model with no price. */
24
+ export declare function requestPrice(model: string, t: Tokens): number | null;
25
+ export {};
@@ -0,0 +1,77 @@
1
+ // What the same tokens would cost on the Claude API, at list price, and the
2
+ // share of the owner's subscription they used. The owner pays a flat fee, so
3
+ // the list price is a measure of tokens, not a charge. Node built-ins only:
4
+ // the hooks run it before npm ci.
5
+ //
6
+ // Prices per million tokens, from
7
+ // https://platform.claude.com/docs/en/about-claude/pricing (read 2026-11-11).
8
+ /** Haiku 5.5 bills a request whose prompt is over this many tokens at its
9
+ * higher rates. */
10
+ const HAIKU_LONG_PROMPT = 100_000;
11
+ export const PRICES = {
12
+ "claude-fable-5-2": {
13
+ input: 8,
14
+ cacheWrite5m: 10,
15
+ cacheWrite1h: 16,
16
+ cacheRead: 0.2,
17
+ output: 40,
18
+ },
19
+ "claude-opus-5-5": {
20
+ input: 4,
21
+ cacheWrite5m: 5,
22
+ cacheWrite1h: 8,
23
+ cacheRead: 0.2,
24
+ output: 20,
25
+ },
26
+ "claude-sonnet-5-5": {
27
+ input: 2,
28
+ cacheWrite5m: 2.5,
29
+ cacheWrite1h: 4,
30
+ cacheRead: 0.1,
31
+ output: 10,
32
+ },
33
+ "claude-haiku-5-5": {
34
+ short: {
35
+ input: 0.1,
36
+ cacheWrite5m: 0.125,
37
+ cacheWrite1h: 0.2,
38
+ cacheRead: 0.01,
39
+ output: 0.5,
40
+ },
41
+ long: {
42
+ input: 0.5,
43
+ cacheWrite5m: 0.625,
44
+ cacheWrite1h: 1,
45
+ cacheRead: 0.05,
46
+ output: 2.5,
47
+ },
48
+ },
49
+ };
50
+ /** Subscription dollars per list-price dollar. An estimate from one week:
51
+ * $276.32 of list price used 35% of the Max plan's weekly allowance
52
+ * (2026-11-12), and a week is 12/52 of the $100 monthly fee. No script can
53
+ * read the allowance, so this is recalibrated by hand, and a change to it
54
+ * reprices every card on the board at the next sync. */
55
+ export const SUBSCRIPTION_RATE = 0.03;
56
+ /** A list price as its share of the subscription, in dollars. */
57
+ export const subscriptionDollars = (listPrice) => listPrice * SUBSCRIPTION_RATE;
58
+ export const totalTokens = (t) => t.input + t.cacheWrite5m + t.cacheWrite1h + t.cacheRead + t.output;
59
+ /** The prompt, as the long-prompt rule counts it: everything sent. */
60
+ const promptTokens = (t) => t.input + t.cacheWrite5m + t.cacheWrite1h + t.cacheRead;
61
+ /** One request's list price in dollars, or null for a model with no price. */
62
+ export function requestPrice(model, t) {
63
+ const entry = PRICES[model];
64
+ if (!entry)
65
+ return null;
66
+ const rates = "short" in entry
67
+ ? promptTokens(t) > HAIKU_LONG_PROMPT
68
+ ? entry.long
69
+ : entry.short
70
+ : entry;
71
+ return ((t.input * rates.input +
72
+ t.cacheWrite5m * rates.cacheWrite5m +
73
+ t.cacheWrite1h * rates.cacheWrite1h +
74
+ t.cacheRead * rates.cacheRead +
75
+ t.output * rates.output) /
76
+ 1_000_000);
77
+ }
@@ -0,0 +1,34 @@
1
+ export type Spend = {
2
+ /** The priced requests' list price, in dollars. */
3
+ dollars: number;
4
+ /** Requests on a model with a list price. */
5
+ priced: number;
6
+ /** Tokens on models with no list price, by model. */
7
+ unpriced: Map<string, number>;
8
+ };
9
+ export type Measured = {
10
+ ok: true;
11
+ spend: Spend;
12
+ } | {
13
+ ok: false;
14
+ reason: string;
15
+ };
16
+ /** The usage in JSONL transcripts, from `since` on when it is given. Entries
17
+ * that repeat one API response's usage count once, by request ID, and
18
+ * entries with no tokens, such as Claude Code's `<synthetic>` ones, are
19
+ * skipped rather than reported as unpriced. */
20
+ export declare function spendIn(texts: string[], since?: string | null): Spend;
21
+ /** "$3.41" */
22
+ export declare const dollars: (amount: number) => string;
23
+ /** "$0.10 of the subscription ($3.41 at API list prices)" */
24
+ export declare const bothPrices: (listPrice: number) => string;
25
+ /** The cost note's visible line and hidden marker, or the line that says
26
+ * why the cost could not be measured. */
27
+ export declare function costNote(measured: Measured, issue: number, session: string): string;
28
+ /** Where Claude Code keeps its transcripts. */
29
+ export declare function projectsDir(env: Record<string, string | undefined>): string;
30
+ /** The session's own transcript and its subagents', or null when the
31
+ * session's transcript is not there. */
32
+ export declare function sessionTranscripts(root: string, session: string): string[] | null;
33
+ /** What this session spent since `since`, or since it started. */
34
+ export declare function measureSession(root: string, session: string, since: string | null): Measured;
@@ -0,0 +1,128 @@
1
+ // What a Claude Code session spent, read from its transcripts under
2
+ // ~/.claude/projects/. Each assistant entry records the model and the
3
+ // request's token counts. The format is internal to Claude Code, not a
4
+ // documented contract, so a read that finds no usage says so rather than
5
+ // reporting $0. Node built-ins only: the hooks run it before npm ci.
6
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { requestPrice, subscriptionDollars, totalTokens, } from "./pricing.mjs";
10
+ function tokensOf(u) {
11
+ const split = u.cache_creation;
12
+ const write5m = split?.ephemeral_5m_input_tokens;
13
+ const write1h = split?.ephemeral_1h_input_tokens;
14
+ // Without the split, a write is billed as the default 5-minute one.
15
+ const unsplit = write5m === undefined && write1h === undefined
16
+ ? (u.cache_creation_input_tokens ?? 0)
17
+ : 0;
18
+ return {
19
+ input: u.input_tokens ?? 0,
20
+ cacheWrite5m: (write5m ?? 0) + unsplit,
21
+ cacheWrite1h: write1h ?? 0,
22
+ cacheRead: u.cache_read_input_tokens ?? 0,
23
+ output: u.output_tokens ?? 0,
24
+ };
25
+ }
26
+ /** The usage in JSONL transcripts, from `since` on when it is given. Entries
27
+ * that repeat one API response's usage count once, by request ID, and
28
+ * entries with no tokens, such as Claude Code's `<synthetic>` ones, are
29
+ * skipped rather than reported as unpriced. */
30
+ export function spendIn(texts, since = null) {
31
+ const from = since === null ? -Infinity : Date.parse(since);
32
+ const requests = new Map();
33
+ let anonymous = 0;
34
+ for (const text of texts) {
35
+ for (const line of text.split("\n")) {
36
+ if (!line.trim())
37
+ continue;
38
+ let entry;
39
+ try {
40
+ entry = JSON.parse(line);
41
+ }
42
+ catch {
43
+ continue;
44
+ }
45
+ const model = entry.message?.model;
46
+ const usage = entry.message?.usage;
47
+ if (entry.type !== "assistant" || !model || !usage)
48
+ continue;
49
+ if (entry.timestamp && Date.parse(entry.timestamp) < from)
50
+ continue;
51
+ const key = entry.requestId ?? entry.message?.id ?? `anonymous-${anonymous++}`;
52
+ // The last copy of a response carries its final output count.
53
+ requests.set(key, { model, tokens: tokensOf(usage) });
54
+ }
55
+ }
56
+ const spend = { dollars: 0, priced: 0, unpriced: new Map() };
57
+ for (const { model, tokens } of requests.values()) {
58
+ const price = requestPrice(model, tokens);
59
+ if (price === null) {
60
+ const total = totalTokens(tokens);
61
+ if (total > 0)
62
+ spend.unpriced.set(model, (spend.unpriced.get(model) ?? 0) + total);
63
+ }
64
+ else {
65
+ spend.dollars += price;
66
+ spend.priced += 1;
67
+ }
68
+ }
69
+ return spend;
70
+ }
71
+ /** "$3.41" */
72
+ export const dollars = (amount) => `$${amount.toFixed(2)}`;
73
+ /** "$0.10 of the subscription ($3.41 at API list prices)" */
74
+ export const bothPrices = (listPrice) => `${dollars(subscriptionDollars(listPrice))} of the subscription (${dollars(listPrice)} at API list prices)`;
75
+ /** ", plus 120,000 tokens on claude-fable-5-1 with no price" */
76
+ function unpricedClause(spend) {
77
+ if (spend.unpriced.size === 0)
78
+ return "";
79
+ const parts = [...spend.unpriced].map(([model, tokens]) => `${tokens.toLocaleString("en-US")} tokens on ${model} with no price`);
80
+ return `, plus ${parts.join(" and ")}`;
81
+ }
82
+ /** The cost note's visible line and hidden marker, or the line that says
83
+ * why the cost could not be measured. */
84
+ export function costNote(measured, issue, session) {
85
+ const failed = (reason) => `This session's cost could not be measured: ${reason}.`;
86
+ if (!measured.ok)
87
+ return failed(measured.reason);
88
+ const { spend } = measured;
89
+ if (spend.priced === 0)
90
+ return failed(spend.unpriced.size === 0
91
+ ? "its transcript records no usage since its last note"
92
+ : `no token in it is on a model with a list price${unpricedClause(spend).replace(/^, plus/, ":")}`);
93
+ const amount = spend.dollars.toFixed(2);
94
+ return `This session used ${bothPrices(spend.dollars)} on #${issue} since its last note${unpricedClause(spend)}.\n\n<!-- cost: ${amount} session=${session} -->`;
95
+ }
96
+ /** Where Claude Code keeps its transcripts. */
97
+ export function projectsDir(env) {
98
+ return join(env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), "projects");
99
+ }
100
+ /** The session's own transcript and its subagents', or null when the
101
+ * session's transcript is not there. */
102
+ export function sessionTranscripts(root, session) {
103
+ if (!existsSync(root))
104
+ return null;
105
+ for (const project of readdirSync(root)) {
106
+ const main = join(root, project, `${session}.jsonl`);
107
+ if (!existsSync(main))
108
+ continue;
109
+ const subagents = join(root, project, session, "subagents");
110
+ const extra = existsSync(subagents)
111
+ ? readdirSync(subagents)
112
+ .filter((name) => name.endsWith(".jsonl"))
113
+ .map((name) => join(subagents, name))
114
+ : [];
115
+ return [main, ...extra];
116
+ }
117
+ return null;
118
+ }
119
+ /** What this session spent since `since`, or since it started. */
120
+ export function measureSession(root, session, since) {
121
+ if (!session)
122
+ return { ok: false, reason: "the session has no ID" };
123
+ const paths = sessionTranscripts(root, session);
124
+ if (!paths)
125
+ return { ok: false, reason: `no transcript for ${session}` };
126
+ const spend = spendIn(paths.map((p) => readFileSync(p, "utf8")), since);
127
+ return { ok: true, spend };
128
+ }
@@ -0,0 +1,251 @@
1
+ import type { Board, Ticket, TicketComment } from "../tickets/types.mts";
2
+ export type { Board, BoardField, BoardItem } from "../tickets/types.mts";
3
+ export declare const AGENT_MARK = "<!-- agent -->";
4
+ export declare const STATUSES: readonly ["Backlog", "In refinement", "Ready", "In progress", "In review", "Done"];
5
+ export type Status = (typeof STATUSES)[number];
6
+ /** The six states a ticket moves through, by the key a repository's
7
+ * settings use for each. Inside the code a state stays one of `Status`; a
8
+ * board's own column names are applied only where the board is read and
9
+ * where it is written. */
10
+ export declare const STATE_KEYS: {
11
+ readonly backlog: "Backlog";
12
+ readonly refining: "In refinement";
13
+ readonly ready: "Ready";
14
+ readonly building: "In progress";
15
+ readonly review: "In review";
16
+ readonly done: "Done";
17
+ };
18
+ export type StateKey = keyof typeof STATE_KEYS;
19
+ /** The column each state has on the board, or null for a board with none. */
20
+ export type Columns = Record<Status, string | null>;
21
+ /** The factory's own board: every state has the column of its own name. */
22
+ export declare const DEFAULT_COLUMNS: Columns;
23
+ /** A name matches whatever its capitals and the spaces around it. */
24
+ export declare const sameName: (a: string, b: string) => boolean;
25
+ /** The column a ticket in `status` shows in: its own, or else the nearest
26
+ * earlier state's. Nothing but an approved ticket shows in the Ready
27
+ * column, so a state with no column passes over it. */
28
+ export declare function columnFor(status: Status, columns: Columns): string;
29
+ /** The state whose column is named `name`, or null when none is. */
30
+ export declare function statusOfColumn(name: string, columns: Columns): Status | null;
31
+ export type RunsIn = "Local" | "Actions" | "";
32
+ /** Where a session runs: on a person's machine, or in a GitHub Actions run. */
33
+ export type SessionKind = "local" | "actions";
34
+ /** Where a marker says its session ran. `cloud` is only read, from comments
35
+ * posted before unattended runs moved to GitHub Actions; nothing writes it. */
36
+ export type MarkedWhere = SessionKind | "cloud";
37
+ export type Marker = {
38
+ kind: "refining";
39
+ where: MarkedWhere;
40
+ id: string;
41
+ } | {
42
+ kind: "waiting";
43
+ } | {
44
+ kind: "refined";
45
+ } | {
46
+ kind: "started";
47
+ where: MarkedWhere;
48
+ marker: string;
49
+ } | {
50
+ kind: "claim";
51
+ where: MarkedWhere;
52
+ id: string;
53
+ } | {
54
+ kind: "released";
55
+ } | {
56
+ kind: "cleared";
57
+ } | {
58
+ kind: "partial";
59
+ };
60
+ export type IssueComment = TicketComment;
61
+ /** A comment carrying a marker, in the order the rules read them. */
62
+ export type Marked = IssueComment & {
63
+ marker: Marker;
64
+ };
65
+ /** The markers in one comment: each on a line of its own, outside a fenced
66
+ * code block, in a comment that also carries the agent mark. */
67
+ export declare function parseMarkers(body: string): Marker[];
68
+ /** The account the CI review's summary is posted from. */
69
+ export declare const CI_BOT = "github-actions[bot]";
70
+ /** Whether a body already carries a cost marker, read as `parseCosts` reads
71
+ * one: on a line of its own, outside a fenced code block. A marker quoted in
72
+ * prose does not count. */
73
+ export declare function hasCostMarker(body: string): boolean;
74
+ /** The cost markers in one comment, read as markers are: each on a line of
75
+ * its own, outside a fenced code block. Only the owner's account, which the
76
+ * agents post as, and the CI review's bot count; the owner's comments count
77
+ * only with the agent mark. */
78
+ export declare function parseCosts(comment: IssueComment, owner: string): number[];
79
+ /** Whether a pull request's body says it builds this issue, as "Closes #N"
80
+ * or "Part of #N". */
81
+ export declare function buildsIssue(body: string, number: number): boolean;
82
+ /** The issue's Cost: every cost marker on it and on each pull request, open,
83
+ * merged, or closed, that builds it, to the cent. Null when there are none. */
84
+ export declare function issueCost(issue: Issue, pulls: PullRequest[], owner: string): number | null;
85
+ export declare const REVIEWER_RUNS_MARK = "<!-- reviewer-runs session=";
86
+ export type RunResult = "running" | "passed" | "failed" | "no verdict";
87
+ export type ReviewerRun = {
88
+ /** The subagent's ID, which ties a finish to its start. */
89
+ id: string;
90
+ reviewer: string;
91
+ model: string;
92
+ start: string;
93
+ end?: string;
94
+ result: RunResult;
95
+ findings?: number;
96
+ cost?: number;
97
+ };
98
+ export declare function runLine(run: ReviewerRun): string;
99
+ /** The runs in a reviewer-runs comment the agents posted. */
100
+ export declare function parseRuns(comment: IssueComment): ReviewerRun[];
101
+ /** How long a run may say "running" before it reads as one that never
102
+ * recorded its finish. */
103
+ export declare const STUCK_AFTER_MS: number;
104
+ export declare const isStuck: (run: ReviewerRun, now: Date) => boolean;
105
+ export declare function markedComments(comments: IssueComment[]): Marked[];
106
+ export type WorkState = {
107
+ /** The claim that holds the issue now. */
108
+ live: Marked | null;
109
+ /** The newest claim that was ever live, for In review and Done. */
110
+ lastLive: Marked | null;
111
+ /** A start the poller posted that no claim, release, clear, or refinement
112
+ * start has followed. */
113
+ start: Marked | null;
114
+ };
115
+ /** A claim is live when it was posted while no other claim was, and no
116
+ * release or clear has followed. A claim posted while another was live never
117
+ * counts, so a losing run that crashes before deleting it blocks nothing. */
118
+ export declare function workState(comments: IssueComment[]): WorkState;
119
+ /** A card's state, read through the board's columns. "Unmapped" is a column
120
+ * no state names, which the factory leaves alone. */
121
+ export type BoardCard = {
122
+ status: string | null;
123
+ updatedAt: string | null;
124
+ };
125
+ export type PullRequest = {
126
+ number: number;
127
+ createdAt: string;
128
+ body: string;
129
+ /** Issue numbers GitHub links as closed by this pull request. */
130
+ closes: number[];
131
+ isDraft: boolean;
132
+ checks: string | null;
133
+ openThreads: number;
134
+ author: string;
135
+ /** Read for the cost markers on it. */
136
+ comments?: IssueComment[];
137
+ };
138
+ /** A ticket as the rules read it: its body is not needed. */
139
+ export type Issue = Omit<Ticket, "body" | "card"> & {
140
+ body?: string;
141
+ };
142
+ export type Derived = {
143
+ status: Status;
144
+ session: string;
145
+ runsIn: RunsIn;
146
+ /** When the issue entered this Status, or null when nothing records it. */
147
+ since: string | null;
148
+ /** Open pull requests that put the issue In review. */
149
+ pulls: number[];
150
+ };
151
+ /** Whether a pull request's body says it builds part of the follow-ups
152
+ * issue, as "Part of #N". A plain mention, such as a build linking the issue
153
+ * it added a line to, does not count. */
154
+ export declare function buildsPartOf(body: string, number: number): boolean;
155
+ /** The pull requests that put this issue In review. */
156
+ export declare function reviewingPulls(issue: Issue, pulls: PullRequest[]): PullRequest[];
157
+ /** The page of an Actions run, from the board's or the view's session: the
158
+ * run's ID, which `runPage` turns into its page. Null for any other
159
+ * session. */
160
+ export declare function actionsRunLink(derived: Pick<Derived, "session" | "runsIn">, runPage: (id: string) => string): string | null;
161
+ /** An issue's Status is the first rule that applies: Done, In review,
162
+ * In progress, Ready, In refinement, Backlog. */
163
+ export declare function derive(issue: Issue, card: BoardCard | null, pulls: PullRequest[], columns?: Columns): Derived;
164
+ /** Over 24 hours In progress or In refinement with a session. */
165
+ export declare function isStale(derived: Derived, now: Date): boolean;
166
+ /** Ready for over 5 minutes with no start: the poller should have fired. */
167
+ export declare function isNotStarted(derived: Derived, openBlockers: number[], now: Date): boolean;
168
+ /** A claim or start over 24 hours old with no pull request, which the
169
+ * nightly sync clears. Null when there is nothing to clear. */
170
+ export declare function toClear(issue: Issue, pulls: PullRequest[], now: Date): {
171
+ kind: "claim" | "start";
172
+ since: string;
173
+ } | null;
174
+ /** "2026-11-09 14:05 UTC" */
175
+ export declare function utc(iso: string): string;
176
+ export type Identity = {
177
+ where: SessionKind;
178
+ id: string;
179
+ link?: string;
180
+ /** Who started an Actions run. */
181
+ actor?: string;
182
+ };
183
+ /** The comments sessions, the poller, and the sync post: one visible
184
+ * sentence, then its marker line and the agent mark. */
185
+ export type CommentKind = {
186
+ kind: "refining";
187
+ who: Identity;
188
+ } | {
189
+ kind: "waiting";
190
+ cost?: string;
191
+ } | {
192
+ kind: "refined";
193
+ issue: number;
194
+ before?: string;
195
+ cost?: string;
196
+ } | {
197
+ kind: "started";
198
+ marker: string;
199
+ } | {
200
+ kind: "dispatch-failed";
201
+ issue: number;
202
+ status: string;
203
+ reason: string;
204
+ } | {
205
+ kind: "claim";
206
+ who: Identity;
207
+ } | {
208
+ kind: "stopped";
209
+ where: SessionKind;
210
+ issue: number;
211
+ reason: string;
212
+ cost?: string;
213
+ } | {
214
+ kind: "cost";
215
+ cost: string;
216
+ } | {
217
+ kind: "ended";
218
+ issue: number;
219
+ } | {
220
+ kind: "cleared-claim";
221
+ issue: number;
222
+ since: string;
223
+ } | {
224
+ kind: "cleared-start";
225
+ issue: number;
226
+ since: string;
227
+ } | {
228
+ kind: "follow-ups-merged";
229
+ pull: number;
230
+ } | {
231
+ kind: "pull-closed";
232
+ issue: number;
233
+ pull: number;
234
+ };
235
+ export declare function commentBody(c: CommentKind, columns?: Columns): string;
236
+ export type RepoSnapshot = {
237
+ issues: Issue[];
238
+ /** The open pull requests: each puts the issues it builds In review. */
239
+ pulls: PullRequest[];
240
+ /** Closed and merged pull requests that mentioned an issue, read only
241
+ * for their cost markers. */
242
+ donePulls?: PullRequest[];
243
+ };
244
+ /** What the views and the sync work from: the open tickets and those
245
+ * closed in the last day, from what "Read everything at once" returned, and
246
+ * the pull requests. */
247
+ export declare function toSnapshot(tickets: Issue[], pulls: PullRequest[], now: Date, donePulls?: PullRequest[]): RepoSnapshot;
248
+ /** A ticket's card, its column read as the state that column shows. A
249
+ * card with no Status has none; one in a column no state names is
250
+ * "Unmapped". */
251
+ export declare const cardOf: (board: Board, number: number, columns?: Columns) => BoardCard | null;