@houserules/payload 0.3.2 → 0.4.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@houserules/payload",
3
- "version": "0.3.2",
3
+ "version": "0.4.1",
4
4
  "description": "houserules: shared payload libraries, copied into .claude/scripts/lib and executed on bare node with zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -71,11 +71,11 @@
71
71
  "hooks"
72
72
  ],
73
73
  "devDependencies": {
74
- "@types/node": "26.6.2",
75
- "publint": "^0.3.24",
76
- "type-fest": "^5.9.0",
74
+ "@types/node": "26.6.3",
75
+ "publint": "^0.3.25",
76
+ "type-fest": "^5.10.0",
77
77
  "typescript": "^6.0.3",
78
- "vitest": "^5.0.1",
78
+ "vitest": "^5.0.4",
79
79
  "wireit": "^0.14.13",
80
80
  "@houserules/test": "0.1.3"
81
81
  },
@@ -9,6 +9,8 @@ export interface RunnerBlock {
9
9
  commandExtensions?: Record<string, string[]>;
10
10
  /** `verify` only: branch the changed-file diff is taken against. */
11
11
  baseBranch?: string;
12
+ /** `verify` only: per-command wall-clock cap in milliseconds. Unset means no cap. */
13
+ timeoutMs?: number;
12
14
  }
