@chrono-meta/fh-gate 3.26.1 → 3.27.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,270 @@
1
+ #!/usr/bin/env python3
2
+ """memory_gc_report.py — read-only lifecycle report for a Claude Code memory directory.
3
+
4
+ WHY: MEMORY.md is a capped overview (the loader stops at ~25,000 chars and silently drops the
5
+ rest), but nothing decides WHICH entries stay above the cap. Ordering by recency pushes
6
+ long-confirmed feedback below the cut, and recurrence lived only in prose ("하루 3회"), so no
7
+ machine could rank by it. Generational-GC framing (imweb tech, 2026-10-06): an entry's AGE rises
8
+ only when the same observation is recorded again; recurrence across several days marks a
9
+ promotion candidate.
10
+
11
+ WHAT: reads every topic file's frontmatter and the index, and reports
12
+ · index hygiene — unlisted files · duplicate index lines · dangling local links
13
+ · loader cap — the character offset where the cap cuts, and the line it falls in
14
+ · every entry — status, type, age (from `metadata.hits`), distinct days, last hit, index line
15
+ · cold — non-user, age 1, last hit ≥ --cold-days ago → drop from the INDEX only
16
+ · promote — age ≥ --promote-age across ≥ 2 distinct days → propose a rule/hook (human approves)
17
+ · order — user entries in index order, then valid measured entries by age (ties: index
18
+ order), then the rest in index order; cold entries leave the order. Entries with an
19
+ error status never drive cold / promote / measured ranking until repaired
20
+
21
+ INVARIANTS:
22
+ · Read-only. It never edits, moves or deletes anything.
23
+ · No `hits` = UNMEASURED, never age 1, never cold. A rule that is followed well also stops
24
+ recurring; absence of a record is not a zero.
25
+ · Unreadable files, missing/unterminated frontmatter, inline or malformed `hits`, invalid or
26
+ future dates are reported as such (status / bad lines) — never folded into "no hits".
27
+ · Same-day repeats count once toward the distinct-days condition.
28
+
29
+ `hits` format (a child of the frontmatter `metadata:` block; one occurrence per item, first = founding):
30
+ metadata:
31
+ hits:
32
+ - 2026-10-15 | live lane windows covered the operator's screen
33
+ usage: memory_gc_report.py <memory_dir> [--index MEMORY.md] [--today YYYY-MM-DD]
34
+ [--cold-days 30] [--promote-age 3] [--cap 25000] [--json]
35
+ exit: 0 report printed · 2 memory dir or index unreadable (instrument error, never an empty report)
36
+ """
37
+ import argparse, datetime as dt, json, os, re, sys, urllib.parse
38
+
39
+ def link_dests(line):
40
+ """Markdown inline-link destinations with their start offset: <...> form, balanced parens, title dropped."""
41
+ out, i = [], 0
42
+ while True:
43
+ j = line.find('](', i)
44
+ if j < 0:
45
+ return out
46
+ k = j + 2
47
+ while k < len(line) and line[k] == ' ':
48
+ k += 1
49
+ start = k
50
+ if k < len(line) and line[k] == '<':
51
+ e = line.find('>', k + 1)
52
+ if e < 0:
53
+ i = j + 2; continue
54
+ out.append((line[k + 1:e], start)); i = e + 1; continue
55
+ depth, d = 0, k
56
+ while d < len(line):
57
+ c = line[d]
58
+ if c == '(':
59
+ depth += 1
60
+ elif c == ')':
61
+ if depth == 0:
62
+ break
63
+ depth -= 1
64
+ elif c in ' \t' and depth == 0:
65
+ break
66
+ d += 1
67
+ if d > k:
68
+ out.append((line[k:d], start))
69
+ i = d
70
+ HIT_RE = re.compile(r'^-\s*(\S+)\s*\|\s*(.+?)\s*$')
71
+
72
+
73
+ def indent(line):
74
+ return len(line) - len(line.lstrip(' '))
75
+
76
+
77
+ def parse_entry(path, today):
78
+ """-> dict(status, type, hits[(date,str)], bad[str])"""
79
+ out = {'status': 'OK', 'type': None, 'hits': [], 'bad': []}
80
+ try:
81
+ text = open(path, encoding='utf-8').read()
82
+ except (OSError, UnicodeDecodeError) as e:
83
+ out['status'] = 'READ_ERROR'
84
+ out['bad'].append(type(e).__name__)
85
+ return out
86
+ lines = text.splitlines()
87
+ if not lines or lines[0].strip() != '---':
88
+ out['status'] = 'NO_FRONTMATTER'
89
+ return out
90
+ try:
91
+ end = next(i for i in range(1, len(lines)) if lines[i].strip() == '---')
92
+ except StopIteration:
93
+ out['status'] = 'UNTERMINATED_FRONTMATTER'
94
+ return out
95
+ fm = lines[1:end]
96
+ meta_i = next((i for i, l in enumerate(fm) if indent(l) == 0 and re.match(r'^metadata:\s*$', l)), None)
97
+ if meta_i is None:
98
+ return out
99
+ meta = []
100
+ for l in fm[meta_i + 1:]:
101
+ if l.strip() and not l.lstrip().startswith('#') and indent(l) == 0:
102
+ break
103
+ meta.append(l)
104
+ child = min((indent(l) for l in meta if l.strip() and not l.lstrip().startswith('#')), default=None)
105
+ hits_i = None
106
+ for i, l in enumerate(meta):
107
+ if not l.strip() or l.lstrip().startswith('#'):
108
+ continue
109
+ if indent(l) == child:
110
+ m = re.match(r'^\s*type:\s*(.*)$', l)
111
+ if m and out['type'] is None:
112
+ out['type'] = m.group(1).strip().strip('"\'') or None
113
+ if re.match(r'^\s*hits:', l):
114
+ if re.match(r'^\s*hits:\s*$', l):
115
+ hits_i = i
116
+ else:
117
+ out['status'] = 'HITS_MALFORMED'
118
+ out['bad'].append(l.strip())
119
+ if hits_i is None:
120
+ return out
121
+ hind = indent(meta[hits_i])
122
+ for l in meta[hits_i + 1:]:
123
+ if not l.strip() or l.lstrip().startswith('#'):
124
+ continue
125
+ if indent(l) == hind and l.lstrip().startswith('- '):
126
+ out['bad'].append(l.strip() + ' (indentless list item — indent it under hits:)')
127
+ continue
128
+ if indent(l) <= hind:
129
+ break
130
+ s = l.strip()
131
+ m = HIT_RE.match(s)
132
+ if not m:
133
+ out['bad'].append(s)
134
+ continue
135
+ try:
136
+ d = dt.date.fromisoformat(m.group(1))
137
+ except ValueError:
138
+ out['bad'].append(s)
139
+ continue
140
+ if d > today:
141
+ out['bad'].append(s + ' (future date)')
142
+ continue
143
+ out['hits'].append((d.isoformat(), m.group(2)))
144
+ if out['bad'] and out['status'] == 'OK':
145
+ out['status'] = 'HITS_MALFORMED'
146
+ return out
147
+
148
+
149
+ def local_target(dest, index_dir):
150
+ if re.match(r'^[a-zA-Z][a-zA-Z0-9+.-]*:', dest): # https:, mailto:, file: …
151
+ return None
152
+ dest = urllib.parse.unquote(dest.split('#', 1)[0].split('?', 1)[0])
153
+ if not dest.endswith('.md'):
154
+ return None
155
+ return os.path.normpath(dest)
156
+
157
+
158
+ def main():
159
+ ap = argparse.ArgumentParser()
160
+ ap.add_argument('memory_dir')
161
+ ap.add_argument('--index', default='MEMORY.md')
162
+ ap.add_argument('--today')
163
+ ap.add_argument('--cold-days', type=int, default=30)
164
+ ap.add_argument('--promote-age', type=int, default=3)
165
+ ap.add_argument('--cap', type=int, default=25000)
166
+ ap.add_argument('--json', action='store_true')
167
+ a = ap.parse_args()
168
+
169
+ idx_path = os.path.join(a.memory_dir, a.index)
170
+ try:
171
+ names = sorted(f for f in os.listdir(a.memory_dir) if f.endswith('.md') and f != a.index)
172
+ idx_text = open(idx_path, encoding='utf-8').read()
173
+ except (OSError, UnicodeDecodeError) as e:
174
+ print(f'HARNESS-ERROR: {e}', file=sys.stderr)
175
+ return 2
176
+ today = dt.date.fromisoformat(a.today) if a.today else dt.date.today()
177
+
178
+ # loader cap: character offset, and the line it falls in (prefix of that line is still loaded)
179
+ cut = None
180
+ if len(idx_text) > a.cap:
181
+ line_no = idx_text.count('\n', 0, a.cap) + 1
182
+ line_start = idx_text.rfind('\n', 0, a.cap) + 1
183
+ cut = {'char': a.cap, 'line': line_no, 'chars_loaded_in_line': a.cap - line_start}
184
+ pos, dups, dangling, offset = {}, [], [], 0
185
+ for i, line in enumerate(idx_text.splitlines(keepends=True), 1):
186
+ for dest, at in link_dests(line):
187
+ t = local_target(dest, a.memory_dir)
188
+ if t is None:
189
+ continue
190
+ if not os.path.isfile(os.path.join(a.memory_dir, t)):
191
+ dangling.append([t, i])
192
+ continue
193
+ if t in pos:
194
+ dups.append([t, pos[t]['line'], i])
195
+ else:
196
+ pos[t] = {'line': i, 'ord': len(pos), 'past_cap': cut is not None and offset + at >= a.cap}
197
+ offset += len(line)
198
+
199
+ entries = []
200
+ for n in names:
201
+ p = parse_entry(os.path.join(a.memory_dir, n), today)
202
+ e = {'file': n, 'status': p['status'], 'type': p['type'], 'bad': p['bad'],
203
+ 'index_line': pos.get(n, {}).get('line'), 'index_ord': pos.get(n, {}).get('ord'),
204
+ 'past_cap': pos.get(n, {}).get('past_cap', False)}
205
+ if p['hits']:
206
+ days = sorted({d for d, _ in p['hits']})
207
+ e.update(age=len(p['hits']), distinct_days=len(days), last_hit=days[-1])
208
+ else:
209
+ e.update(age=None, distinct_days=None, last_hit=None) # UNMEASURED, not age 1
210
+ entries.append(e)
211
+
212
+ def days_since(d):
213
+ return (today - dt.date.fromisoformat(d)).days
214
+
215
+ ok = lambda e: e['status'] == 'OK'
216
+ cold = [e for e in entries if ok(e) and e['type'] != 'user' and e['age'] == 1
217
+ and days_since(e['last_hit']) >= a.cold_days]
218
+ promote = [e for e in entries if ok(e) and e['age'] is not None and e['age'] >= a.promote_age
219
+ and e['distinct_days'] >= 2]
220
+ cold_set = {e['file'] for e in cold}
221
+ listed = sorted((e for e in entries if e['index_line'] is not None), key=lambda e: e['index_ord'])
222
+ users = [e for e in listed if e['type'] == 'user']
223
+ meas = sorted((e for e in listed if e['type'] != 'user' and ok(e) and e['age'] is not None and e['file'] not in cold_set),
224
+ key=lambda e: (-e['age'], e['index_ord'])) # age ties keep index (link) order
225
+ rest = [e for e in listed if e['type'] != 'user' and not (ok(e) and e['age'] is not None)]
226
+ order = [e['file'] for e in users + meas + rest]
227
+
228
+ rep = {'memory_dir': a.memory_dir, 'today': today.isoformat(), 'files': len(entries),
229
+ 'index_chars': len(idx_text), 'cap': a.cap, 'cut': cut,
230
+ 'unlisted': [e['file'] for e in entries if e['index_line'] is None],
231
+ 'duplicates': dups, 'dangling': dangling,
232
+ 'measured': sum(e['age'] is not None for e in entries),
233
+ 'unmeasured': sum(e['age'] is None for e in entries),
234
+ 'errors': [[e['file'], e['status'], e['bad']] for e in entries if e['status'] != 'OK'],
235
+ 'cold': [e['file'] for e in cold],
236
+ 'promote': [[e['file'], e['age'], e['distinct_days']] for e in promote],
237
+ 'order': order, 'entries': entries}
238
+ if a.json:
239
+ print(json.dumps(rep, ensure_ascii=False, indent=1))
240
+ return 0
241
+ cut_s = 'within cap' if cut is None else f"cap cuts at char {cut['char']} = line {cut['line']} (first {cut['chars_loaded_in_line']} chars of it load)"
242
+ print(f"memory GC report — {rep['files']} topic files · index {len(idx_text)} chars, {cut_s} · today {rep['today']}")
243
+ print(f" index: unlisted {len(rep['unlisted'])} · duplicate lines {len(dups)} · dangling local links {len(dangling)}")
244
+ for t, first, again in dups:
245
+ print(f" dup {t} (lines {first} and {again})")
246
+ for t, ln in dangling:
247
+ print(f" dangling {t} (line {ln})")
248
+ print(f" errors (not folded into 'no hits'): {len(rep['errors'])}")
249
+ for f, st, bad in rep['errors']:
250
+ print(f" {st:<24} {f} {'; '.join(bad)[:120]}")
251
+ print(f" age: measured {rep['measured']} · UNMEASURED {rep['unmeasured']} (no `hits` — never age 1, never cold)")
252
+ for e in sorted(entries, key=lambda e: (e['age'] is None, -(e['age'] or 0), e['file'])):
253
+ age = 'UNMEAS' if e['age'] is None else f"age {e['age']:>2}"
254
+ print(f" {age} · {e['type'] or '-'} · {e['status']} · days {e['distinct_days']} · last {e['last_hit']} · "
255
+ f"{'line ' + str(e['index_line']) if e['index_line'] else 'unlisted'}{' (past cap)' if e['past_cap'] else ''} · {e['file']}")
256
+ print(f" cold (non-user, age 1, no recurrence for ≥ {a.cold_days}d → drop from index only, keep file): {len(cold)}")
257
+ for e in cold:
258
+ print(f" cold {e['file']} last {e['last_hit']}")
259
+ print(f" promote candidates (age ≥ {a.promote_age} over ≥ 2 days → propose rule/hook, human approves): {len(promote)}")
260
+ for e in promote:
261
+ print(f" promote {e['file']} age {e['age']} · days {e['distinct_days']} · last {e['last_hit']}")
262
+ print(f" proposed order ({len(order)}):")
263
+ for n, f in enumerate(order, 1):
264
+ print(f" {n:>3}. {f}")
265
+ print(' read-only: nothing was changed.')
266
+ return 0
267
+
268
+
269
+ if __name__ == '__main__':
270
+ sys.exit(main())
@@ -990,6 +990,7 @@ for _pair in \
990
990
  "templates/.git-hooks/pre-commit|scripts/test_marker_crossfamily_lanes.sh" \
