@houserules/payload 0.0.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.
@@ -0,0 +1,131 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { execSync } from 'node:child_process';
4
+ /** What `filterFlag` means when a runner block omits it: a workspace, filtered per package. */
5
+ export const DEFAULT_FILTER_FLAG = '--filter';
6
+ /**
7
+ * The commands that actually run for one target, from its own override and the block's list.
8
+ *
9
+ * `null` and `undefined` are different answers, which is why this is not a bare `??`. An
10
+ * absent override inherits the block's commands. An explicit `null` means this target has
11
+ * none, the escape hatch for a package the runner should skip entirely.
12
+ */
13
+ export function resolveTargetCommands(override, blockCommands) {
14
+ if (override === null)
15
+ return [];
16
+ return override ?? blockCommands ?? [];
17
+ }
18
+ /**
19
+ * Whether a runner block's commands run as REPO-ROOT scripts rather than once per package.
20
+ *
21
+ * An empty `filterFlag` is how a single-package repo, or a workspace whose lint and format
22
+ * live at the root, is spelled. Both runners drop the package name from the argv in that
23
+ * shape, so the script that has to exist is the ROOT one no matter which target contributed
24
+ * the command.
25
+ */
26
+ export function runsAtRepoRoot(block) {
27
+ return !(block?.filterFlag ?? DEFAULT_FILTER_FLAG);
28
+ }
29
+ export function repoRoot() {
30
+ return execSync('git rev-parse --show-toplevel', {
31
+ stdio: ['ignore', 'pipe', 'ignore'],
32
+ })
33
+ .toString()
34
+ .trim();
35
+ }
36
+ /**
37
+ * `repoRoot()` for a script that must not crash. Returns null outside a git work tree, or
38
+ * when `git` is absent, rather than throwing.
39
+ *
40
+ * A runtime-invoked payload script is required to exit 0 on every failure path, and a
41
+ * throw at module load defeats that before any handler can run. Such a script resolves its
42
+ * root through this and exits cleanly on null.
43
+ */
44
+ export function repoRootSafe() {
45
+ try {
46
+ return repoRoot() || null;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ export const GUARD_DEFAULTS = {
53
+ gitCommit: true,
54
+ gitPush: true,
55
+ gitStash: true,
56
+ prCreate: true,
57
+ custom: [],
58
+ };
59
+ /**
60
+ * Defaults for the opt-in PreToolUse(Read) guard. Only unbounded whole-file reads, those
61
+ * with no offset or limit, of generated or oversized files are redirected. `maxBytes` is
62
+ * deliberately high so it catches only genuinely huge files, and `denyGlobs` handles the
63
+ * common always-generated cases regardless of size.
64
+ */
65
+ export const READ_GUARD_DEFAULTS = {
66
+ enabled: true,
67
+ maxBytes: 500000,
68
+ denyGlobs: [
69
+ '**/*.min.js',
70
+ '**/*.min.css',
71
+ '**/*.map',
72
+ 'pnpm-lock.yaml',
73
+ 'package-lock.json',
74
+ 'yarn.lock',
75
+ 'bun.lock',
76
+ 'bun.lockb',
77
+ '**/dist/**',
78
+ '**/build/**',
79
+ '**/.next/**',
80
+ '**/node_modules/**',
81
+ ],
82
+ };
83
+ const EMPTY = Object.freeze({ targets: [] });
84
+ const cache = new Map();
85
+ /**
86
+ * Reads `<repo>/.claude/houserules.config.json`, the declarative file adapting the scripts to a
87
+ * repo's package layout and toolchain. CLI-style scripts demand a config and exit loudly
88
+ * without one. Hooks must call `loadConfigSafe()` instead.
89
+ */
90
+ export function loadConfig(root = repoRoot(), { required = true } = {}) {
91
+ if (cache.has(root))
92
+ return cache.get(root);
93
+ const path = resolve(root, '.claude/houserules.config.json');
94
+ let config;
95
+ if (!existsSync(path)) {
96
+ if (required) {
97
+ console.error(`houserules: missing ${path}\n` +
98
+ 'Run `npx houserules init` (or copy houserules.config.example.json) to create it.');
99
+ process.exit(1);
100
+ }
101
+ config = { targets: [] };
102
+ }
103
+ else {
104
+ try {
105
+ config = JSON.parse(readFileSync(path, 'utf8'));
106
+ }
107
+ catch (e) {
108
+ if (required) {
109
+ console.error(`houserules: ${path} is not valid JSON: ${e.message}`);
110
+ process.exit(1);
111
+ }
112
+ config = { targets: [] };
113
+ }
114
+ }
115
+ config.targets ??= [];
116
+ cache.set(root, config);
117
+ return config;
118
+ }
119
+ /**
120
+ * The loader hooks must use. It never exits and never throws, returning an empty config
121
+ * in the worst case. A hook that crashes on a missing or broken config is noise on every
122
+ * single tool call.
123
+ */
124
+ export function loadConfigSafe() {
125
+ try {
126
+ return loadConfig(repoRoot(), { required: false });
127
+ }
128
+ catch {
129
+ return EMPTY;
130
+ }
131
+ }
@@ -0,0 +1,240 @@
1
+ export declare const SEPARATOR = "---";
2
+ export declare const nowIso: () => string;
3
+ export declare const todayDate: () => string;
4
+ export declare const encodeBody: (s?: string) => string;
5
+ export declare const decodeBody: (s: string) => string;
6
+ /** Splices `--chat <id>` / `--chat=<id>` out of `argv` in place. */
7
+ export declare function takeChatFlag(argv: string[]): string | null;
8
+ /** `--chat=none` suppresses provenance. Any other flag wins over detection. */
9
+ export declare function resolveChat(flag: string | null, repoRoot: string): string | null;
10
+ export declare function appendEvent(logFile: string, record: Record<string, unknown>): void;
11
+ /** Every parseable record in log order. Unparseable lines are skipped, never fatal. */
12
+ export declare function readLog<TRecord>(logFile: string): TRecord[];
13
+ /**
14
+ * The append-only ledger for `name`, at `.claude/ledgers/<name>.jsonl`.
15
+ *
16
+ * Its own directory rather than `.claude/state/`, which the changesets module already owns for
17
+ * ephemeral cache and self-gitignores with `*` because none of it needs to survive being
18
+ * deleted. The ledger is a local write-ahead queue that `projects-sync.mjs push` drains to
19
+ * GitHub Projects, so an entry not yet pushed exists nowhere else, and the two directories need
20
+ * different ignore rules and cannot share one. `.jsonl` and not `.log`, because `*.log` is a
21
+ * common ignore pattern this file must avoid.
22
+ *
23
+ * Older trees are migrated in place, newest layout first, so there is one path afterward and
24
+ * never a split ledger. A rename that fails leaves the older file authoritative rather than
25
+ * starting a second one.
26
+ */
27
+ export declare function ledgerPath(repoRoot: string, name: string, configuredDir?: string): string;
28
+ /**
29
+ * Whether replacing `file` with `nextContent` would drop entries the file already holds and
30
+ * the ledger does not account for.
31
+ *
32
+ * A rebuild reads the ledger and overwrites the surface, so a missing ledger silently destroys
33
+ * the only remaining copy. Measured, not assumed: a checkout carrying the surface without its
34
+ * ledger turned four recorded decisions into one.
35
+ *
36
+ * Compares id SETS, not counts. A count check cannot tell a legitimate removal from the loss
37
+ * of a different entry, and it misses the case where one entry vanishes as another appears.
38
+ * `intentionallyDropped` is the ids the ledger records as removed, which a backlog removal
39
+ * produces and a decision never does, since superseding leaves the entry rendered.
40
+ */
41
+ export declare function rebuildWouldDropEntries(file: string, nextContent: string, intentionallyDropped?: ReadonlySet<string>): boolean;
42
+ export declare function readSurface(file: string): string;
43
+ /** Reads the body from the argument, or from stdin when it was omitted and stdin is a pipe. */
44
+ export declare function readContentArg(content: string | undefined): string;
45
+ export declare function relativeToRoot(repoRoot: string, p: string): string;
46
+ /**
47
+ * The ledger directory, from `ledgers.dir` or the default.
48
+ *
49
+ * Falls back to the default for a path that escapes the repo, and for the repo root itself. The
50
+ * root is refused because houserules self-ignores this directory with `*.md`, and that rule at the
51
+ * repo root would hide README.md, CLAUDE.md, and every other document in the project.
52
+ */
53
+ export declare function ledgerDir(repoRoot: string, configured?: string): string;
54
+ /**
55
+ * Where one area's rendered surface lives, as `<dir>/<target>.<basename>`.
56
+ *
57
+ * A monorepo separates areas by filename inside one ledger directory rather than by nesting a
58
+ * ledger beside each package. One directory per repo means one place to find, ignore, and
59
+ * reconcile, and the record's own `file` field already says which surface an entry belongs to.
60
+ * The root area has no prefix, so it stays `BACKLOG.md`.
61
+ */
62
+ export declare function surfacePath(dir: string, basename: string, target?: string | null): string;
63
+ /**
64
+ * Whether a surface with zero live entries should be deleted rather than left as a bare header.
65
+ *
66
+ * A surface is written for any area the ledger has ever recorded against, so an area whose
67
+ * entries were all removed kept rendering as a header-only stub that no `remove` could ever
68
+ * clear. The repo-root area collects every entry logged without an `<area>`, which makes it the
69
+ * one that accumulates stubs by accident.
70
+ *
71
+ * A configured target is exempt. Its surface is declared in `houserules.config.json`, so an empty one
72
+ * reads as "this area has nothing open" rather than as residue, and deleting it would churn a
73
+ * file the repo means to have. An area with no target and no entries is residue, so it goes.
74
+ */
75
+ export declare function surfaceIsResidue(file: string, basename: string, entryCount: number, targets: readonly {
76
+ name?: string;
77
+ }[]): boolean;
78
+ /**
79
+ * The area a rendered surface covers, for its header. Reads the target out of the filename and
80
+ * maps it through the configured targets, so a file named `studio.BACKLOG.md` renders as
81
+ * `Backlog — Studio` rather than naming the directory it happens to sit in.
82
+ *
83
+ * The target's `label` wins over its `pathPrefix`. A surface named for a target does not have to
84
+ * hold only that target's entries: a repo whose whole product is one target files everything
85
+ * there, and rendering `pathPrefix` then claims a scope narrower than the entries below it. The
86
+ * label is the name the user chose for the area, so it stays true either way. `pathPrefix`
87
+ * remains the fallback for a target that somehow carries no label.
88
+ */
89
+ export declare function surfaceScope(file: string, basename: string, targets: ReadonlyArray<{
90
+ name: string;
91
+ label?: string;
92
+ pathPrefix?: string;
93
+ }>): string;
94
+ /**
95
+ * The path recorded on each entry's `file`, and matched against when rebuilding a surface.
96
+ *
97
+ * Relative to the LEDGER DIRECTORY, never the repo root. Two reasons, both load-bearing. A
98
+ * record written when the surface sat at the repo root says `BACKLOG.md`, and that keeps
99
+ * matching once the surface moves into the ledger directory, so no migration is needed. And
100
+ * moving the directory later through `ledgers.dir` does not orphan every existing record.
101
+ *
102
+ * Recording this against the repo root instead silently renders an empty surface: the filter
103
+ * compares `.claude/ledgers/BACKLOG.md` to a stored `BACKLOG.md` and matches nothing.
104
+ */
105
+ export declare function surfaceRelFile(dir: string, file: string): string;
106
+ /**
107
+ * The ledger-dir-relative surface name a recorded `file` value refers to today.
108
+ *
109
+ * Ledgers written before the surfaces moved into the ledger directory recorded a repo-relative
110
+ * path such as `games/tower-push/BACKLOG.md`. Nothing can equal that today, because
111
+ * {@link surfaceRelFile} now yields `tower-push.BACKLOG.md`, so every such entry silently stops
112
+ * matching its surface and the ledger renders empty.
113
+ *
114
+ * Normalizing on READ rather than rewriting the ledger is deliberate. The ledger is append-only,
115
+ * so a migration that rewrote historical `file` fields would edit records already appended and
116
+ * possibly already pushed to the board. This is a pure projection instead, it is idempotent,
117
+ * and a repo can roll back to an older houserules without its history having been altered.
118
+ *
119
+ * The area is taken from the configured targets first, since that is authoritative. The trailing
120
+ * directory name is the fallback, which is what makes an area the config no longer lists still
121
+ * resolve rather than vanish.
122
+ *
123
+ * @param recorded The `file` value as stored on the entry.
124
+ * @param basename The surface basename, `BACKLOG.md` or `DECISIONS.md`.
125
+ */
126
+ export declare function normalizeSurfaceRef(recorded: string, basename: string, targets: ReadonlyArray<{
127
+ name: string;
128
+ pathPrefix?: string;
129
+ }>): string;
130
+ /**
131
+ * Resolves the `<area>` argument the ledger commands accept, one rule for every ledger.
132
+ *
133
+ * Omitted, or the basename itself, means the repo-root surface inside the ledger directory. A
134
+ * bare word names an area. A path ending in the surface basename names an area too, and routes
135
+ * to the same canonical file the bare word would. So does an area's own surface filename, so
136
+ * `tower-push` and `tower-push.BACKLOG.md` are one area rather than two.
137
+ *
138
+ * That last rule is why this takes `targets`. The argument goes through
139
+ * {@link normalizeSurfaceRef}, the same projection the rebuild uses to decide which entries
140
+ * belong to a surface, so the file written is always the file the projection matched. While the
141
+ * two disagreed, `remove <id> games/tower-push/BACKLOG.md` rebuilt the surface into a stray file
142
+ * and left the canonical one still carrying the entry it had just removed, at exit code 0.
143
+ *
144
+ * Anything else with a separator stays an explicit path, resolved against the repo root rather
145
+ * than the process cwd, so a hook invoked from a subdirectory writes where the caller meant. A
146
+ * literal path that escapes the repo falls back to the root surface, the way {@link ledgerDir}
147
+ * refuses an escaping `ledgers.dir`, since no ledger command has reason to write outside the
148
+ * repo it is recording.
149
+ *
150
+ * Lives here rather than in each script because the two ledgers diverged when they each owned a
151
+ * copy: one sent the bare basename to the repo root and the other to the ledger directory, so the
152
+ * same argument meant two different files.
153
+ */
154
+ export declare function resolveSurfaceArg(repoRoot: string, dir: string, basename: string, targets: ReadonlyArray<{
155
+ name: string;
156
+ pathPrefix?: string;
157
+ }>, arg?: string): string;
158
+ /**
159
+ * The bare area name an `<area>` argument refers to, or null when {@link resolveSurfaceArg} would
160
+ * not resolve it against a per-target surface at all: the repo-root surface, or a literal path
161
+ * escape hatch, meaning a path with a separator that does not name a configured target's area.
162
+ *
163
+ * Mirrors {@link resolveSurfaceArg}'s branching on the same argument, so a name checked here is the
164
+ * name the surface would actually resolve to.
165
+ */
166
+ export declare function resolveAreaName(arg: string, basename: string, targets: ReadonlyArray<{
167
+ name: string;
168
+ pathPrefix?: string;
169
+ }>): string | null;
170
+ /**
171
+ * The area names a list of surface files stands for, skipping the repo-root surface.
172
+ *
173
+ * Takes the file list rather than reading the directory, so this stays pure and the script that
174
+ * already knows its surfaces is the one that supplies them.
175
+ */
176
+ export declare function areaNamesOf(surfaceFiles: readonly string[], dir: string, basename: string, targets: ReadonlyArray<{
177
+ name: string;
178
+ pathPrefix?: string;
179
+ }>): Set<string>;
180
+ /**
181
+ * Why this `<area>` argument cannot be used, or null when it names an area that exists.
182
+ *
183
+ * Every ledger command that takes an area calls this BEFORE it appends or renders anything. An area
184
+ * nothing knows about is not a harmless typo. It renders a surface file nobody asked for, and the
185
+ * ledger then carries entries filed against a surface no board is configured for, so the mistake
186
+ * surfaces one or more pushes later as `no board configured for surface "<area>.BACKLOG.md"`, far
187
+ * from the command that caused it.
188
+ *
189
+ * An area counts as existing if a target configures it OR a surface for it is already on disk.
190
+ * `existingAreas` is what carries the second half, and dropping it would break the fallback
191
+ * {@link normalizeSurfaceRef} exists for: an area whose target the config no longer lists still
192
+ * has its entries, and `render <that area>` has to keep resolving rather than being called a typo.
193
+ * A genuine typo matches neither half.
194
+ *
195
+ * Returns the message rather than exiting, because the two ledger scripts own their own exits. It
196
+ * returns the message rather than a boolean so the wording cannot drift between them, which is the
197
+ * same reason {@link resolveSurfaceArg} lives here.
198
+ */
199
+ export declare function unknownAreaMessage(arg: string | undefined, basename: string, targets: ReadonlyArray<{
200
+ name: string;
201
+ pathPrefix?: string;
202
+ }>, existingAreas: ReadonlySet<string>): string | null;
203
+ /**
204
+ * Every surface the ledger implies, union'd with every surface already on disk.
205
+ *
206
+ * The `.jsonl` is the source of truth and the markdown is a generated view, so a freshly
207
+ * migrated ledger, one whose entries moved into `.claude/ledgers/` but was never rendered,
208
+ * has zero files on disk and would otherwise look empty to `list` and `render`. Deriving the
209
+ * surface set from the ledger's own recorded `file` values instead means a surface with no
210
+ * live entries still gets its header, and a surface every entry was removed from does not
211
+ * silently vanish just because nothing wrote it since.
212
+ *
213
+ * On-disk names go through the same projection as the recorded ones. A file left behind under
214
+ * a name that no longer projects to itself, such as a doubled `x.BACKLOG.md.BACKLOG.md`, would
215
+ * otherwise be rebuilt on every render with the content of the area it collapses to, leaving
216
+ * two files holding the same entries.
217
+ *
218
+ * @param recordedFiles The raw `file` value off every ledger record, in any order, possibly
219
+ * holding `undefined` for records that predate the field.
220
+ */
221
+ export declare function impliedSurfaceFiles(dir: string, basename: string, recordedFiles: Iterable<string | undefined>, targets: ReadonlyArray<{
222
+ name: string;
223
+ pathPrefix?: string;
224
+ }>): string[];
225
+ /** Every rendered surface with this basename in the ledger directory. */
226
+ export declare function findSurfaceFiles(dir: string, basename: string): string[];
227
+ export declare function renderMetadata(fields: Record<string, string | null>): string;
228
+ interface ParsedEntry {
229
+ id: string;
230
+ title: string;
231
+ meta: Record<string, string>;
232
+ body: string;
233
+ }
234
+ /**
235
+ * Every entry in a rendered surface. A metadata line is consumed into `meta` rather than the
236
+ * body, and the first occurrence of a label wins, so prose below the header that happens to
237
+ * look like metadata cannot displace the real header value.
238
+ */
239
+ export declare function parseEntries(text: string): ParsedEntry[];
240
+ export {};