13
15
  export interface ConfigTarget {
14
16
  name: string;
@@ -74,6 +76,8 @@ export interface HouseConfig {
74
76
  claudeMd?: {
75
77
  managed?: boolean;
76
78
  };
79
+ /** Which file carries the houserules block. Unset honors the file the repo already has. */
80
+ instructionsFile?: 'CLAUDE.md' | 'AGENTS.md';
77
81
  /** Read by the design plugin's `design.mjs`: the stylesheet Tailwind compiles, repo-root-relative. */
78
82
  design?: {
79
83
  themeEntry?: string;
@@ -4,6 +4,20 @@ export declare const nowIso: () => string;
4
4
  export declare const todayDate: () => string;
5
5
  export declare const encodeBody: (s?: string) => string;
6
6
  export declare const decodeBody: (s: string) => string;
7
+ /**
8
+ * The directory name Claude Code gives a project under `~/.claude/projects/`: the absolute
9
+ * working-directory path with every character outside `A-Z`, `a-z`, and `0-9` replaced by
10
+ * `-`, per https://code.claude.com/docs/en/sessions.md. A name that reaches
11
+ * {@link PROJECT_DIR_NAME_MAX_LENGTH} is cut to that length and followed by a hash the page
12
+ * does not name, so the real directory is the one entry in `projectsDir` that starts with the
13
+ * prefix. Every reader of a project's transcripts, in the payload and in the CLI, derives the
14
+ * name here, so the encoding can never disagree between them.
15
+ *
16
+ * @param projectsDir The directory to list for a capped name. Read only for such a name.
17
+ * @returns The bare prefix when no entry or several entries match, or the directory cannot be
18
+ * read.
19
+ */
20
+ export declare function claudeProjectDir(absolutePath: string, projectsDir?: string): string;
7
21
  /** Splices `--chat <id>` / `--chat=<id>` out of `argv` in place. */
8
22
  export declare function takeChatFlag(argv: string[]): string | null;
9
23
  /** `--chat=none` suppresses provenance. Any other flag wins over detection. */
@@ -46,9 +46,45 @@ function readLastJsonRecord(file) {
46
46
  }
47
47
  }
48
48
  /**
49
- * The active Claude Code session, from `CLAUDE_SESSION_ID` or the freshest transcript tail.
49
+ * The longest project directory name Claude Code writes before it truncates, per
50
+ * https://code.claude.com/docs/en/sessions.md. Past this length Claude Code keeps the first
51
+ * 200 characters and appends a hash of the full path. The page does not name the hash, so
52
+ * {@link claudeProjectDir} finds the real directory by listing the projects directory for the
53
+ * single entry that starts with the 200-character prefix.
54
+ */
55
+ const PROJECT_DIR_NAME_MAX_LENGTH = 200;
56
+ /**
57
+ * The directory name Claude Code gives a project under `~/.claude/projects/`: the absolute
58
+ * working-directory path with every character outside `A-Z`, `a-z`, and `0-9` replaced by
59
+ * `-`, per https://code.claude.com/docs/en/sessions.md. A name that reaches
60
+ * {@link PROJECT_DIR_NAME_MAX_LENGTH} is cut to that length and followed by a hash the page
61
+ * does not name, so the real directory is the one entry in `projectsDir` that starts with the
62
+ * prefix. Every reader of a project's transcripts, in the payload and in the CLI, derives the
63
+ * name here, so the encoding can never disagree between them.
64
+ *
65
+ * @param projectsDir The directory to list for a capped name. Read only for such a name.
66
+ * @returns The bare prefix when no entry or several entries match, or the directory cannot be
67
+ * read.
68
+ */
69
+ export function claudeProjectDir(absolutePath, projectsDir = resolve(homedir(), '.claude/projects')) {
70
+ const encoded = absolutePath.replace(/[^A-Za-z0-9]/g, '-');
71
+ if (encoded.length < PROJECT_DIR_NAME_MAX_LENGTH)
72
+ return encoded;
73
+ const prefix = encoded.slice(0, PROJECT_DIR_NAME_MAX_LENGTH);
74
+ try {
75
+ const matches = readdirSync(projectsDir).filter((name) => name.startsWith(prefix));
76
+ return matches.length === 1 ? (matches[0] ?? prefix) : prefix;
77
+ }
78
+ catch {
79
+ return prefix;
80
+ }
81
+ }
82
+ /**
83
+ * The active Claude Code session. Reads `CLAUDE_SESSION_ID` first as the manual override,
84
+ * then `CLAUDE_CODE_SESSION_ID`, which Claude Code sets in Bash and hook subprocesses, and
85
+ * only then the freshest transcript tail.
50
86
  * Transcripts live at `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl`, where encoded-cwd
51
- * is the absolute repo path with `/` replaced by `-`. mtime alone is not reliable when several
87
+ * is {@link claudeProjectDir} of the repo root. mtime alone is not reliable when several
52
88
  * sessions share one project at once, so this compares the last record's timestamp.
53
89
  *
54
90
  * @returns null in any harness that is not Claude Code, which callers report as `chat: null`.
@@ -56,7 +92,10 @@ function readLastJsonRecord(file) {
56
92
  function detectChatId(repoRoot) {
57
93
  if (process.env.CLAUDE_SESSION_ID)
58
94
  return process.env.CLAUDE_SESSION_ID;
59
- const dir = resolve(homedir(), '.claude/projects', repoRoot.replaceAll('/', '-'));
95
+ if (process.env.CLAUDE_CODE_SESSION_ID) {
96
+ return process.env.CLAUDE_CODE_SESSION_ID;
97
+ }
98
+ const dir = resolve(homedir(), '.claude/projects', claudeProjectDir(repoRoot));
60
99
  if (!existsSync(dir))
61
100
  return null;
62
101
  let entries;
@@ -44,9 +44,10 @@ export declare function serializeIndex(index: LedgerIndex): string;
44
44
  * The index in `raw`, or null when it cannot be trusted.
45
45
  *
46
46
  * **Never throws, for any input.** `ledger-inject.mjs` reads this on every prompt as a
47
- * `UserPromptSubmit` hook, and a hook that throws costs the user their turn. A truncated write, a
48
- * hand-edit, or an index from a future version all return null, and null means "no cache", which
49
- * every caller already has to handle for a fresh clone.
47
+ * `UserPromptSubmit` hook. A hook that throws loses its injected context for that prompt, since the
48
+ * prompt still reaches Claude without it, and a reader of stderr sees a crash where a cache miss was
49
+ * meant. A truncated write, a hand-edit, or an index from a future version all return null, and null
50
+ * means "no cache", which every caller already has to handle for a fresh clone.
50
51
  */
51
52
  export declare function parseIndex(raw: string, kind: LedgerKind): LedgerIndex | null;
52
53
  /**
@@ -55,7 +56,9 @@ export declare function parseIndex(raw: string, kind: LedgerKind): LedgerIndex |
55
56
  * **Never throws, for any state of the disk.** Null covers every failure the same way: no file, an
56
57
  * unreadable file, a truncated write, a hand-edit, a version from the future. Callers already have
57
58
  * to handle null for a fresh clone that has never pulled, so there is no second path to get wrong.
58
- * `ledger-inject.mjs` calls this on every prompt, and a hook that throws costs the user their turn.
59
+ * `ledger-inject.mjs` calls this on every prompt. A hook that throws loses its injected context for
60
+ * that prompt, since the prompt still reaches Claude without it, and stderr shows a crash where a
61
+ * cache miss was meant.
59
62
  *
60
63
  * This index is the other half of the queue-and-index split: the `.jsonl` ledgers hold what has
61
64
  * not reached a board yet, and this index is a projection of the boards so `scope`, `show`, and
@@ -21,9 +21,10 @@ export function serializeIndex(index) {
21
21
  * The index in `raw`, or null when it cannot be trusted.
22
22
  *
23
23
  * **Never throws, for any input.** `ledger-inject.mjs` reads this on every prompt as a
24
- * `UserPromptSubmit` hook, and a hook that throws costs the user their turn. A truncated write, a
25
- * hand-edit, or an index from a future version all return null, and null means "no cache", which
26
- * every caller already has to handle for a fresh clone.
24
+ * `UserPromptSubmit` hook. A hook that throws loses its injected context for that prompt, since the
25
+ * prompt still reaches Claude without it, and a reader of stderr sees a crash where a cache miss was
26
+ * meant. A truncated write, a hand-edit, or an index from a future version all return null, and null
27
+ * means "no cache", which every caller already has to handle for a fresh clone.
27
28
  */
28
29
  export function parseIndex(raw, kind) {
29
30
  let parsed;
@@ -50,7 +51,9 @@ export function parseIndex(raw, kind) {
50
51
  * **Never throws, for any state of the disk.** Null covers every failure the same way: no file, an
51
52
  * unreadable file, a truncated write, a hand-edit, a version from the future. Callers already have
52
53
  * to handle null for a fresh clone that has never pulled, so there is no second path to get wrong.
53
- * `ledger-inject.mjs` calls this on every prompt, and a hook that throws costs the user their turn.
54
+ * `ledger-inject.mjs` calls this on every prompt. A hook that throws loses its injected context for
55
+ * that prompt, since the prompt still reaches Claude without it, and stderr shows a crash where a
56
+ * cache miss was meant.
54
57
  *
55
58
  * This index is the other half of the queue-and-index split: the `.jsonl` ledgers hold what has
56
59
  * not reached a board yet, and this index is a projection of the boards so `scope`, `show`, and
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Tools whose use never writes to the working tree. A turn whose tool uses all fall in this
3
+ * set is a read-only turn, and a Stop hook that exists to react to edits has nothing to do
4
+ * after one. Any tool not named here, including every MCP tool and the agent-dispatching
5
+ * tools, counts as a possible write, so an unknown tool fails safe to running the hook.
6
+ */
7
+ export declare const READ_ONLY_TOOLS: ReadonlySet<string>;
8
+ /** The fields of a transcript record this module reads. Every other record type is skipped. */
9
+ export interface TurnRecord {
10
+ type?: string;
11
+ isMeta?: boolean;
12
+ isCompactSummary?: boolean;
13
+ origin?: {
14
+ kind?: string;
15
+ };
16
+ timestamp?: string;
17
+ message?: {
18
+ content?: unknown;
19
+ };
20
+ }
21
+ /**
22
+ * The name of every tool the assistant used since the last human prompt in `records`, in
23
+ * transcript order. Null when no assistant record follows that prompt. Null is the lag case:
24
+ * the harness writes the transcript asynchronously, so a file with no assistant record since
25
+ * the prompt may not have caught up yet, and a caller must not read it as "no tools used".
26
+ *
27
+ * @param records Transcript records oldest first, as the `.jsonl` file holds them.
28
+ */
29
+ export declare function toolUsesSinceLastPrompt(records: readonly TurnRecord[]): string[] | null;
30
+ /**
31
+ * Whether the turn that just ended may have written to the working tree, judged from the
32
+ * tool uses recorded since the last human prompt in the transcript at `transcriptPath`.
33
+ *
34
+ * `false` means every tool use was in {@link READ_ONLY_TOOLS}, or there were none, so a Stop
35
+ * hook that reacts to edits can exit before spawning anything. `true` means at least one
36
+ * tool use could have written. `undefined` means the question has no answer: no path, an
37
+ * unreadable file, or no assistant record since the prompt, which is how a lagging write
38
+ * looks. A caller treats `undefined` exactly as it behaved before this gate existed.
39
+ */
40
+ export declare function turnTouchedFiles(transcriptPath: string | undefined): boolean | undefined;
41
+ /**
42
+ * When the turn that just ended began, as epoch milliseconds: the `timestamp` of the last
43
+ * human prompt in the transcript at `transcriptPath`. Undefined when there is no path, the
44
+ * file is unreadable, or no prompt carries a parseable timestamp. A lagging transcript can
45
+ * only yield an earlier prompt, which widens the turn rather than narrowing it.
46
+ */
47
+ export declare function turnStartedAt(transcriptPath: string | undefined): number | undefined;
@@ -0,0 +1,146 @@
1
+ import { readFileSync } from 'node:fs';
2
+ /**
3
+ * Tools whose use never writes to the working tree. A turn whose tool uses all fall in this
4
+ * set is a read-only turn, and a Stop hook that exists to react to edits has nothing to do
5
+ * after one. Any tool not named here, including every MCP tool and the agent-dispatching
6
+ * tools, counts as a possible write, so an unknown tool fails safe to running the hook.
7
+ */
8
+ export const READ_ONLY_TOOLS = new Set([
9
+ 'Read',
10
+ 'Grep',
11
+ 'Glob',
12
+ 'LS',
13
+ 'WebFetch',
14
+ 'WebSearch',
15
+ 'TodoWrite',
16
+ 'AskUserQuestion',
17
+ 'Skill',
18
+ 'ToolSearch',
19
+ 'ListAgents',
20
+ 'ListMcpResourcesTool',
21
+ 'ReadMcpResourceTool',
22
+ 'Monitor',
23
+ 'EnterPlanMode',
24
+ 'ExitPlanMode',
25
+ ]);
26
+ /**
27
+ * Whether a `user` record carries a human prompt rather than a tool result. A meta record
28
+ * (a command caveat), a task notification, and a compaction summary are inserted by the
29
+ * harness and continue the turn already running. Stopping at one would hide the tool uses
30
+ * before it, such as the dispatch of the background agent that just reported.
31
+ */
32
+ function isHumanPrompt(record) {
33
+ if (record.type !== 'user' || record.isMeta === true)
34
+ return false;
35
+ if (record.isCompactSummary === true)
36
+ return false;
37
+ if (record.origin?.kind === 'task-notification')
38
+ return false;
39
+ const content = record.message?.content;
40
+ if (typeof content === 'string')
41
+ return true;
42
+ if (!Array.isArray(content))
43
+ return false;
44
+ return !content.some((block) => block?.type === 'tool_result');
45
+ }
46
+ function toolUseNames(record) {
47
+ const content = record.message?.content;
48
+ if (!Array.isArray(content))
49
+ return [];
50
+ const names = [];
51
+ for (const block of content)
52
+ if (block?.type === 'tool_use' && typeof block.name === 'string')
53
+ names.push(block.name);
54
+ return names;
55
+ }
56
+ /**
57
+ * Walks records newest first, collecting tool-use names until the last human prompt.
58
+ * Null when no assistant record was seen before that prompt.
59
+ */
60
+ function collectNewestFirst(records) {
61
+ const names = [];
62
+ let sawAssistant = false;
63
+ for (const record of records) {
64
+ if (isHumanPrompt(record))
65
+ break;
66
+ if (record.type !== 'assistant')
67
+ continue;
68
+ sawAssistant = true;
69
+ names.push(...toolUseNames(record).reverse());
70
+ }
71
+ return sawAssistant ? names.reverse() : null;
72
+ }
73
+ function* reversed(items) {
74
+ for (let i = items.length - 1; i >= 0; i--)
75
+ yield items[i];
76
+ }
77
+ function readTranscriptLines(transcriptPath) {
78
+ if (!transcriptPath)
79
+ return undefined;
80
+ try {
81
+ return readFileSync(transcriptPath, 'utf8').split('\n');
82
+ }
83
+ catch {
84
+ return undefined;
85
+ }
86
+ }
87
+ function* parsedFromEnd(lines) {
88
+ for (const line of reversed(lines)) {
89
+ if (!line.trim())
90
+ continue;
91
+ try {
92
+ yield JSON.parse(line);
93
+ }
94
+ catch {
95
+ // A truncated or malformed line is skipped, never fatal: a hook reads this on every stop.
96
+ }
97
+ }
98
+ }
99
+ /**
100
+ * The name of every tool the assistant used since the last human prompt in `records`, in
101
+ * transcript order. Null when no assistant record follows that prompt. Null is the lag case:
102
+ * the harness writes the transcript asynchronously, so a file with no assistant record since
103
+ * the prompt may not have caught up yet, and a caller must not read it as "no tools used".
104
+ *
105
+ * @param records Transcript records oldest first, as the `.jsonl` file holds them.
106
+ */
107
+ export function toolUsesSinceLastPrompt(records) {
108
+ return collectNewestFirst(reversed(records));
109
+ }
110
+ /**
111
+ * Whether the turn that just ended may have written to the working tree, judged from the
112
+ * tool uses recorded since the last human prompt in the transcript at `transcriptPath`.
113
+ *
114
+ * `false` means every tool use was in {@link READ_ONLY_TOOLS}, or there were none, so a Stop
115
+ * hook that reacts to edits can exit before spawning anything. `true` means at least one
116
+ * tool use could have written. `undefined` means the question has no answer: no path, an
117
+ * unreadable file, or no assistant record since the prompt, which is how a lagging write
118
+ * looks. A caller treats `undefined` exactly as it behaved before this gate existed.
119
+ */
120
+ export function turnTouchedFiles(transcriptPath) {
121
+ const lines = readTranscriptLines(transcriptPath);
122
+ if (!lines)
123
+ return undefined;
124
+ const uses = collectNewestFirst(parsedFromEnd(lines));
125
+ if (uses === null)
126
+ return undefined;
127
+ return uses.some((name) => !READ_ONLY_TOOLS.has(name));
128
+ }
129
+ /**
130
+ * When the turn that just ended began, as epoch milliseconds: the `timestamp` of the last
131
+ * human prompt in the transcript at `transcriptPath`. Undefined when there is no path, the
132
+ * file is unreadable, or no prompt carries a parseable timestamp. A lagging transcript can
133
+ * only yield an earlier prompt, which widens the turn rather than narrowing it.
134
+ */
135
+ export function turnStartedAt(transcriptPath) {
136
+ const lines = readTranscriptLines(transcriptPath);
137
+ if (!lines)
138
+ return undefined;
139
+ for (const record of parsedFromEnd(lines)) {
140
+ if (!isHumanPrompt(record))
141
+ continue;
142
+ const startedAt = Date.parse(record.timestamp ?? '');
143
+ return Number.isNaN(startedAt) ? undefined : startedAt;
144
+ }
145
+ return undefined;
146
+ }