991
991
  "templates/.git-hooks/pre-commit|scripts/test_marker_floor_lanes.sh" \
992
992
  ".github/workflows/regression-guard.yml|scripts/test_regression_guard_ci_lanes.sh" \
993
+ "templates/regression_guard.sh|scripts/test_regression_guard_sibling_lanes.sh" \
993
994
  ".github/workflows/validate.yml|scripts/test_leak_scan_control_lanes.sh" \
994
995
  "templates/.git-hooks/pre-commit|scripts/test_marker_standpoint_lanes.sh" \
995
996
  "templates/.git-hooks/pre-commit|scripts/test_marker_thirdparty_lanes.sh" \
@@ -2101,6 +2102,32 @@ else
2101
2102
  fail=1
2102
2103
  fi
2103
2104
 
2105
+ # env-delta SessionStart hook — linked worktrees are not new sibling repos (2026-10-15: 30 of 33
2106
+ # «unmapped siblings» were worktrees). Same pairing rule as above.
2107
+ if [ ! -f scripts/fh_env_delta_scan.sh ]; then
2108
+ _absent_subject_verdict "test_env_delta_worktree_lanes.sh" "scripts/fh_env_delta_scan.sh" || fail=1
2109
+ elif [ -f scripts/test_env_delta_worktree_lanes.sh ]; then
2110
+ if ! bash scripts/test_env_delta_worktree_lanes.sh; then
2111
+ fail=1
2112
+ fi
2113
+ else
2114
+ echo "FAIL test_env_delta_worktree_lanes.sh: fh_env_delta_scan.sh present but its anchor is missing"
2115
+ fail=1
2116
+ fi
2117
+
2118
+ # memory_gc_report.py — read-only lifecycle report over a memory dir (age from `hits`, cold, promote,
2119
+ # index hygiene, loader cap). Same pairing rule as above.
2120
+ if [ ! -f scripts/memory_gc_report.py ]; then
2121
+ _absent_subject_verdict "test_memory_gc_report_lanes.sh" "scripts/memory_gc_report.py" || fail=1
2122
+ elif [ -f scripts/test_memory_gc_report_lanes.sh ]; then
2123
+ if ! bash scripts/test_memory_gc_report_lanes.sh; then
2124
+ fail=1
2125
+ fi
2126
+ else
2127
+ echo "FAIL test_memory_gc_report_lanes.sh: memory_gc_report.py present but its anchor is missing"
2128
+ fail=1
2129
+ fi
2130
+
2104
2131
  # SessionStart multi-hook + install-wizard snippet merge. Subject for both = the shipped settings
