Merge origin/main into feat/295-auth-pr1
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 5s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m27s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 5m36s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Build ErsatzTV Image / Docs update reminder (push) Has been skipped
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 6m7s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 10m11s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 5m36s

Brings in the #303 process/rigor hooks + docs. Only conflict-free overlap was
docs/decisions.md (main added the ## Index TOC); reconciled by adding the #295
auth entry to the index.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit was merged in pull request #300.
This commit is contained in:
2026-07-12 17:07:52 +02:00
co-authored by Claude Opus 4.8
9 changed files with 312 additions and 128 deletions
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# PostToolUse / Bash — after a successful `git worktree add`, stamp the new worktree with
# this session's id (.claude-worktree-owner) so pretooluse-worktree-guard.sh (H7) can tell
# a sibling worktree another session created apart from this session's own.
# Fail-safe: any parse trouble → do nothing (the guard stays fail-open without a marker).
set -euo pipefail
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
cwd=$(printf '%s' "$input" | jq -r '.cwd // ""' 2>/dev/null || true)
me=$(printf '%s' "$input" | jq -r '.session_id // ""' 2>/dev/null || true)
printf '%s' "$cmd" | grep -qE 'git[[:space:]]+worktree[[:space:]]+add\b' || exit 0
[ -z "$me" ] && exit 0
[ -z "$cwd" ] && cwd="$PWD"
# Extract the <path> arg of `git worktree add [flags] <path> [<commit-ish>]`.
# Skip flags; skip the values of the value-taking flags (-b/-B/--reason). Worktree paths
# in this repo have no spaces, so whitespace tokenization is safe.
add_args=$(printf '%s' "$cmd" | sed -E 's/.*git[[:space:]]+worktree[[:space:]]+add[[:space:]]+//')
path=""
skip=0
for tok in $add_args; do
if [ "$skip" = 1 ]; then skip=0; continue; fi
case "$tok" in
-b|-B|--reason) skip=1; continue ;;
--) continue ;;
-*) continue ;;
*) path=$(printf '%s' "$tok" | tr -d '"'"'"''); break ;;
esac
done
[ -z "$path" ] && exit 0
case "$path" in /*) abs="$path" ;; *) abs="$cwd/$path" ;; esac
[ -d "$abs" ] || exit 0
# Don't clobber a marker a different session already planted.
[ -f "$abs/.claude-worktree-owner" ] && exit 0
printf '%s\n' "$me" > "$abs/.claude-worktree-owner" 2>/dev/null || true
exit 0
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# PreToolUse / Agent (subagent spawn) — RAM-gate the fan-out.
# The historic 8-9-way crash was RAM starvation, not CPU load; gate on FREE RAM.
# Fail-open: if memory_pressure is unavailable/unparsable → allow.
set -euo pipefail
free=$(memory_pressure -Q 2>/dev/null | grep -oE 'free percentage: [0-9]+' | grep -oE '[0-9]+' || true)
[ -z "${free:-}" ] && exit 0
if [ "$free" -lt 10 ]; then
jq -n --arg f "$free" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:("Free RAM \($f)% (<10%): do NOT spawn more agents — the historic crash was RAM starvation from an 8-9-way fan-out. Wait for memory_pressure -Q to recover, then retry.")}}'
elif [ "$free" -lt 20 ]; then
jq -n --arg f "$free" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:("Free RAM \($f)% (<20%): near the fan-out ceiling. Confirm before adding another build/implementer agent (read-only recon agents are cheap).")}}'
fi
exit 0
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# PreToolUse / Bash — deny commands that violate a HARD RULE.
# Fail-open: any parse trouble → allow (exit 0 with no output).
set -euo pipefail
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
# Match an actual env ASSIGNMENT in COMMAND POSITION — line start or right after a shell
# separator (; && || | ( ), optionally `export`. This deliberately does NOT match the name
# when it sits inside a quoted string (echo, git commit -m, jq test payloads), where the
# preceding char is a quote/word, not a separator — so mentions of the rule never false-trip.
if printf '%s' "$cmd" | grep -qE '(^|[;&|(]|&&|\|\|)[[:space:]]*(export[[:space:]]+)?ETV_UPDATE_GOLDENS='; then
jq -n '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Blocked: ETV_UPDATE_GOLDENS regenerates golden-test baselines — HARD RULE (docs/handoffs lore); never set it in a session. Update a golden deliberately and reviewed, not via a guarded run."}}'
fi
exit 0
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# PreToolUse / browser-navigate — deny opening download/stream endpoints in a tab
# (they hang the MCP session; curl them instead). Fail-open on parse trouble.
set -euo pipefail
input=$(cat)
url=$(printf '%s' "$input" | jq -r '.tool_input.url // ""' 2>/dev/null || true)
if printf '%s' "$url" | grep -qE '/iptv/|\.m3u8|/artwork/|playback\.m3u8'; then
jq -n '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Blocked: do not open download/stream endpoints (/iptv, .m3u8, /artwork, playback.m3u8) in a browser tab — they stall the MCP session. curl them instead (docs/handoffs lore)."}}'
fi
exit 0
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env bash
# PreToolUse / Bash — deny `git commit`/`git merge` inside a sibling worktree that
# a DIFFERENT session created (burned us twice — #289 path-leak, the plumbing-merge
# workaround exists precisely because of this). Ownership is a `.claude-worktree-owner`
# marker (session id) written at `git worktree add` time by posttooluse-worktree-marker.sh.
#
# Fail-open by design: no marker, unparsable input, or marker == this session → allow.
# So the main tree (never marked) and pre-convention worktrees (no marker) are unaffected;
# only a commit/merge into another session's marked worktree is blocked.
set -euo pipefail
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
cwd=$(printf '%s' "$input" | jq -r '.cwd // ""' 2>/dev/null || true)
me=$(printf '%s' "$input" | jq -r '.session_id // ""' 2>/dev/null || true)
# Only guard the state-mutating ops. Match `git commit`/`git merge` in command position
# (line start or after a shell separator) so a quoted mention never false-trips.
printf '%s' "$cmd" | grep -qE '(^|[;&|(]|&&|\|\|)[[:space:]]*git[[:space:]]+(-C[[:space:]]+[^[:space:]]+[[:space:]]+)?(commit|merge)\b' || exit 0
[ -z "$cwd" ] && cwd="$PWD"
# Determine the effective directory the git op runs in. Two common redirections in the
# lore's usage move it off the session cwd: `git -C <path>` and a leading `cd <path> &&`.
effdir="$cwd"
cpath=$(printf '%s' "$cmd" | grep -oE 'git[[:space:]]+-C[[:space:]]+[^[:space:]&|;]+' | head -1 | sed -E 's/^git[[:space:]]+-C[[:space:]]+//' | tr -d '"'"'"'' || true)
cdpath=$(printf '%s' "$cmd" | grep -oE '^[[:space:]]*cd[[:space:]]+[^[:space:]&|;]+' | head -1 | sed -E 's/^[[:space:]]*cd[[:space:]]+//' | tr -d '"'"'"'' || true)
if [ -n "${cpath:-}" ]; then
effdir="$cpath"
elif [ -n "${cdpath:-}" ]; then
effdir="$cdpath"
fi
# Resolve a relative effective dir against the session cwd.
case "$effdir" in /*) : ;; *) effdir="$cwd/$effdir" ;; esac
root=$(git -C "$effdir" rev-parse --show-toplevel 2>/dev/null || true)
[ -z "$root" ] && exit 0
marker="$root/.claude-worktree-owner"
[ -f "$marker" ] || exit 0
owner=$(tr -d '[:space:]' < "$marker" 2>/dev/null || true)
[ -z "$owner" ] && exit 0
[ "$owner" = "$me" ] && exit 0
# Marker names a DIFFERENT session → deny.
jq -n --arg o "$owner" --arg r "$root" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:("Blocked: worktree \($r) is owned by session \($o), not this one. Never commit/merge inside a sibling worktree another session created (#289 path-leak, plumbing-merge workaround). Commit from your own tree; if you genuinely own this worktree now, overwrite its .claude-worktree-owner marker with your session id.")}}'
exit 0
+54
View File
@@ -0,0 +1,54 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-bash-guard.sh\"",
"timeout": 10
},
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-worktree-guard.sh\"",
"timeout": 10
}
]
},
{
"matcher": "mcp__plugin_playwright_playwright__browser_navigate|mcp__claude-in-chrome__navigate",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-nav-guard.sh\"",
"timeout": 10
}
]
},
{
"matcher": "Agent|Task",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-agent-ram.sh\"",
"timeout": 10
}
]
}
],
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/posttooluse-worktree-marker.sh\"",
"timeout": 10
}
]
}
]
}
}
+7
View File
@@ -55,3 +55,10 @@ ErsatzTV/wwwroot/v2/
ErsatzTV/wwwroot/app/
web/dist/
web/node_modules/
# E2E / screenshot scratch (from Playwright/live-E2E runs) — never committed
/*.png
.playwright-mcp/
# Per-session worktree-ownership marker (H7, ersatztv#303) — local, never committed
.claude-worktree-owner
+52
View File
@@ -5,6 +5,58 @@ relitigate a settled call. Append new entries at the bottom in date order; never
past entries except to fix a factual error. **Update this doc in the same PR that changes any fact
below (or that establishes a new convention worth recording).**
---
## Index
- [2026-06 — REST API wraps existing MediatR handlers 1:1, no service layer](#2026-06--rest-api-wraps-existing-mediatr-handlers-11-no-service-layer)
- [2026-06 — UI rebuild is a React SPA (ChicoryTV) on the REST API, not a Blazor reskin](#2026-06--ui-rebuild-is-a-react-spa-chicorytv-on-the-rest-api-not-a-blazor-reskin)
- [2026-07 — Response DTOs live in `ErsatzTV.Core/Api`, file-scoped `#nullable enable`](#2026-07--response-dtos-live-in-ersatztvcoreapi-file-scoped-nullable-enable)
- [2026-07 — PUT-replace list endpoints derive `Index` from array order; alternate-schedules last row = catch-all default](#2026-07--put-replace-list-endpoints-derive-index-from-array-order-alternate-schedules-last-row--catch-all-default)
- [2026-07 — Templates editor in the SPA is a table, not Blazor's drag-calendar](#2026-07--templates-editor-in-the-spa-is-a-table-not-blazors-drag-calendar)
- [2026-07-07 — API artwork contract: rooted URLs produced server-side](#2026-07-07--api-artwork-contract-rooted-urls-produced-server-side)
- [2026-07-07 — Decode-style endpoints take a row id and look up server-side](#2026-07-07--decode-style-endpoints-take-a-row-id-and-look-up-server-side)
- [2026-07-07 — Season/episode/music-video drill-in via `parentId`, not new child-listing endpoints](#2026-07-07--seasonepisodemusic-video-drill-in-via-parentid-not-new-child-listing-endpoints)
- [2026-07-07 — Convention docs read at session start, updated in-PR](#2026-07-07--convention-docs-read-at-session-start-updated-in-pr)
- [2026-07-09 — Playback-troubleshooting completion feedback: poll status, no push channel](#2026-07-09--playback-troubleshooting-completion-feedback-poll-status-no-push-channel)
- [2026-07-09 — datetime-local instead of Chronic natural-language start parsing](#2026-07-09--datetime-local-instead-of-chronic-natural-language-start-parsing)
- [2026-07-09 — SPA gates Download Media Sample while a session is active](#2026-07-09--spa-gates-download-media-sample-while-a-session-is-active)
- [2026-07-09 — OpenAPI spec mirrors the runtime Newtonsoft serializer (#198)](#2026-07-09--openapi-spec-mirrors-the-runtime-newtonsoft-serializer-198)
- [2026-07-09 — YAML playout validator: paste-textarea instead of a server file path](#2026-07-09--yaml-playout-validator-paste-textarea-instead-of-a-server-file-path)
- [2026-07-09 — Channel numbers: prompt-driven sequential renumber instead of drag-to-reorder](#2026-07-09--channel-numbers-prompt-driven-sequential-renumber-instead-of-drag-to-reorder)
- [2026-07-09 — "Table, not calendar" convention also covers the deco-templates editor](#2026-07-09--table-not-calendar-convention-also-covers-the-deco-templates-editor)
- [2026-07-09 — Trash "see all" is capped at 100 items per kind; true paging deferred](#2026-07-09--trash-see-all-is-capped-at-100-items-per-kind-true-paging-deferred)
- [2026-07-11 — Logs page-size is a client-local preference, not a server ConfigElement](#2026-07-11--logs-page-size-is-a-client-local-preference-not-a-server-configelement)
- [2026-07-11 — Logs column sorting: allow-listed `sortField`/`sortDirection` on `GET /api/logs`](#2026-07-11--logs-column-sorting-allow-listed-sortfieldsortdirection-on-get-apilogs)
- [2026-07-09 — Per-playout "Schedule reset" button dropped; Reset uses the server-default build mode](#2026-07-09--per-playout-schedule-reset-button-dropped-reset-uses-the-server-default-build-mode)
- [2026-07-09 — Collection custom order: move up/down buttons, any-kind collections](#2026-07-09--collection-custom-order-move-updown-buttons-any-kind-collections)
- [2026-07-10 — Shared "Add to…" layer lives in `web/src/media/addTo/`; select-mode is an explicit toggle](#2026-07-10--shared-add-to-layer-lives-in-websrcmediaaddto-select-mode-is-an-explicit-toggle)
- [2026-07-10 — Schedule-item GET returns a flat, non-polymorphic DTO (`ScheduleItemResponseModel`)](#2026-07-10--schedule-item-get-returns-a-flat-non-polymorphic-dto-scheduleitemresponsemodel)
- [2026-07-10 — Playout API mutations return 409 while the build lock is held (#215)](#2026-07-10--playout-api-mutations-return-409-while-the-build-lock-is-held-215)
- [2026-07-11 — Schedules SPA editor: draft/explicit-Save over instant-persist; Copy includes multi/smart/rerun; shuffled-GET normalization preserved](#2026-07-11--schedules-spa-editor-draftexplicit-save-over-instant-persist-copy-includes-multismartrerun-shuffled-get-normalization-preserved)
- [2026-07-11 — Channel editor: bare-create entry point + external-logo mutual exclusion (#212)](#2026-07-11--channel-editor-bare-create-entry-point--external-logo-mutual-exclusion-212)
- [2026-07-11 — EntityLocker: atomic flags + single-owner release discipline, no owner tokens (#231)](#2026-07-11--entitylocker-atomic-flags--single-owner-release-discipline-no-owner-tokens-231)
- [2026-07-11 — Channels screen extraction (#244): single-file screen, no sibling helper dir (epic #243 phase 1)](#2026-07-11--channels-screen-extraction-244-single-file-screen-no-sibling-helper-dir-epic-243-phase-1)
- [2026-07-11 — Media-source management REST write API + SPA (#202)](#2026-07-11--media-source-management-rest-write-api--spa-202)
- [2026-07-11 — Legacy→SPA redirect matcher: exact map + ordered segment-template patterns (#204)](#2026-07-11--legacyspa-redirect-matcher-exact-map--ordered-segment-template-patterns-204)
- [2026-07-11 — Blazor removal auth posture: no new exposure beyond phase (a); real auth deferred to #197 (#206)](#2026-07-11--blazor-removal-auth-posture-no-new-exposure-beyond-phase-a-real-auth-deferred-to-197-206)
- [2026-07-11 — Pre-removal Blazor rollback tag `blazor-final` (#205)](#2026-07-11--pre-removal-blazor-rollback-tag-blazor-final-205)
- [2026-07-11 — Async-op API contract normalization + playout build observability + F9 scan endpoints (#235)](#2026-07-11--async-op-api-contract-normalization--playout-build-observability--f9-scan-endpoints-235)
- [2026-07-11 — Optimistic-concurrency contract for replace-all PUTs (#253 PR1: infra + Block reference)](#2026-07-11--optimistic-concurrency-contract-for-replace-all-puts-253-pr1-infra--block-reference)
- [2026-07-11 — Post-commit side effects run on `CancellationToken.None` (generalized from #251 to #254)](#2026-07-11--post-commit-side-effects-run-on-cancellationtokennone-generalized-from-251-to-254)
- [2026-07-11 — #253 PR3: Diff + Scalar concurrency fan-out (Collection / Playout×2 / MultiCollection / RerunCollection)](#2026-07-11--253-pr3-diff--scalar-concurrency-fan-out-collection--playout2--multicollection--reruncollection)
- [2026-07-11 — External Collections in the SPA derives from `getMediaSources()`; collections scans are optimistically bounded (#91b Libraries.razor parity)](#2026-07-11--external-collections-in-the-spa-derives-from-getmediasources-collections-scans-are-optimistically-bounded-91b-librariesrazor-parity)
- [2026-07-12 — External-collections scans get an authoritative status surface (#271); the SPA timeout is retired](#2026-07-12--external-collections-scans-get-an-authoritative-status-surface-271-the-spa-timeout-is-retired)
- [2026-07-11 — Blazor Server UI removed (#91 phase b)](#2026-07-11--blazor-server-ui-removed-91-phase-b)
- [2026-07-11 — Stable child identity for schedule-item replace (#259, split from #252/#253)](#2026-07-11--stable-child-identity-for-schedule-item-replace-259-split-from-252253)
- [2026-07-11 — Baseline security response headers + Phase-0 API hardening (#197, PR #279)](#2026-07-11--baseline-security-response-headers--phase-0-api-hardening-197-pr-279)
- [2026-07-12 — Artwork content-type is sniffed, never reflected (#283, S4/S9 stored XSS)](#2026-07-12--artwork-content-type-is-sniffed-never-reflected-283-s4s9-stored-xss)
- [2026-07-12 — Fail-closed API auth + sensitive-read tier + CORS/ForwardedHeaders lockdown (#197 Bundle A, PR #292)](#2026-07-12--fail-closed-api-auth--sensitive-read-tier--corsforwardedheaders-lockdown-197-bundle-a-pr-292)
- [2026-07-12 (#197 Bundle C — contract-freeze honesty)](#2026-07-12-197-bundle-c--contract-freeze-honesty)
- [2026-07-12 — Browser SPA session auth: `/api` accepts session OR machine key (#295 PR1, server-only)](#2026-07-12--browser-spa-session-auth-api-accepts-session-or-machine-key-295-pr1-server-only)
---
## 2026-06 — REST API wraps existing MediatR handlers 1:1, no service layer
The REST API (#2, `docs/rest-api.md`) is thin controllers over the existing MediatR
+77 -128
View File
@@ -32,12 +32,32 @@ Everything else (claiming, worktrees, dispatching implementers, CI monitoring, p
bookkeeping, routine merges of green reviewed PRs with user consent) stays at your level.
Then work the queue:
1. Read the pinned tracker **ersatztv#237** — body = goal + ordered arc + session protocol —
and its most recent session comments; list open issues in the `Blazor removal (#91 phase b)`
milestone and with the `review` label; ALSO list open `ersatztv`-labeled issues in
**timothy/adversarial-reviewer** — unclaimed audits there are pickup candidates too
(read-only, parallel-safe; see the tracker's "Pending adversarial reviews" section).
2. Pick the top arc item that is open and NOT labeled `in-progress` (or the item the user names).
1. Read the pinned tracker **ersatztv#237** — body = goal + ordered arc + session protocol — and
its **last ~6 session comments** (newest-first; the full comment payload is large, so stop at ~6).
**SOURCE OF TRUTH = live Gitea issue state, NEVER the prose.** The arc body carries ORDER + goal
only; a session comment's "Recommended next" is a forward *guess* written before the next session
acted. Both go stale the instant an item closes (especially under parallel sessions narrating each
other's work as "the gate that unblocks X"). So derive the candidate set from LIVE state, not from
any inline marker or a prior comment's "next": the **current gate = the lowest-numbered OPEN arc
item in #237's arc list**; its open children are the gate cluster (query them by the `review`
label). Cross-check every arc / "recommended" item's real open/closed state (issue **and**
milestone) before trusting it — do NOT hardcode which issue is the frontier; read it. ALSO list
open `ersatztv`-labeled issues in **timothy/adversarial-reviewer** — unclaimed audits there are
pickup candidates too (read-only, parallel-safe; see the tracker's "Pending adversarial reviews"
section). If the Gitea MCP is down, hit the REST API directly (creds in your global CLAUDE.md):
`curl -u <user>:<pass> http://192.168.1.95:3000/api/v1/repos/timothy/ersatztv/issues/237`.
**The authoritative pickup + ranking protocol lives in #237's "Session protocol" section — this is a summary; if the two ever disagree, #237 wins.**
2. Pick the highest-ranked OPEN, un-`in-progress` candidate (or the item the user names). **Rank by
labels, not just arc position** (labels are live state; prose is not): (1) arc order in #237, then
(2) **gate vs backlog** — an item marked gate by the `review` label OR membership in an open gate
milestone outranks anything unmilestoned; then (3) **`priority:`** label — `high` > `medium` >
`low` within a tier. Pick order across the three pools: the **arc frontier** (lowest-numbered open
arc item) first; an unclaimed Blocker/High **priority-pickup** (`review` + `priority: high`, e.g.
#253) beats a *non-frontier* arc item; reviewer-repo **audits** are read-only and run in parallel.
**Confirm the pick is genuinely OPEN in Gitea first.** If the prose says "recommended next / now
unblocked" but the issue (or its milestone) is already CLOSED, it is done — skip it and fix the
stale line in your session comment. Prose lags live state; live state wins; milestone + `priority:`
labels decide gate-vs-backlog, not the prose. (This mirrors #237's Session-protocol ranking — #237 is canonical.)
3. **Claim it**: add the `in-progress` label + a "claiming" comment on the issue(s);
reviewer-repo audits are claimed by comment only.
4. Read the issue bodies (they carry the task context/evidence) and work the item under the
@@ -64,18 +84,17 @@ HARD CONSTRAINTS:
---
# Lessons / workflow lore (append-only; conventions live in docs/, this is workflow lore)
# Lessons / workflow lore (STANDING workflow/orchestration rules only)
> **Scope**: this section is *how we work* (orchestration, CI, review, cross-session hygiene) —
> not engineering decisions. **Every "why the code does X" decision lives in `docs/decisions.md`**
> (+ `api-conventions.md` §7a/b/c for the concurrency/side-effect mechanics, `spa-conventions.md`,
> `e2e-local.md`). Do NOT re-record a code/API/SPA decision here — it will duplicate and drift.
> Pruned 2026-07-12: issue-specific engineering bullets now covered in those docs, and dead
> Blazor-parity process notes, were removed (git history has them).
- READ docs/README.md → the convention docs FIRST; point recon/implementer agents at specific
doc sections. Only recon the task-specific delta.
- **blazor-route-parity.md carries mutation-depth verdicts** (2026-07-09 sweep table at the
top of Section 2). A row is only trustworthy if its cluster verdict is PARITY-OK; the sweep
evidence lives in the issues #207–#213. Keep the verdict table updated as gates close.
- "Screen exists" ≠ parity: the root cause of the false SPA-READY rows was same-session
verification that never diffed capabilities against the Blazor page. Per-capability diff vs
the Blazor page is the standard for any future parity claim.
- Several gaps are UNWIRED EXISTING endpoints (playout delete/reset, block copy, scan-show,
collections add-item kinds) — check the endpoint index before building new API surface.
- Keep the MAIN checkout's `web/node_modules` fresh (`npm install` after pulling a PR that
adds a dep) — worktrees copy it, and a stale copy broke typecheck in a #198 worktree.
- **Playwright-MCP E2E: never open tabs/window.open for file-download endpoints** — curl them.
@@ -92,38 +111,23 @@ HARD CONSTRAINTS:
(`scripts/e2e-local.sh`) → review fixes as follow-up COMMITS (never amend/force-push) → CI
green → merge (consent per session) → structured close comments per CLAUDE.md protocol.
- Never run TWO committing agents on one worktree concurrently. Read-only review forks are fine.
- Reusable API facts: DTO records in ErsatzTV.Core/Api need file-scoped `#nullable enable`;
ErsatzTV.Application has NO nullable context (CS8632); `Option<T>`→nullable =
`MatchUnsafe(v => (T?)v, () => null)`; `LanguageExtensions.Apply` collapses NotFoundError→422,
so real 404s need a controller pre-check; id-taking child GETs get an
OpenApiErrorResponseContractTests [TestCase].
- **Arm a CI monitor the moment the PR opens** — in the #216 session three PR runs sat red for
~an hour (a CI-only debounce-timing flake) while review/E2E ran, because CI was only checked
"at the end". Also: concurrent runs can collide on the MySQL service host port 3306
("port is already allocated") — that's infra flake, rerun; consider unpinning the host port.
- **Arm a CI monitor the moment the PR opens** (commit-status endpoint), not at the end — in the
#216 session three PR runs sat red ~an hour on a CI-only flake while review/E2E ran. (The old
MySQL host-port 3306 collision is fixed on main, `ef8915f1`; a lone MySQL-apply red now = the
known infra flake, rerun — see MEMORY / `ci-migration-job-mysql-flake`.)
- **"Make X consistent with Y" review findings deserve new-code scrutiny** — a #216 review fix
propagated MediaBrowseScreen's mount-debounce selection-wipe race to SearchScreen instead of
catching it. For any timer/effect, ask "when does this fire?" (incl. mount).
- SPA mutation affordances on media items: USE the shared `web/src/media/addTo/` layer
(spa-conventions §5c) — don't build screen-local pickers. Schedule adds are valid only for
shows/seasons/artists (server validator).
- Live E2E seeding: the local library isn't API-seedable; the #216 E2E agent generated tiny
ffmpeg testsrc MKVs + inserted LibraryPath rows via SQL then scanned. Recipe not yet in
docs/e2e-local.md — worth adding next time it's needed.
- **Parallel sessions (2026-07-11 protocol)**: claim before working (`in-progress` label — the
tiny read→claim race window is accepted; later claimant backs off). Claiming prevents
duplicate pickup, NOT overlapping code changes — check the tracker's dependency notes
("#234 after #231", "coordinate with #215") before touching shared surfaces. Lessons edits
to THIS file: append bullets only, `git pull --rebase` before commit.
- **Fan-out health = RAM, not CPU load** (2026-07-11, user calibration): the 8–9-way crash was
RAM starvation. `uptime` load of 10–24 during parallel Roslyn/vitest bursts is benign with
memory healthy. Watchdog pattern: background monitor emitting only when `memory_pressure -Q`
free % < 20 (silence = healthy); pause/stagger agents below 10%.
- **CI MySQL host-port collision FIXED on main** (`ef8915f1`, issue #236): the migrations
service no longer publishes host 3306. Branches created before that commit still collide —
merge main in. There are now TWO runners (ci-runner VM 127 + bumblebee-runner), 4 slots:
faster drains, and superseded-run results are ignorable. Neither the cancel-run API route
nor the web cancel route exists on this Gitea version — stale runs just drain.
("#234 after #231", "coordinate with #215") before touching shared surfaces. Editing THIS
lore: prune covered/stale bullets too (not append-only — git keeps history), `git pull --rebase`
before commit. Two runners (ci-runner VM 127 + bumblebee-runner, 4 slots) → superseded runs
drain on their own; no cancel route exists on this Gitea version.
- **Two sessions touching one machine**: a branch may be checked out in ANOTHER session's
worktree — never commit/merge inside a worktree you didn't create. To land a merge on such a
branch without touching their checkout: plumbing merge (`git read-tree -m base ours theirs`
@@ -136,11 +140,10 @@ HARD CONSTRAINTS:
stuck-diagnosis second opinions) via `codex:rescue`, never for implementation. Check
readiness/quota with `/codex:setup`; on exhaustion fall back to fork/subagent review and
retry next window.
- **Fixed-point round-trip tests can't see lazy-evaluation crashes** (2026-07-11, PR #229): a
write-path 500 (unset navs projected after SaveChanges) survived a green fixed-point test
because the handler returned a lazy LanguageExt `Map` the test never enumerated. Rules:
force enumeration of handler return values in tests; write-path responses reload through the
read path's include chain (api-conventions §7); live E2E remains the only net for this class.
- **Force enumeration of lazy LanguageExt returns in tests** (2026-07-11, PR #229): a write-path 500
survived a green fixed-point test because the handler returned a lazy `Map` the test never enumerated.
Enumerate handler return values in tests; live E2E remains the only net for this class. (Write-path
reload-through-read-path mechanics: api-conventions §7.)
- **Merging main into an open PR branch: REGENERATE generated artifacts** (v1.json, v1.d.ts,
endpoint-index) after resolving source conflicts — git text-merges them plausibly-but-wrong;
`npm run check:api` is the guard. Also expect other sessions to push to YOUR PR branch
@@ -170,11 +173,6 @@ HARD CONSTRAINTS:
(Codex if quota, else a fork) over the fix commit into the close protocol; loop until a clean
MERGEABLE verdict or an explicit acceptable-defer (file a tracked issue for the deferral, as #248
here). Cheap relative to shipping a half-fix that reopens the issue.
- **`disabled={saving}` is the SchedulesScreen convention for "no schedule-switch/mutation mid-save"**
(2026-07-11, #242): the Select + `guardedSwitch` already guard `saving`; Edit and Delete must too
— Delete switches schedules via `applySwitch`, and a stale items PUT resolving after the switch
clobbers the next schedule's draft. When adding any control that can switch the active schedule or
reopen the editor, gate it on `saving` (and, for the editor, on the dirty draft).
- **Negative-controlling a lock/flag fix: invert the condition, don't stub `if (true)`** (2026-07-11,
#250): to prove a lock-release test is non-vacuous I temporarily broke the fix. First attempt made
the guard `if (true)` — but that left the ownership flag "assigned but never read" → **CS0219 under
@@ -185,34 +183,6 @@ HARD CONSTRAINTS:
always grep the build for `error CS` before trusting a `--no-build` test result. (Codex-found High
this session: an outer `catch` that unlocked unconditionally cross-released another session's lock on
a pre-acquisition exception — the fix was a Handle-scoped ownership flag gating the catch.)
- **Post-commit side-effect invalidation must run its QUERIES on `CancellationToken.None`, not just the
enqueue** (2026-07-11, #251, Codex-found Medium the fork missed): the deco-invalidation handlers committed
the edit on the request token (correct — a pre-commit cancel safely aborts), then queried the affected
playouts *also* on the request token before a `WriteAsync(..., None)` enqueue. A cancel landing in the
window between commit and query throws before the enqueue → edit persisted, no rebuild queued, stale-content
bug re-opens. Fix: once `SaveChangesAsync` has committed, run the ENTIRE side effect (affected-entity
queries + enqueue) on `CancellationToken.None` — a committed change's compensating side effect must not be
half-abortable. Generalizes the audit #22 policy from "the enqueue" to "everything after the commit". The
fork review OK'd it; only the independent Codex pass caught the query-token gap — evidence for keeping both
reviewers when quota allows.
- **Replace-all handler with NO client stable id → positional in-place reconcile via `CurrentValues.SetValues`**
(2026-07-11, #252): to stop a delete-and-reinsert handler from cascade-wiping a child that FKs the item
(`PlayoutScheduleItemFillGroupIndex` owns fill-group enumerator state, `OnDelete(Cascade)`), reconcile by
ordered POSITION (the DTO carries no id): same-runtime-type slot → `built = BuildItem(...); built.Id =
existing.Id; dbContext.Entry(existing).CurrentValues.SetValues(built)` (reuse the builder as the SetValues
source so NO field is hand-copied/dropped; set the key first so SetValues doesn't zero it), then rebuild
child join rows; subtype change/surplus → delete+insert that slot only. Keeps the row id → the cascade never
fires. The schedule-item hierarchy is **TPT** (table-per-type), not TPH — SetValues is still safe (same-type
guard; no discriminator). This is the SCOPED placeholder; true content-aware stable child identity is #253
(a moved fill-group item still inherits the state of whatever held its new slot). Anyone doing #253 builds on
/ replaces this positional reconcile in `ReplaceProgramScheduleItemsHandler`.
- **A docs PR that lists gates/cross-refs can go STALE mid-flight** (2026-07-11, #205/#206 PR #261): while the
PR sat in review a *listed* gate (#204) merged. The PR FF-rejected → rebased; the `decisions.md` append
conflict was trivial, but the real trap was the **prose** — the new removal runbook still named #204 an open
removal gate. After rebasing over a parallel merge, re-read your prose cross-references (gate lists, "blocked
on #N", status tables), not just resolve the conflict markers — git fast-forwards stale *facts* silently. The
hand-written-docs sibling of the "regenerate generated artifacts after merging main" lesson. Also: docs-only
PRs still trip main's `Build & test` branch protection, so a rebase = a fresh full-CI cycle before merge.
- **A lock/channel-ownership "no cross-release" verdict must enumerate EVERY producer of that message
type, not just the enqueuers visible in the PR diff** (2026-07-11, #235/#267). The cold fork cleared the
new `scan-collections` per-provider lock as sound — "only the acquirer enqueues, so only its message
@@ -229,56 +199,35 @@ HARD CONSTRAINTS:
media source (fixed loop order), prescribing the shipped library-scan §C7 pattern instead (lock once per
provider, batch-enqueue, release on the `Unlock: isLast` message). Escalate the FIX approach too, not just
the finding.
- **Activating an `IsConcurrencyToken` exposes EVERY writer of that root, not just the opt-in ones**
(2026-07-11, #253 PR3, review-caught HIGH): once ANY handler bumps a root's version (making the token
live), EF appends `WHERE Version=@orig` to *every* UPDATE/DELETE of that row — so a *separate*
root-scalar writer that saves via plain `SaveChangesAsync` (and doesn't even bump) now throws
`DbUpdateConcurrencyException`→500 on a concurrent bump. Block (PR1) had a single root writer → no
exposure, which is why PR1/PR2 reviews didn't flag it; Playout/Collection (PR3) have several
(settings/schedule-file/checkpoint/name vs. the bumping alt-sched/template/deco/custom-order) → real
two-tab 500. Fix pattern: `ConcurrencyExtensions.SaveChangesForcingVersion` — on conflict, adopt the
stored token as BOTH `OriginalValue` and `CurrentValue` on each `IVersionedAggregate` entry and retry
(client-wins merge scoped to the token; Phase-1 force-write for a missing If-Match; never reverts the
concurrent bump). When you activate a token on aggregate X, grep for ALL other root-scalar UPDATE/DELETE
writers of X (not just the editor) and force-write or guard them. **Suspected open case: PR2's
`ProgramSchedule`** (`UpdateProgramScheduleHandler` vs. the bumping `ReplaceProgramScheduleItems`) — audit
for #197/#269/PR4.
- **A phased force-write→428 rollout (and its "soak") only earns its keep when INDEPENDENT clients must adopt
the new header on their own schedule — when you own the ONLY client, the gate is essentially vestigial**
(2026-07-11, #253 PR4; user-sharpened). The two-phase `If-Match` migration exists so un-migrated third-party
clients aren't hard-rejected (428) before they start sending the header; the soak is the client-*adoption*
window. We ship the only client — the ChicoryTV SPA, in lockstep in the same image — and it already echoes
`If-Match` on every editor (E2E-verified). So there is no client population to protect and the gate's core
purpose is void; the real #197 decision is whether to keep the two-phase design at all vs. collapse it (flip
to 428 in the same release Phase-1 first ships, gated on the SPA echoing correctly — which E2E already
proves — not on a prod soak). **General lesson: the value of any "soak"/phased-rollout gate is a function of
whether independent clients exist; a single lockstep-shipped client usually makes phased API migrations
over-engineered.** Secondary/tactical only: even under the *current* two-phase design PR4 can't ship yet
because Phase-1 has never reached prod — prod is v26.5.0 (2026-07-07) and the newest tag v26.6.0
(2026-07-08) predates all of #253 (`git merge-base --is-ancestor <pr3-sha> v26.6.0` → NOT an ancestor), so
"one release soaks" hasn't begun; resolve any "after a release soaks" against the actual deployed tag, not
wall-clock. But that's the narrow reason PR4 is blocked, not why the gate barely matters.
- **Harden a soon-to-grow feature with a runtime *posture/toggle*, not a hardcoded clamp** (2026-07-12, #289).
The MCP verb-guard finding said "assert `HttpMethod.Get`", but the MCP's *final* design (#58) is read+write, so
a hardcoded GET-clamp would just be ripped out later. Shipped a runtime **read-only posture**
(`ERSATZTV_ALLOW_WRITES`, default false) enforced in the executor instead — same runtime backstop (a wrong
catalog entry can't mutate), but the toggle IS the seam the future write tools slot behind. General rule: when
a security fix constrains a capability the roadmap will later want, make the safe state the *default of a
switch*, not a wall. Check the feature's tracking issue for its end-state before choosing the shape of a guard.
- **Fixing onto an unmerged feature branch (not `main`): branch off it, land by FF-push, never touch a sibling
worktree that has it checked out** (2026-07-12, #289 → PR #76's `issue58-mcp`). Worked in a fresh worktree off
`origin/issue58-mcp`, then landed with `git push origin fix/289:issue58-mcp` (pure fast-forward — verify with
`git merge-base --is-ancestor`). The owning session's local `issue58-mcp` worktree just pulls; you never commit
inside a checkout you didn't create. **Gotcha that bit me:** I did recon by `Read`ing files from the
*pre-existing* `ersatztv-issue58-mcp` sibling worktree, so my later `Edit`s carried those paths and landed
there — while `dotnet` built the fresh worktree (unchanged) → "0 new tests" tipped it off. After creating a new
worktree, do the first `Edit`/`Read` against ITS absolute paths and `git status` the new worktree before
building; don't let a recon-worktree path leak into the implementation.
- **Harden a soon-to-grow feature with a runtime posture/toggle, not a hardcoded clamp** (2026-07-12, #289):
the MCP's final design (#58) is read+write, so a GET-clamp would be ripped out — shipped a runtime read-only
posture (`ERSATZTV_ALLOW_WRITES`, default false) instead. When a security fix constrains a capability the
roadmap will later want, make the safe state the *default of a switch*, not a wall; check the feature's issue
for its end-state first.
- **Fixing onto an unmerged feature branch: branch off it, land by FF-push, never touch a sibling worktree that
has it checked out** (2026-07-12, #289 → PR#76). Gotcha: recon by `Read`ing a *sibling* worktree leaked its
paths into my later `Edit`s → they landed there, not the fresh worktree (`dotnet` built the unchanged tree →
"0 new tests" tipped it off). After creating a worktree, do the first Edit/Read against ITS absolute paths and
`git status` it before building.
- **`HttpCompletionOption.ResponseHeadersRead` moves the body read OUTSIDE `HttpClient.Timeout`** (2026-07-12,
#289, cold-fork-caught HIGH regression). Switching to `ResponseHeadersRead` to stream+cap a response body
silently drops the body read out of `HttpClient.Timeout`'s coverage; if the read token is `None`, a slow-drip
upstream hangs forever. Fix = a per-request linked `CancellationTokenSource.CancelAfter(timeout)` threaded into
BOTH `SendAsync` and the stream reads, with `HttpClient.Timeout = InfiniteTimeSpan` so one timer owns it. And:
transport/timeout exceptions must be caught and turned into a response (a `-32603`), else the failure escapes
the handler and the client hangs awaiting a reply that never comes. Proved live with a black-hole socket
(accept, never respond) → 1s timeout → error in ~1s, no hang.
#289): with a `None` read token a slow-drip upstream hangs forever. Fix = per-request linked
`CancellationTokenSource.CancelAfter(timeout)` into BOTH `SendAsync` and the stream reads +
`HttpClient.Timeout = InfiniteTimeSpan`; catch transport/timeout exceptions and turn them into a response.
(Not yet in decisions.md — #289 landed on PR#76, not main.)
- **Queue-drift root cause + standing rule (2026-07-12, user-surfaced)**: pickups repeatedly re-picked
already-done work — #91b was framed "recommended next / now unblocked" for two sessions *after* it had
merged (2026-07-11), and the #251/#252 priority-pickups sat listed "open" after closing — requiring a
reactive body correction (tracker comment 16:00). ROOT CAUSE: DONE/OPEN status was read from **prose** (the
arc body's inline "DONE" markers + each session comment's "Recommended next"), which is append-only and
hand-edited, so it lags real issue state — worst under parallel sessions that narrate each other's merges as
"the gate that unblocks X" (#271 got cast as the last gate for an already-merged #91b). It is a *structural*
bug, not a stale-writer bug: any status embedded in prose will drift. STANDING FIX (don't just re-patch the
body next time): **live Gitea state is the ONLY source of truth for status.** The arc body carries order+goal;
a comment's "Recommended next" is a *candidate* that MUST be re-verified OPEN (issue **and** milestone) at
pickup. When prose disagrees with live state, live state wins — correct the prose in your session comment,
never propagate it. STRUCTURAL CURE (2026-07-12 review, Fable): #237's arc no longer carries inline `DONE`
markers — closed items move to a "Done (history)" section, so status lives ONLY in live Gitea state and can't
drift; and the gate/frontier is defined **structurally** (lowest-numbered open arc item), never hardcoded to
an issue number. Beware: the *first* pass at this fix re-planted the very bug by hardcoding "#197 cluster" /
"#91b milestone CLOSED" into the kickoff — if you name today's frontier issue in this standing file, you are
writing the next drift. Gate cluster = open `review`-labeled issues serving the current open arc item.