@bookedsolid/rea 0.4.0 → 0.5.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,115 @@
1
+ /**
2
+ * Review cache (BUG-009). The push-review-gate hook (`hooks/push-review-gate.sh`)
3
+ * has shipped since 0.3.x calling `rea cache check <sha>` to skip re-review on
4
+ * a previously-approved diff, and `rea cache set <sha> pass ...` as the
5
+ * operator's advertised way to complete the gate. Neither subcommand existed
6
+ * in the CLI through 0.4.0. Once BUG-008's pre-push stdin adapter lands and
7
+ * the gate actually fires, a protected-path push has no completion path
8
+ * without this cache — hence "paired ship blocker."
9
+ *
10
+ * ## File layout
11
+ *
12
+ * `.rea/review-cache.jsonl` — one JSON object per line, terminated with `\n`.
13
+ * Each entry:
14
+ *
15
+ * {
16
+ * "sha": "<diff-sha256>",
17
+ * "branch": "<feature-branch>",
18
+ * "base": "<target-branch>",
19
+ * "result": "pass" | "fail",
20
+ * "recorded_at": "<ISO-8601>",
21
+ * "reason"?: "<free text>" // optional, populated on fail or on skip
22
+ * }
23
+ *
24
+ * The `sha` is whatever the caller supplies — the hook happens to use a
25
+ * SHA-256 of the full diff, but the cache does not interpret or validate the
26
+ * value. Hash-chained is intentionally NOT required: this is a keyed cache,
27
+ * not an append-only integrity log. The audit log at `.rea/audit.jsonl`
28
+ * remains the integrity story.
29
+ *
30
+ * ## Concurrency
31
+ *
32
+ * Every write takes the same `proper-lockfile` lock on the `.rea/` parent
33
+ * directory that the audit helpers use (`withAuditLock`). This means a
34
+ * concurrent audit append and cache write serialize against each other — a
35
+ * negligible cost given cache writes happen once per push gate completion.
36
+ *
37
+ * ## Idempotency
38
+ *
39
+ * `appendEntry` writes a new line unconditionally. `lookup` returns the most
40
+ * recent entry matching `(sha, branch, base)`. This "last write wins" keeps
41
+ * the write path O(1) and the read path O(n) over the file; n is bounded by
42
+ * typical review frequency (dozens per week, not millions). If a future
43
+ * operator needs a compact file, `rea cache clear <sha>` drops matching
44
+ * entries and a separate `rea cache compact` (not in 0.5.0) could rewrite.
45
+ *
46
+ * ## TTL
47
+ *
48
+ * `lookup` honors `review.cache_max_age_seconds` (default 3600). Entries
49
+ * older than the window are treated as a miss. Expired entries are not
50
+ * garbage-collected on read — `rea cache clear` or `rea cache compact`
51
+ * is the operator tool for shrinking.
52
+ */
53
+ /** Default TTL when policy does not supply one. */
54
+ export declare const DEFAULT_CACHE_MAX_AGE_SECONDS = 3600;
55
+ export type CacheResult = 'pass' | 'fail';
56
+ export interface CacheEntry {
57
+ sha: string;
58
+ branch: string;
59
+ base: string;
60
+ result: CacheResult;
61
+ recorded_at: string;
62
+ reason?: string;
63
+ }
64
+ export interface CacheLookupInput {
65
+ sha: string;
66
+ branch: string;
67
+ base: string;
68
+ /** Epoch ms used as the "now" reference for TTL comparison. Defaults to `Date.now()`. */
69
+ nowMs?: number;
70
+ /** TTL in seconds; defaults to {@link DEFAULT_CACHE_MAX_AGE_SECONDS}. */
71
+ maxAgeSeconds?: number;
72
+ }
73
+ export interface CacheLookupResult {
74
+ hit: boolean;
75
+ entry?: CacheEntry;
76
+ /** Reason for a miss. One of `'no-entry' | 'expired' | 'empty-file'`. Always set when `hit === false`. */
77
+ missReason?: 'no-entry' | 'expired' | 'empty-file';
78
+ }
79
+ export interface CacheAppendInput {
80
+ sha: string;
81
+ branch: string;
82
+ base: string;
83
+ result: CacheResult;
84
+ reason?: string;
85
+ /** ISO-8601 timestamp. Defaults to `new Date().toISOString()`. */
86
+ timestamp?: string;
87
+ }
88
+ export declare function resolveCacheFile(baseDir: string): string;
89
+ /**
90
+ * Append an entry to the cache. Writes are serialized through the shared
91
+ * `.rea/` directory lock so audit writes and cache writes do not interleave.
92
+ */
93
+ export declare function appendEntry(baseDir: string, input: CacheAppendInput): Promise<CacheEntry>;
94
+ /**
95
+ * Find the most-recent entry matching `(sha, branch, base)` within the TTL
96
+ * window. Idempotent and side-effect free.
97
+ */
98
+ export declare function lookup(baseDir: string, input: CacheLookupInput): Promise<CacheLookupResult>;
99
+ /**
100
+ * Remove every entry matching `sha`. Returns the count removed. A `0` return
101
+ * is a valid outcome (sha not present). Writes back via the same lock as
102
+ * `appendEntry`, so concurrent sets do not lose entries.
103
+ *
104
+ * Writes use temp-file + `fs.rename` (atomic within a single directory on
105
+ * POSIX) so unlocked readers (`lookup`, `list`) can never observe a torn or
106
+ * empty intermediate state. Codex F4 on the 0.5.0 PR1 review.
107
+ */
108
+ export declare function clear(baseDir: string, sha: string): Promise<number>;
109
+ /**
110
+ * Return every entry, optionally filtered by branch. Entries are returned in
111
+ * file order (oldest first). Callers that want "newest first" should reverse.
112
+ */
113
+ export declare function list(baseDir: string, options?: {
114
+ branch?: string;
115
+ }): Promise<CacheEntry[]>;
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Review cache (BUG-009). The push-review-gate hook (`hooks/push-review-gate.sh`)
3
+ * has shipped since 0.3.x calling `rea cache check <sha>` to skip re-review on
4
+ * a previously-approved diff, and `rea cache set <sha> pass ...` as the
5
+ * operator's advertised way to complete the gate. Neither subcommand existed
6
+ * in the CLI through 0.4.0. Once BUG-008's pre-push stdin adapter lands and
7
+ * the gate actually fires, a protected-path push has no completion path
8
+ * without this cache — hence "paired ship blocker."
9
+ *
10
+ * ## File layout
11
+ *
12
+ * `.rea/review-cache.jsonl` — one JSON object per line, terminated with `\n`.
13
+ * Each entry:
14
+ *
15
+ * {
16
+ * "sha": "<diff-sha256>",
17
+ * "branch": "<feature-branch>",
18
+ * "base": "<target-branch>",
19
+ * "result": "pass" | "fail",
20
+ * "recorded_at": "<ISO-8601>",
21
+ * "reason"?: "<free text>" // optional, populated on fail or on skip
22
+ * }
23
+ *
24
+ * The `sha` is whatever the caller supplies — the hook happens to use a
25
+ * SHA-256 of the full diff, but the cache does not interpret or validate the
26
+ * value. Hash-chained is intentionally NOT required: this is a keyed cache,
27
+ * not an append-only integrity log. The audit log at `.rea/audit.jsonl`
28
+ * remains the integrity story.
29
+ *
30
+ * ## Concurrency
31
+ *
32
+ * Every write takes the same `proper-lockfile` lock on the `.rea/` parent
33
+ * directory that the audit helpers use (`withAuditLock`). This means a
34
+ * concurrent audit append and cache write serialize against each other — a
35
+ * negligible cost given cache writes happen once per push gate completion.
36
+ *
37
+ * ## Idempotency
38
+ *
39
+ * `appendEntry` writes a new line unconditionally. `lookup` returns the most
40
+ * recent entry matching `(sha, branch, base)`. This "last write wins" keeps
41
+ * the write path O(1) and the read path O(n) over the file; n is bounded by
42
+ * typical review frequency (dozens per week, not millions). If a future
43
+ * operator needs a compact file, `rea cache clear <sha>` drops matching
44
+ * entries and a separate `rea cache compact` (not in 0.5.0) could rewrite.
45
+ *
46
+ * ## TTL
47
+ *
48
+ * `lookup` honors `review.cache_max_age_seconds` (default 3600). Entries
49
+ * older than the window are treated as a miss. Expired entries are not
50
+ * garbage-collected on read — `rea cache clear` or `rea cache compact`
51
+ * is the operator tool for shrinking.
52
+ */
53
+ import fs from 'node:fs/promises';
54
+ import path from 'node:path';
55
+ import { withAuditLock } from '../audit/fs.js';
56
+ /** Default TTL when policy does not supply one. */
57
+ export const DEFAULT_CACHE_MAX_AGE_SECONDS = 3600;
58
+ /**
59
+ * Tolerated clock skew for future-dated entries. A `recorded_at` more than
60
+ * this far in the future relative to `nowMs` is treated as tampered or
61
+ * severely-drifted and forces a miss (re-review). 60s covers NTP jitter on
62
+ * well-synced hosts; anything beyond that is noise we do not trust.
63
+ */
64
+ const FUTURE_SKEW_ALLOWANCE_MS = 60_000;
65
+ const CACHE_FILENAME = 'review-cache.jsonl';
66
+ const REA_DIRNAME = '.rea';
67
+ export function resolveCacheFile(baseDir) {
68
+ return path.join(baseDir, REA_DIRNAME, CACHE_FILENAME);
69
+ }
70
+ /**
71
+ * Load every entry from the cache file. Returns `[]` when the file does not
72
+ * exist or is empty. Malformed lines are skipped — we never throw on a
73
+ * corrupt line, because the cache is advisory and a bad write (e.g. a
74
+ * half-written line from a crashed host) must not block a subsequent push.
75
+ */
76
+ async function loadEntries(cacheFile) {
77
+ let raw;
78
+ try {
79
+ raw = await fs.readFile(cacheFile, 'utf8');
80
+ }
81
+ catch (err) {
82
+ if (err.code === 'ENOENT')
83
+ return [];
84
+ throw err;
85
+ }
86
+ if (raw.length === 0)
87
+ return [];
88
+ const entries = [];
89
+ for (const line of raw.split('\n')) {
90
+ if (line.length === 0)
91
+ continue;
92
+ try {
93
+ const parsed = JSON.parse(line);
94
+ if (typeof parsed.sha === 'string' &&
95
+ typeof parsed.branch === 'string' &&
96
+ typeof parsed.base === 'string' &&
97
+ (parsed.result === 'pass' || parsed.result === 'fail') &&
98
+ typeof parsed.recorded_at === 'string') {
99
+ entries.push(parsed);
100
+ }
101
+ }
102
+ catch {
103
+ // Skip malformed line.
104
+ }
105
+ }
106
+ return entries;
107
+ }
108
+ /**
109
+ * Append an entry to the cache. Writes are serialized through the shared
110
+ * `.rea/` directory lock so audit writes and cache writes do not interleave.
111
+ */
112
+ export async function appendEntry(baseDir, input) {
113
+ const cacheFile = resolveCacheFile(baseDir);
114
+ await fs.mkdir(path.dirname(cacheFile), { recursive: true });
115
+ const entry = {
116
+ sha: input.sha,
117
+ branch: input.branch,
118
+ base: input.base,
119
+ result: input.result,
120
+ recorded_at: input.timestamp ?? new Date().toISOString(),
121
+ ...(input.reason !== undefined && input.reason.length > 0
122
+ ? { reason: input.reason }
123
+ : {}),
124
+ };
125
+ await withAuditLock(cacheFile, async () => {
126
+ const line = JSON.stringify(entry) + '\n';
127
+ await fs.appendFile(cacheFile, line);
128
+ });
129
+ return entry;
130
+ }
131
+ /**
132
+ * Find the most-recent entry matching `(sha, branch, base)` within the TTL
133
+ * window. Idempotent and side-effect free.
134
+ */
135
+ export async function lookup(baseDir, input) {
136
+ const cacheFile = resolveCacheFile(baseDir);
137
+ const entries = await loadEntries(cacheFile);
138
+ if (entries.length === 0)
139
+ return { hit: false, missReason: 'empty-file' };
140
+ // Walk from the tail so the first match is the newest.
141
+ let matched;
142
+ for (let i = entries.length - 1; i >= 0; i--) {
143
+ const e = entries[i];
144
+ if (e.sha === input.sha && e.branch === input.branch && e.base === input.base) {
145
+ matched = e;
146
+ break;
147
+ }
148
+ }
149
+ if (matched === undefined)
150
+ return { hit: false, missReason: 'no-entry' };
151
+ const nowMs = input.nowMs ?? Date.now();
152
+ const maxAgeSeconds = input.maxAgeSeconds ?? DEFAULT_CACHE_MAX_AGE_SECONDS;
153
+ const recordedMs = Date.parse(matched.recorded_at);
154
+ if (Number.isNaN(recordedMs)) {
155
+ // Corrupt timestamp — treat as an expired miss so the caller re-reviews.
156
+ return { hit: false, missReason: 'expired', entry: matched };
157
+ }
158
+ if (recordedMs > nowMs + FUTURE_SKEW_ALLOWANCE_MS) {
159
+ return { hit: false, missReason: 'expired', entry: matched };
160
+ }
161
+ if ((nowMs - recordedMs) / 1000 > maxAgeSeconds) {
162
+ return { hit: false, missReason: 'expired', entry: matched };
163
+ }
164
+ return { hit: true, entry: matched };
165
+ }
166
+ /**
167
+ * Remove every entry matching `sha`. Returns the count removed. A `0` return
168
+ * is a valid outcome (sha not present). Writes back via the same lock as
169
+ * `appendEntry`, so concurrent sets do not lose entries.
170
+ *
171
+ * Writes use temp-file + `fs.rename` (atomic within a single directory on
172
+ * POSIX) so unlocked readers (`lookup`, `list`) can never observe a torn or
173
+ * empty intermediate state. Codex F4 on the 0.5.0 PR1 review.
174
+ */
175
+ export async function clear(baseDir, sha) {
176
+ const cacheFile = resolveCacheFile(baseDir);
177
+ return withAuditLock(cacheFile, async () => {
178
+ const entries = await loadEntries(cacheFile);
179
+ const kept = entries.filter((e) => e.sha !== sha);
180
+ const removed = entries.length - kept.length;
181
+ if (removed === 0)
182
+ return 0;
183
+ const out = kept.length === 0 ? '' : kept.map((e) => JSON.stringify(e)).join('\n') + '\n';
184
+ const tmpFile = `${cacheFile}.tmp.${process.pid}.${Date.now()}`;
185
+ await fs.writeFile(tmpFile, out);
186
+ await fs.rename(tmpFile, cacheFile);
187
+ return removed;
188
+ });
189
+ }
190
+ /**
191
+ * Return every entry, optionally filtered by branch. Entries are returned in
192
+ * file order (oldest first). Callers that want "newest first" should reverse.
193
+ */
194
+ export async function list(baseDir, options = {}) {
195
+ const cacheFile = resolveCacheFile(baseDir);
196
+ const entries = await loadEntries(cacheFile);
197
+ if (options.branch === undefined)
198
+ return entries;
199
+ return entries.filter((e) => e.branch === options.branch);
200
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * `rea cache` — push-review cache operator subcommands (BUG-009).
3
+ *
4
+ * Four verbs:
5
+ * - `check <sha> --branch <b> --base <b>` — JSON to stdout ONLY; never
6
+ * diagnostics. `hooks/push-review-gate.sh` reads this via
7
+ * `printf '%s' "$CACHE_RESULT" | jq -e '.hit == true'`, so any stray
8
+ * text on stdout would poison the hook's JSON parse.
9
+ * - `set <sha> pass|fail --branch <b> --base <b> [--reason <s>]` — record
10
+ * a review outcome.
11
+ * - `clear <sha>` — drop every entry for a sha (dev convenience).
12
+ * - `list [--branch <b>]` — pretty-print entries.
13
+ *
14
+ * The TTL used by `check` reads `review.cache_max_age_seconds` from
15
+ * `.rea/policy.yaml` when present, falling back to
16
+ * {@link DEFAULT_CACHE_MAX_AGE_SECONDS} (1 hour) when the policy file or
17
+ * field is absent. An unreadable/malformed policy file is NOT fatal for
18
+ * `check` — it degrades to the default so a broken policy never deadlocks
19
+ * the push gate; other commands that don't consume the TTL ignore the policy
20
+ * entirely.
21
+ */
22
+ import { type CacheResult } from '../cache/review-cache.js';
23
+ export interface CacheCheckOptions {
24
+ sha: string;
25
+ branch: string;
26
+ base: string;
27
+ }
28
+ export interface CacheSetOptions {
29
+ sha: string;
30
+ result: CacheResult;
31
+ branch: string;
32
+ base: string;
33
+ reason?: string;
34
+ }
35
+ export interface CacheClearOptions {
36
+ sha: string;
37
+ }
38
+ export interface CacheListOptions {
39
+ branch?: string;
40
+ }
41
+ /**
42
+ * Print the cache-check JSON to stdout. Hook contract: stdout is ONLY JSON.
43
+ * On a miss we still exit 0 with `{"hit":false}` — the hook interprets
44
+ * non-zero as "rea broken, force re-review" via its `|| echo '{"hit":false}'`
45
+ * fallback.
46
+ */
47
+ export declare function runCacheCheck(options: CacheCheckOptions): Promise<void>;
48
+ export declare function runCacheSet(options: CacheSetOptions): Promise<void>;
49
+ export declare function runCacheClear(options: CacheClearOptions): Promise<void>;
50
+ export declare function runCacheList(options: CacheListOptions): Promise<void>;
51
+ /** Parse-and-validate helper for `set` — surfaces a clean error on bad input. */
52
+ export declare function parseCacheResult(raw: string): CacheResult;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * `rea cache` — push-review cache operator subcommands (BUG-009).
3
+ *
4
+ * Four verbs:
5
+ * - `check <sha> --branch <b> --base <b>` — JSON to stdout ONLY; never
6
+ * diagnostics. `hooks/push-review-gate.sh` reads this via
7
+ * `printf '%s' "$CACHE_RESULT" | jq -e '.hit == true'`, so any stray
8
+ * text on stdout would poison the hook's JSON parse.
9
+ * - `set <sha> pass|fail --branch <b> --base <b> [--reason <s>]` — record
10
+ * a review outcome.
11
+ * - `clear <sha>` — drop every entry for a sha (dev convenience).
12
+ * - `list [--branch <b>]` — pretty-print entries.
13
+ *
14
+ * The TTL used by `check` reads `review.cache_max_age_seconds` from
15
+ * `.rea/policy.yaml` when present, falling back to
16
+ * {@link DEFAULT_CACHE_MAX_AGE_SECONDS} (1 hour) when the policy file or
17
+ * field is absent. An unreadable/malformed policy file is NOT fatal for
18
+ * `check` — it degrades to the default so a broken policy never deadlocks
19
+ * the push gate; other commands that don't consume the TTL ignore the policy
20
+ * entirely.
21
+ */
22
+ import { loadPolicy } from '../policy/loader.js';
23
+ import { DEFAULT_CACHE_MAX_AGE_SECONDS, appendEntry, clear as clearEntries, list as listEntries, lookup, } from '../cache/review-cache.js';
24
+ import { err, log } from './utils.js';
25
+ function resolveMaxAgeSeconds(baseDir) {
26
+ try {
27
+ const policy = loadPolicy(baseDir);
28
+ const configured = policy.review?.cache_max_age_seconds;
29
+ if (typeof configured === 'number' && configured > 0)
30
+ return configured;
31
+ return DEFAULT_CACHE_MAX_AGE_SECONDS;
32
+ }
33
+ catch {
34
+ // Missing or malformed policy must not block the push gate — degrade to
35
+ // the default. `rea doctor` is the canonical surface for flagging a
36
+ // broken policy file; the cache is not the place to re-diagnose it.
37
+ return DEFAULT_CACHE_MAX_AGE_SECONDS;
38
+ }
39
+ }
40
+ /**
41
+ * Print the cache-check JSON to stdout. Hook contract: stdout is ONLY JSON.
42
+ * On a miss we still exit 0 with `{"hit":false}` — the hook interprets
43
+ * non-zero as "rea broken, force re-review" via its `|| echo '{"hit":false}'`
44
+ * fallback.
45
+ */
46
+ export async function runCacheCheck(options) {
47
+ const baseDir = process.cwd();
48
+ const maxAgeSeconds = resolveMaxAgeSeconds(baseDir);
49
+ const result = await lookup(baseDir, {
50
+ sha: options.sha,
51
+ branch: options.branch,
52
+ base: options.base,
53
+ maxAgeSeconds,
54
+ });
55
+ if (result.hit && result.entry !== undefined) {
56
+ const payload = {
57
+ hit: true,
58
+ result: result.entry.result,
59
+ branch: result.entry.branch,
60
+ base: result.entry.base,
61
+ recorded_at: result.entry.recorded_at,
62
+ ...(result.entry.reason !== undefined ? { reason: result.entry.reason } : {}),
63
+ };
64
+ process.stdout.write(JSON.stringify(payload) + '\n');
65
+ return;
66
+ }
67
+ process.stdout.write(JSON.stringify({ hit: false }) + '\n');
68
+ }
69
+ export async function runCacheSet(options) {
70
+ const baseDir = process.cwd();
71
+ const entry = await appendEntry(baseDir, {
72
+ sha: options.sha,
73
+ branch: options.branch,
74
+ base: options.base,
75
+ result: options.result,
76
+ ...(options.reason !== undefined && options.reason.length > 0
77
+ ? { reason: options.reason }
78
+ : {}),
79
+ });
80
+ log(`Recorded ${entry.result} for ${entry.sha.slice(0, 12)} (${entry.branch} → ${entry.base}).`);
81
+ }
82
+ export async function runCacheClear(options) {
83
+ const baseDir = process.cwd();
84
+ const removed = await clearEntries(baseDir, options.sha);
85
+ if (removed === 0) {
86
+ log(`No entries found for ${options.sha.slice(0, 12)}.`);
87
+ return;
88
+ }
89
+ log(`Cleared ${removed} entr${removed === 1 ? 'y' : 'ies'} for ${options.sha.slice(0, 12)}.`);
90
+ }
91
+ export async function runCacheList(options) {
92
+ const baseDir = process.cwd();
93
+ const entries = await listEntries(baseDir, {
94
+ ...(options.branch !== undefined ? { branch: options.branch } : {}),
95
+ });
96
+ if (entries.length === 0) {
97
+ log('No review-cache entries.');
98
+ return;
99
+ }
100
+ for (const e of entries) {
101
+ const shortSha = e.sha.slice(0, 12);
102
+ const reason = e.reason !== undefined ? ` — ${e.reason}` : '';
103
+ console.log(`${e.recorded_at} ${e.result.padEnd(4)} ${shortSha} ${e.branch} → ${e.base}${reason}`);
104
+ }
105
+ }
106
+ /** Parse-and-validate helper for `set` — surfaces a clean error on bad input. */
107
+ export function parseCacheResult(raw) {
108
+ if (raw === 'pass' || raw === 'fail')
109
+ return raw;
110
+ err(`result must be 'pass' or 'fail'; got ${JSON.stringify(raw)}`);
111
+ process.exit(1);
112
+ }
package/dist/cli/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from 'commander';
3
3
  import { runAuditRotate, runAuditVerify } from './audit.js';
4
+ import { parseCacheResult, runCacheCheck, runCacheClear, runCacheList, runCacheSet, } from './cache.js';
4
5
  import { runCheck } from './check.js';
5
6
  import { runDoctor } from './doctor.js';
6
7
  import { runFreeze, runUnfreeze } from './freeze.js';
@@ -101,6 +102,46 @@ async function main() {
101
102
  .action(async (opts) => {
102
103
  await runAuditVerify({ ...(opts.since !== undefined ? { since: opts.since } : {}) });
103
104
  });
105
+ const cache = program
106
+ .command('cache')
107
+ .description('Review-cache operations — check/set/clear/list .rea/review-cache.jsonl (BUG-009). Used by hooks/push-review-gate.sh to skip re-review on a previously-approved diff.');
108
+ cache
109
+ .command('check <sha>')
110
+ .description('Look up a cache entry. Emits JSON to stdout ONLY — hook contract. On hit: {hit,true,result,branch,base,recorded_at[,reason]}. On miss: {hit:false}. Never exits non-zero for normal miss.')
111
+ .requiredOption('--branch <branch>', 'feature branch being pushed')
112
+ .requiredOption('--base <base>', 'base branch the feature targets')
113
+ .action(async (sha, opts) => {
114
+ await runCacheCheck({ sha, branch: opts.branch, base: opts.base });
115
+ });
116
+ cache
117
+ .command('set <sha> <result>')
118
+ .description('Record a review outcome. <result> must be "pass" or "fail". Idempotent line-per-invocation; last write wins on (sha, branch, base).')
119
+ .requiredOption('--branch <branch>', 'feature branch being pushed')
120
+ .requiredOption('--base <base>', 'base branch the feature targets')
121
+ .option('--reason <text>', 'free-text context for this entry (recommended on fail)')
122
+ .action(async (sha, rawResult, opts) => {
123
+ const result = parseCacheResult(rawResult);
124
+ await runCacheSet({
125
+ sha,
126
+ result,
127
+ branch: opts.branch,
128
+ base: opts.base,
129
+ ...(opts.reason !== undefined ? { reason: opts.reason } : {}),
130
+ });
131
+ });
132
+ cache
133
+ .command('clear <sha>')
134
+ .description('Remove every cache entry matching <sha>. Dev convenience — prints the removed count.')
135
+ .action(async (sha) => {
136
+ await runCacheClear({ sha });
137
+ });
138
+ cache
139
+ .command('list')
140
+ .description('Print cache entries in file order. Filter with --branch.')
141
+ .option('--branch <branch>', 'only list entries for this branch')
142
+ .action(async (opts) => {
143
+ await runCacheList({ ...(opts.branch !== undefined ? { branch: opts.branch } : {}) });
144
+ });
104
145
  program
105
146
  .command('doctor')
106
147
  .description('Validate the install: policy parses, .rea/ layout, hooks, Codex plugin.')
package/dist/cli/init.js CHANGED
@@ -5,6 +5,7 @@ import * as p from '@clack/prompts';
5
5
  import { AutonomyLevel } from '../policy/types.js';
6
6
  import { HARD_DEFAULTS, loadProfile, mergeProfiles } from '../policy/profiles.js';
7
7
  import { copyArtifacts } from './install/copy.js';
8
+ import { ensureReaGitignore } from './install/gitignore.js';
8
9
  import { canonicalSettingsSubsetHash, defaultDesiredHooks, mergeSettings, readSettings, writeSettingsAtomic, } from './install/settings-merge.js';
9
10
  import { installCommitMsgHook } from './install/commit-msg.js';
10
11
  import { installPrePushFallback } from './install/pre-push.js';
@@ -464,6 +465,10 @@ export async function runInit(options) {
464
465
  blockAiAttribution: config.blockAiAttribution,
465
466
  };
466
467
  const mdResult = await writeClaudeMdFragment(targetDir, fragmentInput);
468
+ // BUG-010 — scaffold `.gitignore` entries for every runtime artifact
469
+ // `rea serve` / `rea cache` / `/freeze` can write under `.rea/`. Idempotent
470
+ // append (and `rea upgrade` backfills older installs that never got this).
471
+ const gitignoreResult = await ensureReaGitignore(targetDir);
467
472
  // G12 — record the install manifest. SHAs are of the files actually on disk
468
473
  // after the copy pass, so drift detection compares against real state (not
469
474
  // canonical, which may differ if the consumer's copy was aborted mid-run).
@@ -487,6 +492,17 @@ export async function runInit(options) {
487
492
  console.log(` = ${path.relative(targetDir, prePushResult.decision.hookPath)} (active pre-push already present — skipped fallback)`);
488
493
  }
489
494
  console.log(` ${mdResult.replaced ? '~' : '+'} ${path.relative(targetDir, mdResult.path)} (fragment ${mdResult.replaced ? 'replaced' : 'written'})`);
495
+ if (gitignoreResult.action === 'created') {
496
+ console.log(` + ${path.relative(targetDir, gitignoreResult.path)} (managed block written)`);
497
+ }
498
+ else if (gitignoreResult.action === 'updated') {
499
+ console.log(` ~ ${path.relative(targetDir, gitignoreResult.path)} (managed block ${gitignoreResult.addedEntries.length} entr${gitignoreResult.addedEntries.length === 1 ? 'y' : 'ies'} added)`);
500
+ }
501
+ else {
502
+ console.log(` · ${path.relative(targetDir, gitignoreResult.path)} (managed block up to date)`);
503
+ }
504
+ for (const w of gitignoreResult.warnings)
505
+ warn(w);
490
506
  console.log(` + ${path.relative(targetDir, manifestPath)}`);
491
507
  if (mergeResult.warnings.length > 0) {
492
508
  console.log('');