2105
2132
  # snippets; a clone without them is a legitimate SKIP, a clone with them and no anchor is not —
2106
2133
  # UNLESS the anchor itself is declared package-mode-optional. test_sessionstart_multihook_lanes.sh
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env bash
2
+ # test_env_delta_worktree_lanes.sh — lanes for the linked-worktree rule in scripts/fh_env_delta_scan.sh.
3
+ #
4
+ # WHY: 2026-10-15 the SessionStart hook reported «33 unmapped sibling repos»; 30 of them were linked
5
+ # worktrees of repos the hub already knows (friends-on-desk, qasp-dev, clawd-on-desk, the hub itself).
6
+ # A worktree is another checkout of its main repo, not a new project. These lanes pin both sides:
7
+ # - a linked worktree is NOT counted as a sibling (the fix)
8
+ # - its unmapped main repo IS still counted (known-positive — the fix must not hide real repos)
9
+ # - a `.git` FILE that is not a worktree pointer (submodule shape) still counts (old behaviour kept)
10
+ # - cwd inside a worktree of a MAPPED repo → silent; of an UNMAPPED repo → names the main repo
11
+ set -u
12
+ HERE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
13
+ SCAN="$HERE/fh_env_delta_scan.sh"
14
+ [ -f "$SCAN" ] || { echo "FAIL subject missing: $SCAN"; exit 1; }
15
+ command -v git >/dev/null 2>&1 || { echo "FAIL git not on PATH — lanes cannot build fixtures"; exit 1; }
16
+
17
+ T="$(mktemp -d "${TMPDIR:-/tmp}/fh_envdelta_wt.XXXXXX")"
18
+ trap 'rm -rf "$T"' EXIT
19
+ ROOT="$T/projects"; HUB="$ROOT/hub"; SENT="$T/sent"
20
+ mkdir -p "$HUB/tracks/beta" "$HUB/scripts" "$SENT"
21
+ cp "$SCAN" "$HUB/scripts/"; [ -f "$HERE/hook_source_lib.sh" ] && cp "$HERE/hook_source_lib.sh" "$HUB/scripts/"
22
+
23
+ _repo() { git init -q "$1" && git -C "$1" -c user.email=t@t -c user.name=t commit -q --allow-empty -m init; }
24
+ _repo "$ROOT/alpha" # unmapped main repo
25
+ _repo "$ROOT/beta" # mapped main repo (tracks/beta)
26
+ git -C "$ROOT/alpha" worktree add -q "$ROOT/alpha-wt" -b wt-a 2>/dev/null
27
+ git -C "$ROOT/beta" worktree add -q "$ROOT/beta-wt" -b wt-b 2>/dev/null
28
+ mkdir -p "$ROOT/gamma"; printf 'gitdir: %s\n' "$T/elsewhere/.git/modules/gamma" > "$ROOT/gamma/.git" # submodule shape
29
+
30
+ FAILED=0; PASSED=0
31
+ _pass() { echo "✅ $1"; PASSED=$((PASSED+1)); }
32
+ _fail() { echo "❌ $1"; FAILED=1; }
33
+ _run() { # $1 = cwd to report as CLAUDE_PROJECT_DIR
34
+ printf '{"source":"startup"}' | HUB_DIR="$HUB" FH_PROJECTS_ROOT="$ROOT" CC_SENTINEL_DIR="$SENT" \
35
+ CLAUDE_PROJECT_DIR="$1" bash "$HUB/scripts/fh_env_delta_scan.sh" 2>&1
36
+ }
37
+
38
+ # Fixture sanity: the worktrees really are worktrees (else every lane below is vacuous).
39
+ for w in alpha-wt beta-wt; do
40
+ grep -q '/.git/worktrees/' "$ROOT/$w/.git" 2>/dev/null && _pass "fixture: $w is a linked worktree" \
41
+ || _fail "fixture: $w is not a linked worktree — lanes would be vacuous"
42
+ done
43
+
44
+ OUT="$(_run "$HUB")"
45
+ case "$OUT" in *"2 unmapped sibling repo(s)"*) _pass "siblings: count = 2 (alpha + gamma)";;
46
+ *) _fail "siblings: expected «2 unmapped sibling repo(s)», got: $(printf '%s' "$OUT" | tr '\n' ' ')";; esac
47
+
48
+ OUT="$(_run "$ROOT/beta-wt")"
49
+ case "$OUT" in *"current cwd"*) _fail "cwd in worktree of MAPPED repo: should be silent, got cwd line";;
50
+ *) _pass "cwd in worktree of mapped repo → no cwd line";; esac
51
+
52
+ OUT="$(_run "$ROOT/alpha-wt")"
53
+ case "$OUT" in *"current cwd 'alpha'"*) _pass "cwd in worktree of UNMAPPED repo → names main repo 'alpha'";;
54
+ *) _fail "cwd in worktree of unmapped repo: expected «current cwd 'alpha'», got: $(printf '%s' "$OUT" | tr '\n' ' ')";; esac
55
+
56
+ OUT="$(_run "$ROOT/gamma")"
57
+ case "$OUT" in *"current cwd 'gamma'"*) _pass "submodule-shape .git file still counts (cwd 'gamma')";;
58
+ *) _fail "submodule-shape .git file no longer counts";; esac
59
+
60
+ if [ "$FAILED" -ne 0 ]; then echo "ENV-DELTA WORKTREE LANES: FAIL ($PASSED passed)"; exit 1; fi
61
+ echo "ENV-DELTA WORKTREE LANES: PASS ($PASSED lanes)"
@@ -0,0 +1,210 @@
1
+ #!/usr/bin/env bash
2
+ # test_memory_gc_report_lanes.sh — known-pair lanes for scripts/memory_gc_report.py
3
+ # Every lane asserts an EXACT value or an exact collection (codex R1 2026-10-15: prefix / presence
4
+ # checks stayed green under 4 mutants). Fixtures carry their own negative next to each positive.
5
+ set -u
6
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7
+ PY="${PYTHON:-python3}"
8
+ T="$(mktemp -d)"; trap 'rm -rf "$T"' EXIT
9
+ pass=0; fail=0
10
+ eq(){ if [ "$2" = "$3" ]; then echo "PASS $1"; pass=$((pass+1)); else echo "FAIL $1 — got [$2] want [$3]"; fail=$((fail+1)); fi; }
11
+
12
+ M="$T/m"; mkdir -p "$M"
13
+ w(){ printf '%s\n' "$2" > "$M/$1"; }
14
+ hdr='---
15
+ name: x
16
+ description: fixture
17
+ metadata:'
18
+ w user_z.md "$hdr
19
+ type: user
20
+ ---
21
+ body"
22
+ w user_a.md "$hdr
23
+ type: user
24
+ hits:
25
+ - 2026-01-01 | old founding, user entries never go cold
26
+ ---
27
+ body"
28
+ w fb_promote.md "$hdr
29
+ type: feedback
30
+ hits:
31
+ - 2026-10-01 | first
32
+
33
+ # a comment inside the list must not end it
34
+ - 2026-10-01 | same day again
35
+ - 2026-10-05 | other day
36
+ ---
37
+ body"
38
+ w fb_two_two.md "$hdr
39
+ type: feedback
40
+ hits:
41
+ - 2026-10-03 | a
42
+ - 2026-10-04 | b
43
+ ---
44
+ body"
45
+ w fb_sameday.md "$hdr
46
+ type: feedback
47
+ hits:
48
+ - 2026-10-02 | a
49
+ - 2026-10-02 | b
50
+ - 2026-10-02 | c
51
+ ---
52
+ body"
53
+ w fb_cold.md "$hdr
54
+ type: feedback
55
+ hits:
56
+ - 2026-09-15 | exactly 30 days before today
57
+ ---
58
+ body"
59
+ w fb_fresh.md "$hdr
60
+ type: feedback
61
+ hits:
62
+ - 2026-09-16 | 29 days, not cold yet
63
+ ---
64
+ body"
65
+ w fb_unmeasured.md "$hdr
66
+ type: feedback
67
+ ---
68
+ body"
69
+ w fb_unlisted.md "$hdr
70
+ type: feedback
71
+ ---
72
+ body"
73
+ w fb_baddate.md "$hdr
74
+ type: feedback
75
+ hits:
76
+ - 2026-99-99 | impossible
77
+ - 2026-99-98 | impossible
78
+ - 2026-99-97 | impossible
79
+ ---
80
+ body"
81
+ w fb_future.md "$hdr
82
+ type: feedback
83
+ hits:
84
+ - 2027-01-01 | future
85
+ ---
86
+ body"
87
+ w fb_inline.md "$hdr
88
+ type: feedback
89
+ hits: [bad]
90
+ ---
91
+ body"
92
+ w fb_foreign.md "---
93
+ name: x
94
+ other:
95
+ hits:
96
+ - 2026-10-01 | not under metadata
97
+ metadata:
98
+ type: feedback
99
+ ---
100
+ body"
101
+ w fb_unterm.md "---
102
+ name: x
103
+ metadata:
104
+ type: feedback
105
+ hits:
106
+ - 2026-10-01 | never closed"
107
+ mkdir "$M/fb_dir.md"
108
+ w MEMORY.md "# Memory Index
109
+ - [Z](user_z.md) — user listed first
110
+ - [A](user_a.md) — user listed second
111
+ - [S](fb_sameday.md \"titled\") — titled link
112
+ - [P](./fb_promote.md) — dot-slash link
113
+ - [T](fb_two_two.md#part) — fragment link
114
+ - [C](fb_cold.md)
115
+ - [F](fb_fresh.md)
116
+ - [N](fb_unmeasured.md)
117
+ - [B](fb_baddate.md)
118
+ - [U](fb_future.md)
119
+ - [I](fb_inline.md)
120
+ - [O](fb_foreign.md)
121
+ - [X](fb_unterm.md)
122
+ - [web](https://example.com/page.md) — external, not a local file
123
+ - [P again](fb_promote.md) — duplicate
124
+ - [gone](fb_missing.md#sec) — dangling with fragment"
125
+
126
+ J="$(python3 "$HERE/memory_gc_report.py" "$M" --today 2026-10-15 --json)"; rc=$?
127
+ q(){ printf '%s' "$J" | "$PY" -c "import json,sys;d=json.load(sys.stdin);E={e['file']:e for e in d['entries']};print($1)"; }
128
+
129
+ eq "L0 report runs" "$rc" 0
130
+ eq "L1 promote = exactly age≥3 over ≥2 days (2-hit/2-day and same-day x3 excluded)" "$(q "d['promote']")" "[['fb_promote.md', 3, 2]]"
131
+ eq "L2 blank line + comment inside hits do not truncate the list" "$(q "E['fb_promote.md']['age']")" 3
132
+ eq "L3 cold = non-user age 1 at ≥30 days (29 days and old user entry stay)" "$(q "d['cold']")" "['fb_cold.md']"
133
+ eq "L4 no hits = UNMEASURED (age None), not age 1" "$(q "E['fb_unmeasured.md']['age']")" None
134
+ eq "L5 hits outside metadata are ignored" "$(q "E['fb_foreign.md']['age']")" None
135
+ eq "L6 impossible dates never measure or promote" "$(q "(E['fb_baddate.md']['age'], E['fb_baddate.md']['status'], len(E['fb_baddate.md']['bad']))")" "(None, 'HITS_MALFORMED', 3)"
136
+ eq "L7 future date rejected" "$(q "(E['fb_future.md']['age'], E['fb_future.md']['status'])")" "(None, 'HITS_MALFORMED')"
137
+ eq "L8 inline hits flagged" "$(q "E['fb_inline.md']['status']")" HITS_MALFORMED
138
+ eq "L9 unterminated frontmatter flagged" "$(q "E['fb_unterm.md']['status']")" UNTERMINATED_FRONTMATTER
139
+ eq "L10 unreadable topic flagged, not folded into no-hits" "$(q "E['fb_dir.md']['status']")" READ_ERROR
140
+ eq "L11 errors list is exact" "$(q "sorted(x[0] for x in d['errors'])")" "['fb_baddate.md', 'fb_dir.md', 'fb_future.md', 'fb_inline.md', 'fb_unterm.md']"
141
+ eq "L12 ./ , titled and #fragment links resolve; only the real orphan is unlisted" "$(q "sorted(d['unlisted'])")" "['fb_dir.md', 'fb_unlisted.md']"
142
+ eq "L13 duplicate reported with both line numbers" "$(q "d['duplicates']")" "[['fb_promote.md', 5, 16]]"
143
+ eq "L14 dangling local link (fragment stripped); external https ignored" "$(q "d['dangling']")" "[['fb_missing.md', 17]]"
144
+ eq "L15 full order: users in index order, measured by age (ties index order), rest in index order, cold out" \
145
+ "$(q "d['order']")" \
146
+ "['user_z.md', 'user_a.md', 'fb_sameday.md', 'fb_promote.md', 'fb_two_two.md', 'fb_fresh.md', 'fb_unmeasured.md', 'fb_baddate.md', 'fb_future.md', 'fb_inline.md', 'fb_foreign.md', 'fb_unterm.md']"
147
+ eq "L16 every topic file has an entry" "$(q "len(d['entries'])")" 15
148
+
149
+ # cap boundary: an index that fits exactly is within cap; one char over names the line and the loaded prefix
150
+ C="$T/c"; mkdir -p "$C"; printf '[a](a.md)' > "$C/MEMORY.md"; printf -- '---\nmetadata:\n type: feedback\n---\n' > "$C/a.md"
151
+ eq "L17 exact-fit index is within cap" "$(python3 "$HERE/memory_gc_report.py" "$C" --cap 9 --json | "$PY" -c "import json,sys;print(json.load(sys.stdin)['cut'])")" None
152
+ printf 'line one\n[a](a.md)\n' > "$C/MEMORY.md"
153
+ eq "L18 cut names line 2 with 3 chars loaded" "$(python3 "$HERE/memory_gc_report.py" "$C" --cap 12 --json | "$PY" -c "import json,sys;c=json.load(sys.stdin)['cut'];print(c['line'],c['chars_loaded_in_line'])")" "2 3"
154
+
155
+ python3 "$HERE/memory_gc_report.py" "$T/nope" >/dev/null 2>&1; eq "L19 missing dir = HARNESS-ERROR rc=2, not an empty report" "$?" 2
156
+ before="$(cd "$M" && find . -type f -exec cksum {} + | sort)"; python3 "$HERE/memory_gc_report.py" "$M" >/dev/null 2>&1; after="$(cd "$M" && find . -type f -exec cksum {} + | sort)"
157
+ eq "L20 read-only: fixture bytes unchanged" "$before" "$after"
158
+
159
+ # R2 fixtures (codex R2): mixed validity never drives lifecycle · indentless list flagged ·
160
+ # <...> / %20 / balanced-paren destinations · past_cap by the link's own offset
161
+ R="$T/r"; mkdir -p "$R"
162
+ rw(){ printf '%s\n' "$2" > "$R/$1"; }
163
+ rw mix_cold.md "$hdr
164
+ type: feedback
165
+ hits:
166
+ - 2026-08-01 | valid old
167
+ - 2027-01-01 | future
168
+ ---"
169
+ rw mix_prom.md "$hdr
170
+ type: feedback
171
+ hits:
172
+ - 2026-10-01 | a
173
+ - 2026-10-02 | b
174
+ - 2026-10-03 | c
175
+ - nonsense line
176
+ ---"
177
+ rw flat.md "$hdr
178
+ type: feedback
179
+ hits:
180
+ - 2026-10-01 | indentless
181
+ ---"
182
+ rw "my note.md" "$hdr
183
+ type: feedback
184
+ ---"
185
+ rw "sp name.md" "$hdr
186
+ type: feedback
187
+ ---"
188
+ rw "note(v2).md" "$hdr
189
+ type: feedback
190
+ ---"
191
+ rw MEMORY.md "- [m](mix_cold.md) [p](mix_prom.md) [f](flat.md)
192
+ - [a](<my note.md>) [b](sp%20name.md) [c](note(v2).md) [x](<gone note.md>) [y](gone(v2).md)"
193
+ JR="$(python3 "$HERE/memory_gc_report.py" "$R" --today 2026-10-15 --json)"
194
+ qr(){ printf '%s' "$JR" | "$PY" -c "import json,sys;d=json.load(sys.stdin);E={e['file']:e for e in d['entries']};print($1)"; }
195
+ eq "L21 valid-old + future hit: flagged, not cold" "$(qr "(E['mix_cold.md']['status'], d['cold'])")" "('HITS_MALFORMED', [])"
196
+ eq "L22 three valid + one malformed: no promotion" "$(qr "d['promote']")" "[]"
197
+ eq "L23 indentless hits item flagged, not silently dropped" "$(qr "(E['flat.md']['status'], E['flat.md']['age'])")" "('HITS_MALFORMED', None)"
198
+ eq "L24 <...>, %20 and balanced-paren destinations resolve" "$(qr "sorted(d['unlisted'])")" "[]"
199
+ eq "L25 their missing twins are dangling" "$(qr "sorted(x[0] for x in d['dangling'])")" "['gone note.md', 'gone(v2).md']"
200
+ JP="$(python3 "$HERE/memory_gc_report.py" "$R" --today 2026-10-15 --cap 22 --json)"
201
+ eq "L26 past_cap follows the link's own offset on a shared line" \
202
+ "$(printf '%s' "$JP" | "$PY" -c "import json,sys;E={e['file']:e for e in json.load(sys.stdin)['entries']};print(E['mix_cold.md']['past_cap'],E['mix_prom.md']['past_cap'])")" "False True"
203
+
204
+ # R3 (codex): two links on ONE line keep their link order, not filename order
205
+ Q="$T/q"; mkdir -p "$Q"; for f in z a; do printf -- '---\nmetadata:\n type: user\n---\n' > "$Q/$f.md"; done
206
+ printf -- '- [z](z.md) [a](a.md)\n' > "$Q/MEMORY.md"
207
+ eq "L27 same-line links keep link order" "$(python3 "$HERE/memory_gc_report.py" "$Q" --json | "$PY" -c "import json,sys;print(json.load(sys.stdin)['order'])")" "['z.md', 'a.md']"
208
+
209
+ echo "memory_gc_report lanes: $pass pass · $fail fail"
210
+ [ $fail -eq 0 ]