{"base_sha": "51098c553dd886e046ce38bc5436c1035cbcbc6e", "cohort": null, "context": {"canonical_pr_url": "https://github.com/ChristianLempa/boilerplates/pull/1796", "id": "00eec574c12b5455818225b23db3d254f8dfe0b35019d64d7c10b138ff538845", "preparation_mode": "source-only", "snapshot": {"base_ref": "51098c553dd886e046ce38bc5436c1035cbcbc6e", "base_sha": "51098c553dd886e046ce38bc5436c1035cbcbc6e", "body": "", "head_ref": "6ac2729239d64670e93b2e1d9288f9072f938891", "head_sha": "6ac2729239d64670e93b2e1d9288f9072f938891", "name": "boilerplates", "number": 1796, "owner": "ChristianLempa", "pr_url": "https://github.com/ChristianLempa/boilerplates/pull/1796", "title": ""}}, "head_sha": "6ac2729239d64670e93b2e1d9288f9072f938891", "metadata": {"group_id": "2a4c82256ae3452af1790c4cbf8602e17e65713c91b85904217c1119e022e96c", "snapshot": {"base_sha": "51098c553dd886e046ce38bc5436c1035cbcbc6e", "external_requirements": [], "head_sha": "6ac2729239d64670e93b2e1d9288f9072f938891", "objects": 398, "objects_sha256": "d3c6d11498c5291d42874c6e6c18a3fdb6e2b8fd0f3a3ea54a05d95b20a46bc5", "patch_sha256": "28e16a842d1783dca91946f774657880d6b8eef279e0f784da140326afd7c5cf"}}, "pr_number": 1796, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "09fcc7fc3efe", "description": "The CLI's run function called init_app() and app() without exception handling, so initialization and command errors could produce unhandled tracebacks instead of clear messages and appropriate exit codes, including exit code 130 for Ctrl+C.", "file_path": "cli/__main__.py"}], "commits_under_review": [{"author": "cfakley", "date": "2026-05-30T14:32:29Z", "files": [{"additions": 25, "deletions": 24, "filename": "cli/__main__.py", "patch": "@@ -14,7 +14,7 @@\n \n import click\n from rich.console import Console\n-from typer import Option, Typer\n+from typer import Option, Typer, Context\n from typer.core import TyperGroup\n \n import cli.modules\n@@ -79,6 +79,7 @@ def setup_logging(log_level: str = \"WARNING\") -> None:\n \n @app.callback(invoke_without_command=True)\n def main(\n+ ctx: Context,\n _version: bool | None = Option(\n None,\n \"--version\",\n@@ -104,9 +105,6 @@ def main(\n # Silence all logging (including third-party) unless user explicitly requests it\n logging.disable(logging.CRITICAL)\n \n- # Get context without type annotation (compatible with all Typer versions)\n- ctx = click.get_current_context()\n-\n # Store log level in context for potential use by other commands\n ctx.ensure_object(dict)\n ctx.obj[\"log_level\"] = log_level\n@@ -241,26 +239,29 @@ def run() -> None:\n except (ValueError, IndexError):\n pass # Let Typer handle argument parsing errors\n \n- try:\n- init_app()\n- app()\n- except (ValueError, RuntimeError) as e:\n- # Handle configuration and initialization errors cleanly\n- display.error(str(e))\n- sys.exit(1)\n- except ImportError as e:\n- # Handle module import errors with detailed info\n- display.error(f\"Module Import Error: {e}\")\n- sys.exit(1)\n- except KeyboardInterrupt:\n- # Handle Ctrl+C gracefully\n- display.warning(\"Operation cancelled by user\")\n- sys.exit(130)\n- except Exception as e:\n- # Handle unexpected errors - show simplified message\n- display.error(str(e))\n- display.info(\"Use --log-level DEBUG for more details\")\n- sys.exit(1)\n+ init_app()\n+ app()\n+\n+ # try:\n+ # init_app()\n+ # app()\n+ # except (ValueError, RuntimeError) as e:\n+ # # Handle configuration and initialization errors cleanly\n+ # display.error(str(e))\n+ # sys.exit(1)\n+ # except ImportError as e:\n+ # # Handle module import errors with detailed info\n+ # display.error(f\"Module Import Error: {e}\")\n+ # sys.exit(1)\n+ # except KeyboardInterrupt:\n+ # # Handle Ctrl+C gracefully\n+ # display.warning(\"Operation cancelled by user\")\n+ # sys.exit(130)\n+ # except Exception as e:\n+ # # Handle unexpected errors - show simplified message\n+ # display.error(str(e))\n+ # display.info(\"Use --log-level DEBUG for more details\")\n+ # sys.exit(1)\n \n \n if __name__ == \"__main__\":", "status": "modified"}, {"additions": 1, "deletions": 4, "filename": "cli/core/module/helpers.py", "patch": "@@ -194,10 +194,7 @@ def apply_cli_overrides(template, var: list[str] | None, ctx=None) -> None:\n \n # Get context if not provided (compatible with all Typer versions)\n if ctx is None:\n- try:\n- ctx = click.get_current_context()\n- except RuntimeError:\n- ctx = None\n+ ctx = click.get_current_context(silent=True)\n \n extra_args = list(ctx.args) if ctx and hasattr(ctx, \"args\") else []\n cli_overrides = parse_var_inputs(var or [], extra_args)", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "pyproject.toml", "patch": "@@ -23,6 +23,7 @@ dependencies = [\n \"python-frontmatter>=1.0.0\",\n \"Jinja2>=3.0\",\n \"email-validator>=2.0.0\",\n+ \"click==8.1.4\",\n ]\n \n [project.optional-dependencies]", "status": "modified"}], "message": "Fix Typer Context initialization crashing the CLI and missing clicker requiremnt in pipx toml.", "sha": "6ac2729239d64670e93b2e1d9288f9072f938891"}], "post_review_commits": ["09fcc7fc3efeb945dea02f43e12d6cd6fbd8fe81"], "pr_author": "cfakley", "pr_title": "Fix Typer Context initialization crashing the CLI and missing clicker…", "repo_name": "ChristianLempa/boilerplates"}, "repo": "ChristianLempa/boilerplates", "snapshot": "snapshots/2a4c82256ae3452af1790c4cbf8602e17e65713c91b85904217c1119e022e96c.pack", "split": "rl", "task_id": "00eec574c12b5455818225b23db3d254f8dfe0b35019d64d7c10b138ff538845"} {"base_sha": "3b6c3370e6395d77efdeee23357c0517e3c9a5cf", "cohort": null, "context": {"canonical_pr_url": "https://github.com/inetsoft-technology/stylebi/pull/4165", "id": "01c063a57dac27d52054a73792b0e5a57f560bce1033f2d51f4f7584eaec8eb9", "preparation_mode": "source-only", "snapshot": {"base_ref": "3b6c3370e6395d77efdeee23357c0517e3c9a5cf", "base_sha": "3b6c3370e6395d77efdeee23357c0517e3c9a5cf", "body": "", "head_ref": "da7d995e4f914c5e44a6ac40b8ce9c1d8abaefb1", "head_sha": "da7d995e4f914c5e44a6ac40b8ce9c1d8abaefb1", "name": "stylebi", "number": 4165, "owner": "inetsoft-technology", "pr_url": "https://github.com/inetsoft-technology/stylebi/pull/4165", "title": ""}}, "head_sha": "da7d995e4f914c5e44a6ac40b8ce9c1d8abaefb1", "metadata": {"group_id": "850b584c444f23c9f134400f6eacdf941d81efb9ac0600bb0a2fbd04eab06af4", "snapshot": {"base_sha": "3b6c3370e6395d77efdeee23357c0517e3c9a5cf", "external_requirements": [], "head_sha": "da7d995e4f914c5e44a6ac40b8ce9c1d8abaefb1", "objects": 18224, "objects_sha256": "75986dccd397f350bd2e1ae128d36c63a256dc4b649bdf28f0d82ae546a6ec17", "patch_sha256": "027e8e616789e0065cb21e9abfb10d2b41fbbe1bd22c80148abd7b462e29bada"}}, "pr_number": 4165, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "bug", "commit_sha": "693994eae55e", "description": "The permission tests did not cover SECURITY_ROLE permissions with only ASSIGN granted, leaving the regression where ASSIGN could incorrectly authorize READ, WRITE, DELETE, or ADMIN unchecked.", "file_path": "core/src/test/java/inetsoft/sree/security/DefaultCheckPermissionStrategyTest.java"}], "commits_under_review": [{"author": "bonnieshi43", "date": "2026-07-06T01:59:38Z", "files": [{"additions": 1, "deletions": 1, "filename": "core/src/main/java/inetsoft/sree/security/DefaultCheckPermissionStrategy.java", "patch": "@@ -232,7 +232,7 @@ else if(type.equals(ResourceType.SECURITY_USER)) {\n //if admin permissions to this resource, return true\n boolean hasResourcePermission = provider.getPermission(type, resource, orgID) != null &&\n provider.getPermission(type, resource, orgID)\n- .getOrgScopedUserGrants(ResourceAction.ASSIGN, OrganizationManager.getInstance().getCurrentOrgID())\n+ .getOrgScopedUserGrants(ResourceAction.ADMIN, OrganizationManager.getInstance().getCurrentOrgID())\n .contains(pId);\n \n if(hasResourcePermission) {", "status": "modified"}], "message": "fixed 75567:Fix privilege escalation where ASSIGN implied full role admin access", "sha": "da7d995e4f914c5e44a6ac40b8ce9c1d8abaefb1"}], "post_review_commits": ["693994eae55ea05059a67b4c24edbd21beb8c069"], "pr_author": "bonnieshi43", "pr_title": "fixed 75567:Fix privilege escalation where ASSIGN implied full role admin access", "repo_name": "inetsoft-technology/stylebi"}, "repo": "inetsoft-technology/stylebi", "snapshot": "snapshots/850b584c444f23c9f134400f6eacdf941d81efb9ac0600bb0a2fbd04eab06af4.pack", "split": "rl", "task_id": "01c063a57dac27d52054a73792b0e5a57f560bce1033f2d51f4f7584eaec8eb9"} {"base_sha": "5de47f4567bdd199a77f0ca276e98a4ed43d9c1e", "cohort": null, "context": {"canonical_pr_url": "https://github.com/dork-labs/dorkos/pull/902", "id": "0522f303bf1305a7acecb81eeda9aead9d140bab8dab0a9c26bf5890b0ff6ddd", "preparation_mode": "source-only", "snapshot": {"base_ref": "5de47f4567bdd199a77f0ca276e98a4ed43d9c1e", "base_sha": "5de47f4567bdd199a77f0ca276e98a4ed43d9c1e", "body": "", "head_ref": "e1daf4bb10274709bddd07481f725d4f6532e8fd", "head_sha": "e1daf4bb10274709bddd07481f725d4f6532e8fd", "name": "dorkos", "number": 902, "owner": "dork-labs", "pr_url": "https://github.com/dork-labs/dorkos/pull/902", "title": ""}}, "head_sha": "e1daf4bb10274709bddd07481f725d4f6532e8fd", "metadata": {"group_id": "51bbfc099e0f38160ef7f6f8ccd7ad03d8f577fa1a465a9f076a14e839b249d7", "snapshot": {"base_sha": "5de47f4567bdd199a77f0ca276e98a4ed43d9c1e", "external_requirements": [], "head_sha": "e1daf4bb10274709bddd07481f725d4f6532e8fd", "objects": 10466, "objects_sha256": "0ecedb50d281fffd9b7dd6b586bb52e1cf309ed8dcc5c80fe371d1d4579bb3e9", "patch_sha256": "8293ba4db3c2ccb903a4071095958f4d7b44265e254b9793c74dfa0f26364cb0"}}, "pr_number": 902, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "documentation", "commit_sha": "693dfd783f7b", "description": "Four references to the runtime-prompt-redelivery spec used the nonexistent ID `260807-231653` instead of its actual ID, `260807-231652`.", "file_path": "specs/persistent-session-runtime/01-ideation.md"}, {"action_id": "A2", "action_type": "fix", "category": "documentation", "commit_sha": "693dfd783f7b", "description": "The specification's dependency table and references cited the wrong runtime-prompt-redelivery spec ID (`260807-231653` rather than `260807-231652`).", "file_path": "specs/persistent-session-runtime/02-specification.md"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "693dfd783f7b", "description": "The PR had inadvertently changed the unrelated composer-rich-text manifest status from `implemented` to `specified`.", "file_path": "specs/manifest.json"}], "commits_under_review": [{"author": "doriancollier", "date": "2026-08-10T01:21:46Z", "files": [{"additions": 9, "deletions": 1, "filename": "specs/manifest.json", "patch": "@@ -1,6 +1,14 @@\n {\n \"version\": 1,\n \"specs\": [\n+ {\n+ \"id\": \"260810-003853\",\n+ \"slug\": \"persistent-session-runtime\",\n+ \"title\": \"Persistent session runtime, and the queue / steer / interrupt contract\",\n+ \"created\": \"2026-08-09\",\n+ \"status\": \"specified\",\n+ \"linearIssue\": \"DOR-1089\"\n+ },\n {\n \"id\": \"260809-150251\",\n \"slug\": \"page-width-consistency\",\n@@ -78,7 +86,7 @@\n \"slug\": \"composer-rich-text\",\n \"title\": \"Rich text via markdown in the composer (Lexical)\",\n \"created\": \"2026-08-06\",\n- \"status\": \"implemented\"\n+ \"status\": \"specified\"\n },\n {\n \"id\": \"260806-215028\",", "status": "modified"}, {"additions": 392, "deletions": 0, "filename": "specs/persistent-session-runtime/01-ideation.md", "patch": "@@ -0,0 +1,392 @@\n+# Persistent session runtime, and the queue / steer / interrupt contract\n+\n+**Work item:** DOR-1089 · **Slug:** `persistent-session-runtime` · **Id:** `260810-003853` · **Date:** 2026-08-09 · **Stage:** IDEATE\n+\n+**Source material:** `research/20260610_message_queuing_agent_runtimes.md` (DOR-82, the foundation), a full source trace of `services/runtimes/claude-code/` at `e4b9e1a9b`, the installed `@anthropic-ai/claude-agent-sdk@0.3.224` type surface, and the in-flight DOR-1087 workaround branch (`worktree-dor-1087-phantom-stop`, uncommitted).\n+\n+Every claim about current behavior below carries a `file:line` pointer verified against the tree at `e4b9e1a9b`. Where a claim could not be verified from source it is labelled **unverified** rather than asserted.\n+\n+---\n+\n+## 1) Intent and assumptions\n+\n+**Task brief.** Move the claude-code runtime off resume-per-message (a fresh `query()` subprocess per turn) onto persistent streaming-input sessions, and standardize three dispositions at the `AgentRuntime` boundary: **queue**, **steer**, **interrupt**, plus capability flags and honest degradation for codex and opencode.\n+\n+**Shape constraints already decided (not open for re-litigation in SPECIFY):**\n+\n+1. One persistent `query()` per **ACTIVE** session, with an idle timeout that closes the process.\n+2. Today's resume path stays, as the crash / restart / cold-start fallback. It is not deleted; it is demoted to a recovery route.\n+3. The **server owns the message queue** (ADR-0264's trigger-only POST is the seam). Native runtime queuing is an optimization a given adapter may reach for, never the contract.\n+\n+**Assumptions.**\n+\n+- The Claude Agent SDK stays at `0.3.224` or newer for the life of this programme. Everything the design leans on (`streamInput`, `priority`, `shouldQuery`, interrupt receipts, `cancel_queued`, `reinitialize`) is present in the installed `sdk.d.ts` and cited in §5.\n+- Session count per host stays in the tens, not thousands. `SESSIONS.MAX_SESSIONS = 50` (`apps/server/src/config/constants.ts:119`) is the existing ceiling and this work does not raise it.\n+- DorkOS remains single-process per host. No cross-process session affinity problem is in scope.\n+- The cockpit's ephemeral compose-next queue (ADR-0104) is superseded by the server queue, but its **UX** (queue chips, edit-in-place, `restore` on refusal) is a requirement to preserve, not a thing to redesign.\n+\n+**Out of scope.**\n+\n+- Making codex or opencode persistent. They keep their own process models (ADR-0308, ADR-0309); they only gain the disposition vocabulary and honest capability flags.\n+- Multi-host / horizontally-scaled session routing.\n+- The client's composer redesign. This programme changes what the composer can _ask for_, not how it looks.\n+- `runtime-interrupt-receipts` (spec `260807-231651`) and `runtime-prompt-redelivery` (spec `260807-231653`) remain their own specs. This one **depends on** and **enables** both; see §11 D7.\n+\n+---\n+\n+## 2) Problem statement, with evidence\n+\n+### 2.1 What the claude-code runtime actually does today\n+\n+`executeSdkQuery` is called once per turn and builds a whole new SDK query each time:\n+\n+- Resume is set from the prior SDK session id, and anchored: `sdkOptions.resume = session.sdkSessionId` and `sdkOptions.resumeSessionAt = session.lastAssistantUuid` (`apps/server/src/services/runtimes/claude-code/messaging/message-sender.ts:505-531`).\n+- The prompt is a **held** streaming-input generator that yields exactly one user message, then parks on a promise so the subprocess survives past the `result` message long enough to answer control requests (`apps/server/src/services/runtimes/claude-code/sdk/sdk-utils.ts:73-98`, `:110-112`).\n+- `const agentQuery = query({ prompt: heldPrompt.prompt, options: sdkOptions }); session.activeQuery = agentQuery;` (`message-sender.ts:690-692`).\n+- On the first `result` message the sender fetches context usage and subscription usage, then calls `heldPrompt.close()` to release stdin so the process drains and exits (`message-sender.ts:845-864`).\n+- In the `finally`, the query is demoted to `session.lastQuery` and `session.activeQuery` is cleared (`message-sender.ts:1017-1032`).\n+\n+So: **resume-per-message plus held-stream-within-turn**. The research report called this a hybrid (`research/20260610_message_queuing_agent_runtimes.md` §2.3); the source confirms it verbatim.\n+\n+The `AgentRuntime` interface has no vocabulary for any of this. `sendMessage` is the only ingress (`packages/shared/src/agent-runtime.ts:700`), `interruptQuery` is the only mid-turn control (`:794`), and the interface's own doc asserts a guarantee the server does not actually provide:\n+\n+> \"Single-flight per session: callers must not invoke `sendMessage` concurrently for the same `sessionId` — the server's trigger-turn session lock enforces this, so adapters may assume it.\"\n+> `packages/shared/src/agent-runtime.ts:692-695`\n+\n+The lock does not enforce that. `SessionLockManager.acquireLock` refuses only a **different** client: `else if (existing.clientId !== clientId) return false;` (`apps/server/src/services/session/session-lock.ts:83-89`). A same-client second turn re-acquires and runs concurrently. The lock file's own token doc names the exact case that does it: \"a compose-next auto-flush starting a second detached turn before the first settles\" (`session-lock.ts:38-45`). That is DOR-1088.\n+\n+### 2.2 The fragility classes this shape produces\n+\n+| # | Class | Where it lives | What it costs |\n+| --- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n+| F1 | `resumeSessionAt` anchor hack | `message-sender.ts:505-531` sets the anchor; `:276-279` `isAnchorNotFound`; `:963-973` the drop-anchor retry | 27 lines of comment explaining that without the anchor the CLI's resume classifier reads a trailing Stop-hook attachment as an interrupted turn and injects a synthetic \"Continue from where you left off.\" turn before the real prompt. A compacted transcript makes the anchor vanish and the CLI hard-fails. |\n+| F2 | `isResumeFailure` retries | `message-sender.ts:244-249` (four substring patterns), `:257` (`MAX_RESUME_RETRIES = 1`), `:974-989` (restart-as-new recursion) | Recovery by string-matching an error message. On a match the session silently restarts as brand new, losing history. One shared retry budget for two distinct failures, so spending it on F1 leaves none for F2. |\n+| F3 | The sdk-session rebind dance | `message-sender.ts:894-911` (in-loop rebind, awaited before the event leaves the server), `:948-956` (catch-all rebind), `trigger-turn.ts:336-342` + `:430-434` (the retried `tryRekey` and the best-effort 202) | A brand-new session gets a canonical id mid-first-turn. Every consumer (projector registry, settings row, lock, client URL) has to be moved while the turn streams. Two production incidents are named in the comments: DOR-493 and DOR-838. |\n+| F4 | Concurrent-stream seam (**DOR-1088**) | `agent-types.ts:65-71` (single `activeQuery`, single `eventQueue`, single `eventQueueNotify`); `message-sender.ts:343` (`session.eventQueue = []` at turn start); `message-sender.ts:806-827` (the race loop that registers `session.eventQueueNotify`) | A second concurrent turn on the same session wipes the first turn's queued out-of-band events, steals the notify callback, overwrites `session.activeQuery`, and then the FIRST turn's `finally` clears `activeQuery` out from under the still-running second turn, killing its interrupt path. Same-client concurrency is reachable today (§2.1). |\n+| F5 | Premature `turn_end` on multi-result turns | `sdk/event-mappers/result-event-mapper.ts:223-229` emits `done` for **every** `result`; `session/session-event-normalizer.ts:632-647` calls `closeTurn()` on **every** `done` with no already-ended guard | Today one query produces one `result`, so this never fires. The moment the stream stays open and accepts a second message, the CLI produces a second `result`, and the durable stream emits two `turn_end`s for one logical turn. This is a latent blocker that the persistent design trips on day one. |\n+| F6 | Phantom cancellation (**DOR-1087**) | Reproduced and characterized on `worktree-dor-1087-phantom-stop` (uncommitted): `messaging/phantom-cancellation.ts` | The CLI treats any message queued mid-turn as a user interruption. A background `` sitting in the CLI's internal queue when the model issues a permission-gated tool call makes the CLI cancel the call and write its interrupt sentinel as the tool_result. The model reads a human stop. Observed 2026-08-09: eight phantoms in one session, zero real denies. |\n+\n+Two further consequences of the per-turn subprocess, both measured in comments rather than benchmarks (**unverified numerically**):\n+\n+- **Cold cost every turn.** Subprocess spawn, MCP server connection, plugin activation, and prompt cache all restart per turn. `mcpServers` are deliberately re-created per query to dodge \"Already connected to a transport\" (`message-sender.ts:604-608`).\n+- **Init-time snapshots go stale.** `supportedCommands()` is captured once at session init and never reflects mid-session change, which is why plugin reload needs a second live propagation path (`claude-code-runtime.ts:439-448`).\n+\n+### 2.3 What the person actually experiences\n+\n+- Type while the agent works, and the message is held in the browser (`apps/client/src/layers/features/chat/model/use-message-queue.ts`), flushed on the streaming→idle edge, annotated server-side as a `queue_note` (`packages/shared/src/additional-context.ts:479`). It is lost on refresh and invisible to a second window.\n+- A second client mid-turn gets `409 SESSION_LOCKED`. The route test that pins this says out loud that the DOR-82 dispositions are meant to replace it: \"DOR-82 will replace this incidental semantics with explicit queue/steer/interrupt dispositions\" (`apps/server/src/routes/__tests__/sessions-cross-client.test.ts:26-27`).\n+- There is no way to say \"also do X\" without either waiting or stopping the agent. Steering exists in Codex (`turn/steer`) and Amp (`{steer:true}`) and is the single most-cited missing verb in the DOR-82 survey (§4.1-4.3 of the research report).\n+\n+---\n+\n+## 3) Goals and non-goals\n+\n+**Goals.**\n+\n+- G1. One persistent SDK query per ACTIVE claude-code session; the subprocess, its MCP connections, and its prompt cache stay warm across turns.\n+- G2. Three dispositions on the `AgentRuntime` boundary (`queue`, `steer`, `interrupt`) plus an optional fourth (`stage`), each with a declared capability and an honest server-side fallback.\n+- G3. The server owns the queue: durable across a client refresh, visible to every window, surfaced on the session snapshot and the durable stream.\n+- G4. Retire F1, F2 and F3 from the **hot path** (they survive only on the cold-start / recovery path), and close F4, F5 and F6 outright.\n+- G5. Every runtime passes an extended `runtimeConformance` covering the disposition contract, so a runtime that cannot steer says so instead of pretending.\n+- G6. No regression in the presence/durability contracts that ADR-0263/0264/0310 already hold runtimes to.\n+\n+**Non-goals.**\n+\n+- N1. Not making the persistent process survive a DorkOS restart. ADR-0264 already accepts in-flight turn loss on restart; the persistent query inherits that boundary and recovers via the resume path.\n+- N2. Not deleting `resume`. It is the fallback (constraint 2).\n+- N3. Not exposing `priority: 'now'` as a product feature until its scheduling is measured (see §11 D3). The SDK's own type still carries no prose for it at `0.3.224` (`sdk.d.ts:4757`), which is exactly the low-confidence flag the DOR-82 research raised eight weeks ago and nobody has since closed.\n+- N4. Not changing how codex or opencode run their turns.\n+\n+---\n+\n+## 4) The disposition contract\n+\n+### 4.1 Shape: one envelope field, plus a separate interrupt verb\n+\n+DOR-82 left this open (its §7 Q1). Recommendation: **`sendMessage` grows a disposition on `MessageOpts`; `interrupt` stays its own method.** Rationale:\n+\n+- `interrupt` is not a message. It carries no content, it can be issued with nothing to send after it, and it already has a route (`POST /api/sessions/:id/interrupt`, `apps/server/src/routes/sessions.ts:924-937`) and an interface method (`agent-runtime.ts:794`). Folding it into `sendMessage` would mean inventing a contentless message.\n+- `queue` / `steer` / `stage` all _are_ messages that differ only in when and how they reach the model. That is an envelope field, exactly as Amp models it (`{steer: true}`).\n+\n+```ts\n+/** How a message should reach a session that is already running a turn. */\n+export type MessageDisposition =\n+ /** Default. Run after the current turn ends. Never disturbs in-flight work. */\n+ | 'queue'\n+ /** Inject into the LIVE turn so the agent course-corrects without restarting. */\n+ | 'steer'\n+ /** Append to the transcript WITHOUT starting a turn; merges into the next one. */\n+ | 'stage';\n+\n+export interface MessageOpts extends SessionSettings {\n+ // ...existing fields...\n+ /**\n+ * How this message reaches a session mid-turn. Ignored when the session is\n+ * idle (every disposition then means \"run it now\"). Defaults to 'queue'.\n+ * A runtime that cannot honor the requested disposition MUST degrade per\n+ * the fallback ladder rather than fail, and MUST report what it actually\n+ * did on the durable stream.\n+ */\n+ disposition?: MessageDisposition;\n+}\n+```\n+\n+`interruptQuery` should be widened to return a typed receipt rather than a bare boolean, but that widening is **owned by spec `runtime-interrupt-receipts`** (`260807-231651`), which already designs `{ stopped, queuedDropped }` on top of SDK `interrupt_receipt_v1` / `cancel_queued` (`sdk.d.ts:2346`, `:3620`, `:4613`). This spec consumes that shape; it must not redefine it. See §11 D7 for the sequencing.\n+\n+### 4.2 Capability flags\n+\n+Three new booleans on `RuntimeCapabilities` (`packages/shared/src/agent-runtime.ts:461-560`), following the `supportsManagedMcpServers` precedent of being separate flags rather than a bag:\n+\n+| Flag | Means | Not the same as |\n+| --------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |\n+| `supportsPersistentSession` | The runtime keeps a warm process across turns and can accept input into it between turns | Anything about mid-turn behavior |\n+| `supportsSteer` | The runtime can deliver a message into a turn that is **already running**, without ending it | `supportsPersistentSession`: opencode is neither, codex could be the latter without the former |\n+| `supportsContextStaging` | The runtime can append to the conversation without provoking a turn (`shouldQuery: false`) | `supportsSteer`: staging does not reach a live turn |\n+\n+Queue needs no flag. The server always owns the queue, so every runtime supports it by construction. That is the whole point of the ADR-0264 seam, and it is why the queue is the fallback for everything else.\n+\n+### 4.3 Per-runtime mapping and the fallback ladder\n+\n+**The ladder (server-side, uniform):** `steer` → if unsupported, downgrade to `queue`. `stage` → if unsupported, hold the text and fold it into the next dispatched message as an `additionalContext` entry (the `queue_note` mechanism at `packages/shared/src/additional-context.ts:479` is the existing precedent for exactly this). `queue` → always available. **Every downgrade emits a `queue_update` event naming what was asked for and what happened**, so the cockpit can say \"queued instead of steered, Codex cannot steer mid-turn\" rather than silently doing something else. Honest degradation, ADR-0310 style.\n+\n+| Runtime | `queue` | `steer` | `stage` | Notes (verified) |\n+| --------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | --------------------------------------------- |\n+| **claude-code** | server queue; dispatched into the live query via `streamInput` | native: `streamInput` into the open stream (`sdk.d.ts:2610`) | native: `shouldQuery: false` (`sdk.d.ts:4764`) | The only runtime that gets all three natively |\n+| **codex** | server queue | **investigate.** The DOR-82 survey found `turn/steer` on the Codex app-server, but the shipped DorkOS adapter uses the SDK's thread API whose only interrupt primitive is an `AbortSignal` (`codex-runtime.ts:722-737`, `codex/NOTES.md:145-161`). **Unverified** whether `@openai/codex-sdk` exposes steer at all. Declare `false` until measured. | fallback | ADR-0309: fresh subprocess per turn |\n+| **opencode** | server queue | `false`. Interrupt is `POST /session/{id}/abort` (`opencode-runtime.ts:576-597`); the DOR-82 survey found the queue lives in OpenCode's own TUI, not its server | fallback | ADR-0308 sidecar |\n+| **test-mode** | server queue | `true` (deterministic fixture) | `true` | Exists to exercise the contract |\n+\n+### 4.4 What the queue itself needs\n+\n+DOR-82's §7 Q8 flagged that the session snapshot has no queue field at all. It still does not. The queue must become part of the ADR-0263 contract:\n+\n+- `SessionSnapshot` gains `queuedMessages: QueuedMessage[]` (id, content, disposition, enqueuedAt, enqueuedBy clientId).\n+- A new `queue_update` `SessionEvent` member carrying the whole queue (small, bounded, and a full replacement avoids every ordering bug an incremental diff would invite). **Reminder for EXECUTE:** every new `SessionEvent` member must join the client's allowlist or it is dropped silently.\n+- Queue mutations (enqueue, remove, reorder, edit) get routes. The cockpit's existing queue affordances (`use-message-queue.ts:13-31`, including the `restore` handle that exists because DOR-480 destroyed a person's typed words on a refused trigger) map onto them one for one.\n+\n+---\n+\n+## 5) Persistent session lifecycle\n+\n+### 5.1 States\n+\n+```\n+ first message\n+ ┌────────┐ (or explicit warm) ┌────────┐\n+ │ COLD │ ─────────────────────► │ WARMING│\n+ └────────┘ └────────┘\n+ ▲ │ system/init received\n+ │ ▼\n+ │ idle timeout / evict ┌────────┐ turn ends, queue empty\n+ ┌───────┴────────┐ ◄─────────────── │ WARM │ ◄──────────────┐\n+ │ REAPED │ └────────┘ │\n+ └────────────────┘ │ dispatch │\n+ ▲ ▼ │\n+ │ ┌─────────┐ │\n+ │ process death │ RUNNING │ ──────────────┘\n+ │ ┌──────────────────── └─────────┘\n+ │ ▼\n+ ┌──────────────┐ next dispatch ┌──────────┐\n+ │ CRASHED │ ─────────────────► │ RESUMING │ ──► WARMING\n+ └──────────────┘ └──────────┘\n+```\n+\n+| State | Invariant | `activeQuery` | Holds the write lock? |\n+| -------- | -------------------------------------------------------------------------------- | ----------------------------------- | ---------------------------- |\n+| COLD | No subprocess. Session row may exist on disk. | absent | no |\n+| WARMING | `query()` called, `system/init` not yet seen. No turn is open. | present, not yet usable for control | no |\n+| WARM | Subprocess alive, stdin held open, no turn open. Control methods answerable. | present | **no** |\n+| RUNNING | A turn is open: `turn_start` ingested, `turn_end` not yet. | present | yes, for the turn's duration |\n+| CRASHED | Subprocess exited or the generator threw outside a turn. | cleared | no |\n+| REAPED | Deliberately closed after idle. Indistinguishable from COLD except in telemetry. | cleared | no |\n+| RESUMING | Recovery: a fresh `query()` with `resume` set, exactly today's path. | — | — |\n+\n+**The load-bearing change is that WARM is a real state.** Today there is no such thing: the subprocess exists only inside a turn's `try/finally` and is closed at `message-sender.ts:1017-1020`. Making it a state is what buys warm cache, mid-turn steering, and context staging. It is also what creates every new failure mode in §7.\n+\n+### 5.2 Reap policy\n+\n+Two distinct timers, and conflating them is a trap:\n+\n+| Timer | Governs | Today | Proposal |\n+| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n+| **Process idle timeout** (new) | WARM → REAPED. How long a live subprocess sits with no turn. | n/a (process dies each turn) | Start at **5 minutes**, configurable. Long enough that a person thinking between turns keeps their cache; short enough that 50 abandoned sessions do not hold 50 subprocesses. |\n+| **Session eviction** | The in-memory `AgentSession` record. `SESSIONS.TIMEOUT_MS = 30 * 60 * 1000` (`constants.ts:113`), swept every `INTERVALS.HEALTH_CHECK_MS = 5 * 60 * 1000` (`constants.ts:5`) by `checkSessionHealth` (`session-store.ts:540-560`) | 30 min | Unchanged. Eviction implies reap, never the reverse. |\n+\n+Reaping is invisible: the next message resumes. That is what makes the process-idle timer safe to set aggressively.\n+\n+A reap **must not** happen while a pending interaction is open. `SESSIONS.INTERACTION_TIMEOUT_MS = 10 * 60 * 1000` (`constants.ts:117`) is longer than the proposed 5-minute idle window, and a reaped process cannot answer an approval the person is still looking at. See §7 FM3.\n+\n+### 5.3 Resource ceiling\n+\n+`MAX_SESSIONS = 50` (`constants.ts:119`) enforced at `session-store.ts:211-216`. With one subprocess per WARM session, 50 becomes 50 concurrent CLI processes and their MCP children. Two mitigations, both cheap:\n+\n+- Reaping is per-session and already bounds this in practice.\n+- Add a separate, lower **warm ceiling** (default 10 to 15): the process pool is LRU-reaped down to the ceiling regardless of the idle timer. Session records stay at 50; only warmth is rationed. This keeps `ensureSession`'s existing throw as a genuinely exceptional path rather than something a busy operator hits.\n+\n+---\n+\n+## 6) Turn boundaries on a long-lived query\n+\n+This is the hardest part of the design and the place where a naive implementation breaks ADR-0264.\n+\n+### 6.1 The mismatch\n+\n+Today the mapping is trivial because the units coincide: one `sendMessage` call = one `query()` = one `result` = one `done` = one `turn_end`. Verified at `sdk-event-mapper.ts:43-46` → `result-event-mapper.ts:223-229` → `session-event-normalizer.ts:636-640`.\n+\n+With a persistent query, one `query()` spans **many** `result` messages, and the CLI can start continuations DorkOS never asked for (auto-resume continuations are explicitly named in the SDK's own docs at `sdk.d.ts:3628`). The three units come apart.\n+\n+### 6.2 The rule\n+\n+**A DorkOS turn opens on dispatch and closes on the `result` that answers it.** Concretely:\n+\n+1. `feedProjector`'s `closeTurn()` becomes idempotent: guard on `ended` (`session-event-normalizer.ts:623-647`). This alone kills F5 and is the smallest correct change. It should land **first and independently**, because it is a latent bug regardless of anything else here.\n+2. `executeSdkQuery` stops being \"the turn\". It becomes a long-lived **pump** owned by the session, and a turn becomes a _window_ over that pump's output. Each dispatched message opens a window; the window closes on the correlated `result`.\n+3. **Correlation is by uuid.** `SDKUserMessage` carries an optional `uuid` (`sdk.d.ts` `SDKUserMessage`), and the CLI's queue reasons in exactly those terms: `still_queued` and `cancelled` are uuid lists (`sdk.d.ts:3628`, `:3632`). DorkOS stamps every dispatched message with its own uuid and correlates the `result` back to it. Do **not** correlate positionally: the SDK's own docs say a dequeued batch is coalesced into one turn, so several dispatched uuids can share one `result`, and text matching was already rejected once for exactly this class of ambiguity (`trigger-turn.ts:229-243`).\n+4. **A steer does not open a turn.** It joins the open window. Its content rides the existing `turn_start.userMessage`... which does not have a slot for a second message. Recommendation: a new `turn_input` `SessionEvent` carrying `{ content, disposition: 'steer' }`, ingested into the open turn. The cockpit renders it inline as a user message inside the running turn, which is what the person did.\n+5. **A `stage` message opens no turn at all.** It emits a `context_staged` event so the transcript is honest, and merges into the next dispatch per the SDK's documented `shouldQuery: false` semantics (`sdk.d.ts:4764`).\n+6. **CLI-internal continuations** (a `result` with no correlated uuid) must not be silently dropped or silently rendered as a DorkOS turn. Recommendation: open a synthetic turn tagged with an origin of `runtime`, so the durable stream stays a complete account of the session. This is the same honesty rule the presence contract already enforces (`contributing/adding-a-runtime.md`, presence table).\n+\n+### 6.3 What survives unchanged\n+\n+- The ADR-0264 pipeline: `trigger-turn` → `feedProjector` → `SessionStateProjector` → `GET /:id/events` with snapshot / gap-free replay / live. Turn _identity_ changes; the transport does not.\n+- `guardTurnErrors`' error-terminal translation (`trigger-turn.ts:492-530`). A pump-level throw must still close the open window with `status_change(error)`, a typed `error`, and one `turn_end(error)`.\n+- The stall watchdog (`trigger-turn.ts:378-384`, `services/session/stall-guard.ts`). It measures inactivity **within a turn window** and must not fire on a WARM session that is legitimately silent. This needs an explicit guard: the watchdog arms on window open and disarms on window close.\n+\n+---\n+\n+## 7) Locking, serialization, and DOR-1088\n+\n+### 7.1 The lock's job changes\n+\n+The write lock exists to prevent two clients writing one conversation at once. With a server queue, the honest answer for a second writer is no longer 409; it is **accept and queue**. That is DOR-82's recommendation 5 and the route test's own stated future (`sessions-cross-client.test.ts:26-27`).\n+\n+Recommendation: **keep the lock, retarget it.** It stops being \"who may POST\" and becomes \"who may currently _dispatch_ into the query\" — an internal dispatch mutex held for the length of one turn window, not an HTTP-visible gate. `POST /messages` then returns 202 with a queue position instead of 409. The lock's liveness machinery (`LockActivity`, `session-lock.ts:22-30`, DOR-782) carries over unchanged and is still what reclaims a dark turn.\n+\n+### 7.2 DOR-1088 is a prerequisite, not a side effect\n+\n+The single-flight guarantee the interface _claims_ (`agent-runtime.ts:692-695`) is the guarantee the persistent design _needs_, and it is false today (§2.1, §2.2 F4). Two options:\n+\n+- **(a) Enforce it.** Make the lock reject same-client concurrent dispatch too, and route the second message into the queue.\n+- **(b) Support it.** Make the session's shared mutable state (`activeQuery`, `eventQueue`, `eventQueueNotify` at `agent-types.ts:65-71`) per-turn rather than per-session.\n+\n+**Recommendation: (a).** A persistent query is a single input stream by construction, so genuinely parallel turns on one session are not expressible anyway. Option (b) buys nothing the queue does not already buy, and it multiplies the state the CLI's own queue is already reasoning about. Deliver (a) as DOR-1088 **before** the persistent pump lands, so the pump is built on a guarantee that is actually true.\n+\n+Note the relay's `enqueueForSession` (`packages/relay/src/adapters/runtime-adapter.ts:173-187`, ADR-0075) already serializes per session for exactly this reason. It is the right shape and it is at the wrong layer: it protects relay-driven messages and knows nothing about cockpit-driven ones. The server queue subsumes it.\n+\n+### 7.3 The other trigger paths\n+\n+Every one of these calls `sendMessage` or `executeCommandIntent` and therefore contends: `routes/sessions.ts:695`, `routes/session-ui-action-handler.ts:100`, `routes/session-command-intent-handler.ts:149`, `services/rooms/room-turn-runner.ts:277`, `services/session/embedded-turn-trigger.ts:80` and `:148`, `services/tasks/run-stream.ts`, `services/mesh/mcp-signin-resume.ts:196`. `executeCommandIntent` for claude-code is literally `sendMessage('/compact')` (`claude-code-runtime.ts:422-430`), so it contends identically. **The queue must be the single ingress for all of them**, or one of them keeps the old race.\n+\n+---\n+\n+## 8) Failure modes\n+\n+| # | Failure | Today | With a persistent session | Required behavior |\n+| --- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n+| FM1 | Process dies mid-turn | One turn lost; next turn resumes. Blast radius is a turn. | Blast radius is the **session**: warm cache, in-flight turn, and every queued message behind it | Detect exit, close the open window with `turn_end(terminalReason:'error')`, transition to CRASHED, **preserve the queue**, and RESUME on the next dispatch. The queue surviving a crash is the whole justification for it being server-owned. |\n+| FM2 | Server restart | ADR-0264 accepts in-flight turn loss; a `streaming` turn is marked `interrupted` on cold hydrate | Same, plus every warm process is orphaned | Kill orphans in `shutdownServices()` (the opencode sidecar teardown is the model, `contributing/adding-a-runtime.md` step 7). Queue durability across restart: see §11 D5. |\n+| FM3 | Idle reap while an approval is pending | Cannot happen: the subprocess is held open by the turn | **Can** happen: the person walks away, the reaper fires, the approval is answered into a dead process | Reap is forbidden while `projector.hasPendingInteractions()` is true. That probe already exists and is already shared by the lock and the stall watchdog (`trigger-turn.ts:291`). Reuse it; do not invent a third liveness notion. |\n+| FM4 | Queued message fires during a pending permission prompt | n/a | The classic bug, shipped by Gemini (#17719) and OpenCode (#2609) per the DOR-82 survey §4.3 | Dispatch is gated on the same pending-interaction probe. Test it explicitly. |\n+| FM5 | Queued messages dropped on interrupt | n/a | OpenCode #5333 | Interrupt semantics must be **declared**: does Stop mean \"stop this turn\" or \"stop everything\"? The SDK models both (`cancel_queued`, `sdk.d.ts:3620`). See §11 D4. |\n+| FM6 | Premature dequeue | n/a | OpenCode #15696 | Dequeue happens on `turn_end`, never on `result` alone (§6.2). Pinned by test. |\n+| FM7 | Phantom cancellation (DOR-1087) | Live bug | **Should disappear**, because DorkOS stops racing the CLI's internal queue: with a persistent stream, DorkOS controls when messages enter it and can hold dispatch until the turn window closes. **Unverified.** | Do not assume. Keep the DOR-1087 detector (`phantom-cancellation.ts`) as a **regression tripwire** past the migration: if it ever fires on the persistent path, the design is wrong somewhere. Delete it only after a measured quiet period. |\n+| FM8 | Reap races a dispatch | n/a | The reaper decides to close while a message is being dispatched | Reap and dispatch share the dispatch mutex (§7.1). A reap that loses simply does not happen. |\n+| FM9 | Warm process holds a stale account / cwd / credential | n/a | `accountRoot` is resolved per turn today (`message-sender.ts:450`, spec `claude-code-accounts` D3), as is the credential env (`:429`) and the agent identity token (`:437`) | A warm process pins whatever it was launched with. Any change to account, cwd, model-that-requires-relaunch, or credential must **force a reap** and relaunch. Enumerate the full pin list in SPECIFY; getting it wrong bills a paying client's conversation to the wrong account. |\n+\n+---\n+\n+## 9) Migration and rollout\n+\n+**Per-session opt-in, config-gated, defaulting off, promoted to on in a later release.** Not a global flag, not a hard cutover.\n+\n+Why per-session rather than a global flag: the two paths must be able to run side by side on one host, because that is the only way to compare them on the same workload, and because the fallback path is not going away (constraint 2). The mechanism is a config field under `runtimes.claudeCode` (`packages/shared/src/config-schema.ts`) plus the semver-keyed migration the `adding-config-fields` skill requires.\n+\n+Sequenced so each step is independently shippable and independently revertable:\n+\n+| Step | Ships | Reverts by |\n+| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |\n+| 0 | Idempotent `closeTurn` (F5). Pure bug fix, no flag. | git revert |\n+| 1 | DOR-1088: single-flight enforced, second message queued. | flag off → 409 as before |\n+| 2 | Server-owned queue behind the trigger POST. Snapshot + `queue_update` + routes. Client queue reads the server's. Dispositions accepted, all mapped to `queue`. | flag off → client-side queue |\n+| 3 | Persistent pump for claude-code, opt-in. Resume path becomes the fallback. Reaper, warm ceiling, pin list. | flag off → resume-per-message |\n+| 4 | `steer` and `stage` wired natively for claude-code; capability flags for all four runtimes; conformance extended. | capability flag false → fallback ladder |\n+| 5 | Default flipped on; DOR-1087 tripwire watched; phantom detector removed after a quiet period. | flag off |\n+\n+**The comparison that decides step 5** must be measured, not asserted: time-to-first-token per turn, cache-read token ratio, resident subprocess count, phantom-cancellation rate. Ideation deliberately makes no performance claim; the numbers in §2.2 are marked unverified for that reason.\n+\n+---\n+\n+## 10) Conformance additions\n+\n+Every one of these goes in `packages/test-utils/src/runtime-conformance.ts` (currently 1259 lines, `describe` blocks at `:581-1244`), because a capability that is not conformance-tested is a capability a runtime can lie about. The suite already proves this discipline works: `validatePresenceReport` exists precisely so a runtime cannot fabricate presence.\n+\n+New `RuntimeConformanceOpts` and cases:\n+\n+1. **Disposition honesty.** For each of `steer` / `stage`: if the capability is declared, a mid-turn message must reach the model without a new `turn_start`; if it is not declared, the same call must degrade to `queue` and emit the downgrade notice. Neither may throw.\n+2. **Terminal exactly once.** A turn window emits exactly one `turn_end`, no matter how many native `result`s the backend produced. This is the F5 guard, and it must be provable by **seeding the defect** (drop the idempotence guard, watch it go red).\n+3. **Queue durability.** A message queued behind a turn that then fails must still run (FM1) and must not run during a pending interaction (FM4).\n+4. **Persistence honesty.** A runtime declaring `supportsPersistentSession` must report `idle` (not `streaming`) while WARM. The existing presence table already forbids `streaming` with an empty `inProgressTurn`; WARM is a new way to get that wrong.\n+5. **Reap safety.** Driving a session to WARM, reaping it, and sending again must produce a well-formed turn. The person cannot tell.\n+\n+Cases 1 and 4 need a driver in the mould of `presenceTurn` / `drivePresenceTurn`, for the same stated reason: a `sendMessage` generator alone moves no projector and would assert nothing. Omitted driver = a named skip, never a silent pass.\n+\n+---\n+\n+## 11) Open decisions, with recommended answers\n+\n+| # | Decision | Options | Recommendation | Confidence |\n+| ------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |\n+| **D1** | Interface shape for dispositions | (a) `sendMessage(..., { disposition })` + separate `interrupt`; (b) explicit verbs `enqueueMessage` / `steer(turnId, content)` / `interrupt` | **(a)**, per §4.1. Fewer methods for a new runtime author to implement, and it matches Amp's portable `{steer: true}` envelope. Codex's `expectedTurnId` requirement is served by the correlation uuid, adapter-internal. | High |\n+| **D2** | Default disposition for a mid-turn message | queue / steer / ask the person per message | **`queue`**, matching the SDK default and every surveyed TUI (DOR-82 §4.1). Steer is opt-in via a composer affordance. Calm by default; the person opts into disruption. | High |\n+| **D3** | Use SDK `priority: 'now' \\| 'next' \\| 'later'`? | Adopt / ignore / measure first | **Measure first, do not ship on it.** The field still has no prose doc at `0.3.224` (`sdk.d.ts:4757`). DOR-82 §3.2 flagged this as low confidence and it is still open. Ship `steer` on `streamInput`, whose behavior IS documented (`sdk.d.ts:2610`). Revisit `priority: 'now'` only with an empirical result. | High |\n+| **D4** | Does Stop mean \"stop this turn\" or \"stop everything queued\"? | Turn-only / everything / a person-facing choice | **Everything, by default.** The SDK's own doc says a remote UI's Stop button is the `cancel_queued: true` case (`sdk.d.ts:3620`). A person who presses Stop with three messages queued and watches the next one fire has been lied to. Surface the count in the confirmation (\"Stop, and drop 3 queued messages?\"). | Medium: needs the receipt work (D7) to report honestly |\n+| **D5** | Does the queue survive a server restart? | In-memory / persist to SQLite `session_metadata`-adjacent table | **Persist.** The queue is the person's typed words. ADR-0264 accepts losing an in-flight _turn_ on restart; losing a message somebody typed and was told was accepted is a different and worse promise to break. DOR-480 already established that this class of loss is unacceptable (`use-message-queue.ts:13-31`). | Medium: adds a migration; could slip to a follow-up if it threatens the phase-2 ship |\n+| **D6** | Warm process ceiling | None / equal to `MAX_SESSIONS` (50) / a separate lower number | **Separate, default 10 to 15, configurable.** 50 concurrent CLI subprocesses plus their MCP children on a laptop is not a shape to ship untested; and warmth is a cache, so LRU eviction is exactly right for it. | Medium: the number wants one measurement |\n+| **D7** | Relationship to `runtime-interrupt-receipts` and `runtime-prompt-redelivery` | Absorb them / depend on them / ignore | **Depend, and sequence.** `runtime-interrupt-receipts` (`260807-231651`) owns the typed interrupt result and `cancel_queued`; this spec consumes it and must not redefine it. `runtime-prompt-redelivery` (`260807-231653`) owns `reinitialize()` (`sdk.d.ts:2452`), which becomes **more** valuable here (a warm process that survives a client gap is exactly what it recovers). Land interrupt-receipts alongside phase 4; prompt-redelivery can follow. | High |\n+| **D8** | What happens to the client-side queue (ADR-0104) | Keep both / replace / keep as offline buffer | **Replace, preserving the UX.** Two queues means two sources of truth and a reconciliation bug waiting to happen. ADR-0104 gets superseded by the ADR this spec produces. | High |\n+| **D9** | Does `stage` ship in this programme or later? | Now / later | **Now, but last** (phase 4, behind `supportsContextStaging`). It is the cheapest of the three natively (one boolean on the message) and it is the one that answers the original operator question, \"can I pass information in without stopping the run?\" Cutting it would leave the contract two-thirds done. | Medium |\n+| **D10** | Do phantom-cancellation defences (DOR-1087) get deleted after migration? | Delete on cutover / keep as tripwire / keep forever | **Keep as a tripwire through phase 5, then delete.** The hypothesis that persistence removes the phantom class is untested (FM7). A detector that never fires is cheap; a silently returned phantom is expensive. Deleting it is a scheduled task, not an assumption. | High |\n+\n+---\n+\n+## 12) Phase plan into SPECIFY and DECOMPOSE\n+\n+**SPECIFY produces:** the disposition contract as concrete TypeScript on `AgentRuntime` and `RuntimeCapabilities`; the queue's persisted schema and its `SessionSnapshot` / `SessionEvent` additions; the state machine as an implementable table with every transition's trigger and guard; the complete relaunch-pin list (FM9); the conformance case list with its drivers; and the config field plus its semver-keyed migration.\n+\n+**Draft ADRs SPECIFY should seed (per `writing-adrs`):**\n+\n+- **ADR-a: Three dispositions at the `AgentRuntime` boundary.** Supersedes nothing; extends the ADR-0263 vocabulary.\n+- **ADR-b: Persistent streaming-input sessions for claude-code, with resume as the recovery path.** Records the WARM state and the reap policy.\n+- **ADR-c: Server-owned durable message queue.** **Supersedes ADR-0104** (client-side queue with auto-flush). Amends ADR-0264 by naming the queue as the thing that sits behind the trigger-only POST, which ADR-0264's own context anticipated.\n+\n+**Phases for DECOMPOSE**, matching the rollout table in §9 so each phase is a shippable, revertable slice:\n+\n+| Phase | Scope | Rough shape | Gates on |\n+| ------ | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |\n+| **P0** | Idempotent `closeTurn` (F5) | 1 task, tiny, no flag | nothing |\n+| **P1** | DOR-1088 single-flight | 2 to 3 tasks: lock semantics, all-ingress audit (§7.3), tests | P0 |\n+| **P2** | Server-owned queue | 6 to 8 tasks: schema + persistence (D5), snapshot/event contract, routes, client cutover, `queue_note` continuity, ADR-0104 supersession | P1 |\n+| **P3** | Persistent pump, opt-in | 8 to 10 tasks: pump lifecycle, turn windowing + uuid correlation, reaper + warm ceiling, pin list, crash/resume, stall-guard rearm, config + migration | P2 |\n+| **P4** | Dispositions native + capabilities + conformance | 6 to 8 tasks: `steer` via `streamInput`, `stage` via `shouldQuery`, four runtimes' flags, fallback ladder + downgrade notice, conformance suite, interrupt-receipt integration (D7) | P3 |\n+| **P5** | Default on, measure, clean up | 3 to 4 tasks: measurement pass, flip, DOR-1087 tripwire watch, detector removal (D10) | P4 |\n+\n+P0 and P1 are worth dispatching immediately: both are correctness fixes that stand on their own merits whether or not the rest of the programme proceeds.\n+\n+---\n+\n+## 13) Pre-reading log\n+\n+| Read | Takeaway |\n+| --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n+| `research/20260610_message_queuing_agent_runtimes.md` | The foundation. Four-pattern taxonomy, cross-runtime matrix, the recommendation this programme executes. Its §7 open questions map to §11 here, and Q1/Q2/Q4/Q5/Q8 are answered. |\n+| `apps/server/src/services/runtimes/claude-code/messaging/message-sender.ts` | The whole current turn pipeline, all 1062 lines of it. Sources for F1, F2, F3, F4, and the held-prompt design. |\n+| `apps/server/src/services/runtimes/claude-code/sdk/sdk-utils.ts` | `createHeldPrompt` (`:73-98`) is the seam the persistent pump grows out of. The DOR-1087 branch has already converted it to a queue-driven generator with `push()`, which is very close to what §6 needs. |\n+| `packages/shared/src/agent-runtime.ts` | The interface to extend. Its `sendMessage` single-flight claim (`:692-695`) is false today, which is DOR-1088. |\n+| `decisions/0264-server-owned-durable-resumable-session-stream.md` | Trigger-only POST, projector, snapshot → replay → live. The seam the queue belongs behind, and the restart loss boundary the persistent design inherits. |\n+| `decisions/0075-promise-chain-queue-for-cca-concurrency.md` | Per-session promise chain, now generalized to `enqueueForSession`. Right shape, wrong layer: it protects relay traffic only. |\n+| `contributing/adding-a-runtime.md` | What a new capability costs a runtime author: capability flag, conformance case, honest degradation. The presence-truthfulness section is the model for how the disposition flags should be policed. |\n+| `packages/test-utils/src/runtime-conformance.ts` | 1259 lines; `RuntimeConformanceOpts` at `:44-131`. The driver pattern (`presenceTurn`, `durableHistory`) is what the new cases need. |\n+| `apps/server/src/services/session/{trigger-turn,session-lock,session-event-normalizer}.ts` | Lock lifetime, canonical-id race, stall guard, and the `closeTurn` that fires on every `done`. |\n+| `sdk.d.ts` @ `0.3.224` | `streamInput` `:2610`, `interrupt` receipt `:2346`, `reinitialize` `:2452`, `priority` `:4757` (still undocumented), `shouldQuery` `:4764`, `cancel_queued` `:3620`, capability feature-detection `:4613`. |\n+| `specs/runtime-interrupt-receipts/01-ideation.md`, `specs/runtime-prompt-redelivery/01-ideation.md` | Adjacent, already-ideated. Boundaries drawn in D7. |\n+| `worktree-dor-1087-phantom-stop` (uncommitted) | The live phantom-cancellation characterization: the CLI's interrupt sentinel, verbatim, and why DorkOS can tell a phantom from a real deny. |", "status": "added"}, {"additions": 735, "deletions": 0, "filename": "specs/persistent-session-runtime/02-specification.md", "patch": "@@ -0,0 +1,735 @@\n+# Persistent session runtime, and the queue / steer / interrupt contract\n+\n+**Status:** Approved (frozen for DECOMPOSE)\n+**Work item:** DOR-1089 · **Slug:** `persistent-session-runtime` · **Id:** `260810-003853`\n+**Date:** 2026-08-09\n+**Input:** [`01-ideation.md`](01-ideation.md) (all ten open decisions resolved; see §3)\n+\n+---\n+\n+## Overview\n+\n+Move the claude-code runtime off resume-per-message onto a **persistent streaming-input session**: one long-lived SDK `query()` per active session, with an idle timeout that closes the process, and today's `resume` path demoted to the crash / restart / cold-start fallback.\n+\n+On top of that, standardize how a message reaches a session that is already busy. Three dispositions become first-class at the server ingress: **queue** (default, run after the current turn), **steer** (inject into the live turn), **stage** (append to the transcript without provoking a turn). Interrupt stays a separate verb. Each disposition carries a capability flag, and a runtime that cannot honor one degrades down a uniform ladder and says so out loud rather than silently doing something else.\n+\n+The server owns the queue. That is the load-bearing architectural commitment: it is what makes a queued message survive a refresh, a second window, a crashed turn, and a server restart, and it is what lets three runtimes with three different process models present one honest contract.\n+\n+---\n+\n+## Background / Problem Statement\n+\n+The full evidence trace is in [`01-ideation.md` §2](01-ideation.md), with `file:line` pointers verified at `e4b9e1a9b`. The short form:\n+\n+**The current shape.** `executeSdkQuery` builds a fresh SDK query per turn (`message-sender.ts:690-692`), resumes the prior SDK session with an anchor (`:505-531`), holds stdin open only long enough to answer control requests inside that turn (`sdk-utils.ts:73-98`), and closes the process on the first `result` (`message-sender.ts:845-864`). Resume-per-message plus held-stream-within-turn.\n+\n+**What that costs.** Six fragility classes, four of them live:\n+\n+| Class | Status |\n+| ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |\n+| F1 `resumeSessionAt` anchor hack (`message-sender.ts:505-531`, `:276-279`, `:963-973`) | live, hot path |\n+| F2 `isResumeFailure` retries by substring match (`message-sender.ts:244-249`, `:257`, `:974-989`) | live, hot path |\n+| F3 sdk-session rebind dance (`message-sender.ts:894-911`, `trigger-turn.ts:336-342`) | live, cost two incidents (DOR-493, DOR-838) |\n+| F4 concurrent-stream seam | **being closed now** as DOR-1088; see §4 |\n+| F5 premature `turn_end` on multi-result turns (`result-event-mapper.ts:223-229` + `session-event-normalizer.ts:632-647`) | latent; fires on day one of a persistent stream |\n+| F6 phantom cancellation (DOR-1087) | live; eight phantoms in one session, zero real denies (observed 2026-08-09) |\n+\n+**What the person experiences.** Type while the agent works and the words sit in the browser, lost on refresh, invisible to a second window (`use-message-queue.ts`). A second client mid-turn gets `409 SESSION_LOCKED`, and the route test that pins that behavior already names its replacement: \"DOR-82 will replace this incidental semantics with explicit queue/steer/interrupt dispositions\" (`apps/server/src/routes/__tests__/sessions-cross-client.test.ts:26-27`). There is no way at all to say \"also do X\" without waiting or stopping.\n+\n+---\n+\n+## Goals\n+\n+- **G1.** One persistent SDK query per ACTIVE claude-code session; subprocess, MCP connections, and prompt cache stay warm across turns.\n+- **G2.** `queue` / `steer` / `stage` expressed once at the server ingress, resolved into runtime primitives behind declared capability flags, with a uniform degradation ladder and a visible downgrade notice.\n+- **G3.** A server-owned queue that survives client refresh, multi-window, turn failure, and server restart.\n+- **G4.** F1, F2, F3 confined to the cold-start / recovery path; F5 and F6 closed outright. (F4 closes as DOR-1088, a prerequisite.)\n+- **G5.** Every runtime passes an extended `runtimeConformance` covering dispositions, warmth honesty, and terminal-exactly-once.\n+- **G6.** No regression against the ADR-0263 / 0264 / 0310 contracts: snapshot to gap-free replay to live, presence truthfulness, per-runtime degradation.\n+\n+## Non-Goals\n+\n+- **N1.** The persistent process does **not** survive a DorkOS restart. ADR-0264 already accepts in-flight turn loss on restart; the pump inherits that boundary and recovers through resume.\n+- **N2.** `resume` is not deleted. It is the recovery route.\n+- **N3.** No reliance on the SDK's `priority` field (D3).\n+- **N4.** Codex and OpenCode do not become persistent. They gain vocabulary and honest flags only.\n+- **N5.** No horizontal scaling / cross-process session affinity.\n+- **N6.** No composer redesign. This changes what the composer can ask for, not how it looks.\n+\n+---\n+\n+## Technical Dependencies\n+\n+| Dependency | Version | Why |\n+| --------------------------------------------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n+| `@anthropic-ai/claude-agent-sdk` | `0.3.224` (pinned, `apps/server/package.json:26`) | `streamInput` (`sdk.d.ts:2610`), `shouldQuery` (`:4764`), interrupt receipt (`:2346`), `cancel_queued` (`:3620`), `reinitialize` (`:2452`), capability feature-detection (`:4613`) |\n+| **DOR-1088** (`worktree-dor-1088-stream-serialize`) | in flight | **Hard prerequisite.** See §4 |\n+| `runtime-interrupt-receipts` (spec `260807-231651`) | not started | Owns the typed interrupt result and `cancel_queued`. This spec consumes it (D7) |\n+| `runtime-prompt-redelivery` (spec `260807-231653`) | not started | Owns `reinitialize()`. Composes with warm sessions; not a blocker |\n+\n+Capability detection is by **feature flag from `system/init`, never by version sniffing**, per the SDK's own instruction at `sdk.d.ts:4613`. A CLI that does not advertise `interrupt_cancel_queued_v1` gets the documented older behavior and the client is told so.\n+\n+---\n+\n+## Detailed Design\n+\n+### 1. What DOR-1088 lands, and what this spec builds on top of it\n+\n+DOR-1088 is being implemented right now on `worktree-dor-1088-stream-serialize`. This spec assumes it lands first. Its shape, read from that branch:\n+\n+- **`apps/server/src/services/session/turn-queue.ts` (new).** `SessionTurnQueue.reserve(sessionId, clientId)` returns a `TurnSlot { ready: Promise; release(): void }`. A per-`(session, client)` promise chain, the same shape as `RuntimeAdapter.enqueueForSession` (ADR-0075). Registration is synchronous, so two triggers in one tick are ordered by arrival.\n+- **`trigger-turn.ts`.** Reserves the slot before anything else and awaits `slot.ready`; releases it in `releaseOnce` and on the launch-throw path. The 202 now resolves only once the queued turn actually **starts**, so the trigger POST is held open for as long as the turn ahead of it runs.\n+- **`session-lock.ts`.** `acquireLock` refuses **any** live lock, including the same client's. The same-client re-acquire that let one browser tab start a second turn beside its own is gone. Expired locks are still reclaimable, so a crashed holder still frees its session.\n+- **`message-sender.ts`.** The `finally` learns to clear `session.activeQuery` only when the frame still owns it, so a late-settling frame cannot strand its successor. _(In progress on that branch at time of writing: the comment has landed, the guard has not. Treat the guard as part of DOR-1088's definition of done, not as work for this spec.)_\n+\n+**What DOR-1088 gives this spec:** the single-flight guarantee `AgentRuntime.sendMessage` has always claimed (`agent-runtime.ts:692-695`) and never had. The persistent pump is built on that guarantee being true.\n+\n+**What DOR-1088 deliberately does not give:** a durable queue. Its chain is in-memory, per-client, invisible to other windows, lost on restart, and it holds an HTTP socket open per waiting message. **P2 of this spec upgrades it**: same ordering guarantee, but the queue becomes durable, cross-client, inspectable, mutable, and the 202 returns immediately with a queue position instead of holding the request. `SessionTurnQueue` then becomes an internal detail of the dispatcher rather than the thing an HTTP request waits on.\n+\n+### 2. The disposition contract\n+\n+#### 2.1 Where each piece lives\n+\n+The approved D1 answer is \"envelope plus a separate interrupt verb, not three new required runtime verbs\". Implementing it revealed one refinement, recorded as `Q1 (RESOLVED)` in §Open Questions: **the envelope lives at the server ingress; at the `AgentRuntime` boundary it resolves into two shapes**, because a steer produces events belonging to a turn whose generator is already being consumed by another `feedProjector` call, and therefore cannot itself return a turn-shaped generator.\n+\n+| Layer | Surface |\n+| -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |\n+| Ingress (`POST /messages`, room runner, tasks, embedded, relay, MCP) | one envelope field: `disposition` |\n+| Server queue + dispatcher | resolves disposition against capability + live session state, applies the ladder, emits the outcome |\n+| `AgentRuntime` | `sendMessage` (unchanged signature, opens a turn) **plus** one new optional method `deliverIntoTurn` (does not open a turn) |\n+\n+#### 2.2 Shared types (`packages/shared/src/agent-runtime.ts`)\n+\n+```ts\n+/**\n+ * How a message should reach a session that is already running a turn.\n+ *\n+ * Ignored when the session is idle: every disposition then means \"run it now\".\n+ * Defaults to `'queue'` at every ingress (spec `persistent-session-runtime`, D2).\n+ */\n+export type MessageDisposition =\n+ /** Run after the current turn ends. Never disturbs in-flight work. */\n+ | 'queue'\n+ /** Inject into the LIVE turn so the agent course-corrects without restarting. */\n+ | 'steer'\n+ /** Append to the transcript WITHOUT provoking a turn; merges into the next one. */\n+ | 'stage';\n+\n+/** Why the server applied a disposition other than the one asked for. */\n+export type DispositionDowngradeReason =\n+ /** The resolved runtime does not declare the requested capability. */\n+ | 'unsupported'\n+ /** Nothing was running, so the message simply ran. Not a degradation to apologise for. */\n+ | 'session-idle'\n+ /** The turn closed between acceptance and delivery. */\n+ | 'no-open-turn'\n+ /** The session is parked on an approval/question/elicitation; delivery would fire into it. */\n+ | 'pending-interaction';\n+\n+/** What actually happened to a message the server accepted. */\n+export interface MessageDeliveryOutcome {\n+ /** Server-minted id. The queue, the durable stream, and the runtime all key on it. */\n+ messageId: string;\n+ /** What the caller asked for. */\n+ requested: MessageDisposition;\n+ /** What the server actually did. */\n+ applied: MessageDisposition;\n+ /** Present only when `applied !== requested`. */\n+ degradedBecause?: DispositionDowngradeReason;\n+}\n+```\n+\n+`MessageOpts` gains two fields:\n+\n+```ts\n+export interface MessageOpts extends SessionSettings {\n+ // ...existing fields unchanged...\n+\n+ /**\n+ * How this message reaches a session mid-turn. Defaults to `'queue'`.\n+ * Resolved by the server BEFORE the runtime is called: by the time an adapter\n+ * sees `sendMessage`, the decision to open a turn has already been made.\n+ */\n+ disposition?: MessageDisposition;\n+\n+ /**\n+ * Server-minted correlation id for this message.\n+ *\n+ * A persistent query spans many turns, so a `result` must be matched back to\n+ * the message that caused it. Correlation is by id and never positional: the\n+ * SDK coalesces a dequeued batch into one turn (`sdk.d.ts:3628`), so several\n+ * dispatched ids can share one `result`, and text matching was already\n+ * rejected for this exact ambiguity (`trigger-turn.ts:229-243`).\n+ */\n+ messageId?: string;\n+}\n+```\n+\n+#### 2.3 The new optional runtime method\n+\n+```ts\n+/** Non-turn-opening delivery modes. */\n+export type DeliverMode = 'steer' | 'stage';\n+\n+/** Inputs for {@link AgentRuntime.deliverIntoTurn}. */\n+export interface DeliverIntoTurnOpts {\n+ /** `'steer'` reaches the live turn; `'stage'` reaches the transcript only. */\n+ mode: DeliverMode;\n+ /** The server-minted correlation id (see {@link MessageOpts.messageId}). */\n+ messageId: string;\n+ /** Neutral additional-context bag, assembled server-side exactly as for a turn (ADR-0273). */\n+ additionalContext?: AdditionalContext;\n+}\n+\n+/** What a runtime did with a {@link AgentRuntime.deliverIntoTurn} call. */\n+export interface RuntimeDeliveryResult {\n+ /** True when the content reached the backend. */\n+ delivered: boolean;\n+ /** Why not. Present only when `delivered` is false. */\n+ reason?: 'no-open-turn' | 'stream-closed' | 'unsupported';\n+}\n+```\n+\n+```ts\n+export interface AgentRuntime {\n+ // ...existing members unchanged...\n+\n+ /**\n+ * Deliver a message into a session WITHOUT opening a turn.\n+ *\n+ * `'steer'` requires a turn to be open and injects into it; the resulting\n+ * events surface on that turn's already-running stream, which is why this\n+ * returns a receipt rather than a generator. `'stage'` requires no open turn\n+ * and provokes none.\n+ *\n+ * Called ONLY when the matching capability is declared\n+ * (`supportsSteer` / `supportsContextStaging`). Optional on the interface so a\n+ * runtime that can do neither simply does not implement it; the server's\n+ * degradation ladder covers the gap, so a missing implementation is never an\n+ * error the person sees.\n+ *\n+ * MUST NOT throw for an ordinary refusal. Report it as\n+ * `{ delivered: false, reason }` so the server can degrade rather than fail\n+ * the message.\n+ *\n+ * @param sessionId - Target session.\n+ * @param content - The user's text, pristine. Context rides `additionalContext`.\n+ * @param opts - Mode, correlation id, and the neutral context bag.\n+ */\n+ deliverIntoTurn?(\n+ sessionId: string,\n+ content: string,\n+ opts: DeliverIntoTurnOpts\n+ ): Promise;\n+\n+ /**\n+ * Current process warmth for a runtime that keeps sessions warm.\n+ * Runtimes with no warm concept omit this entirely; the platform reads\n+ * `'cold'` for them and never asks them to reap.\n+ */\n+ getSessionWarmth?(sessionId: string): SessionWarmth;\n+\n+ /**\n+ * Close a warm process without touching the session record or its transcript.\n+ * Idempotent, and a no-op when the session is not warm. Never called while the\n+ * session holds a pending interaction (spec §5, FM3).\n+ */\n+ reapSession?(sessionId: string): Promise;\n+}\n+```\n+\n+`interruptQuery`'s widening to a typed receipt is **owned by `runtime-interrupt-receipts`** (D7). This spec consumes whatever that spec lands and must not redefine it. Until it lands, `interruptQuery(): Promise` stays as is and the client says \"stop requested\" rather than \"stopped\".\n+\n+#### 2.4 Capability flags\n+\n+Three new required booleans on `RuntimeCapabilities` (`agent-runtime.ts:461-560`). Required, not optional, following the `commandIntents` / `settings` precedent (ADR-0256): compile-time forcing so no adapter can silently omit one.\n+\n+```ts\n+export interface RuntimeCapabilities {\n+ // ...existing members unchanged...\n+\n+ /** The runtime keeps a warm process across turns and can accept input between them. */\n+ supportsPersistentSession: boolean;\n+\n+ /** The runtime can deliver a message into a turn that is ALREADY RUNNING, without ending it. */\n+ supportsSteer: boolean;\n+\n+ /** The runtime can append to the conversation without provoking a turn. */\n+ supportsContextStaging: boolean;\n+}\n+```\n+\n+There is deliberately **no** `supportsQueue`. The server always owns the queue, so every runtime supports queueing by construction. That is the whole point of the ADR-0264 seam and it is why queue is the floor of the ladder.\n+\n+#### 2.5 The degradation ladder\n+\n+Uniform, server-side, applied before the runtime is called:\n+\n+```\n+steer → runtime declares supportsSteer AND a turn is open AND no pending interaction\n+ → deliverIntoTurn({ mode: 'steer' })\n+ else → queue\n+stage → runtime declares supportsContextStaging\n+ → deliverIntoTurn({ mode: 'stage' })\n+ else → hold and fold into the next dispatched message as an\n+ `additionalContext` entry (the `queue_note` mechanism at\n+ `packages/shared/src/additional-context.ts:479` is the precedent)\n+queue → always available\n+```\n+\n+**Every downgrade emits a `queue_update` event carrying the `MessageDeliveryOutcome`.** The cockpit then says \"queued instead of steered, Codex cannot steer mid-turn\" rather than silently doing something else. `applied: 'queue', requested: 'steer', degradedBecause: 'session-idle'` is the one case the UI should stay quiet about, because \"it ran immediately\" is not a degradation anybody needs told.\n+\n+#### 2.6 Per-runtime declarations\n+\n+| Runtime | `supportsPersistentSession` | `supportsSteer` | `supportsContextStaging` | Basis |\n+| ------------- | --------------------------- | ----------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n+| `claude-code` | `true` (after P3) | `true` (after P4) | `true` (after P4) | `streamInput` `sdk.d.ts:2610`; `shouldQuery` `:4764` |\n+| `codex` | `false` | `false` | `false` | Fresh subprocess per turn (ADR-0309); its only interrupt primitive is an `AbortSignal` (`codex-runtime.ts:722-737`, `codex/NOTES.md:145-161`). Whether `@openai/codex-sdk` exposes `turn/steer` at all is **unverified**; declaring `false` is the honest answer until measured. Re-open with a live probe, not a doc read. |\n+| `opencode` | `false` | `false` | `false` | Sidecar (ADR-0308); interrupt is `POST /session/{id}/abort` (`opencode-runtime.ts:576-597`). The DOR-82 survey found OpenCode's queue lives in its own TUI, not its server. |\n+| `test-mode` | `true` | `true` | `true` | Exists to exercise the contract deterministically |\n+\n+All three flags land as `false` for every runtime in **P2**, so the shape is in place and conformance is green before any behavior changes. P3 flips `supportsPersistentSession` for claude-code; P4 flips the other two.\n+\n+### 3. The server-owned queue\n+\n+#### 3.1 Data model\n+\n+New table, sibling to `session_metadata`, migrated through the standard Drizzle path:\n+\n+| Column | Type | Notes |\n+| -------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n+| `id` | text, pk | The `messageId`. Server-minted uuid. |\n+| `session_id` | text, indexed | Canonical session id. Re-keyed alongside the projector when a session gains its canonical id (F3's rebind already moves `session_metadata`; this joins that move). |\n+| `position` | integer | Sparse ordering so a reorder is an update, not a rewrite. |\n+| `content` | text | The person's words, pristine. |\n+| `disposition` | text | `queue` / `steer` / `stage` as requested. |\n+| `client_id` | text | Who enqueued it. Drives \"queued by another window\". |\n+| `enqueued_at` | integer | Epoch ms. |\n+| `context_json` | text, nullable | The `ClientContext` captured at enqueue time. |\n+\n+**Why persist (D5).** ADR-0264 accepts losing an in-flight _turn_ on restart. Losing a message somebody typed and was told was accepted is a different and worse promise to break. DOR-480 already established that this class of loss is unacceptable: the client queue's `restore` handle exists precisely because a refused trigger once destroyed a person's typed words (`use-message-queue.ts:13-31`).\n+\n+Rows are deleted on dispatch, on explicit removal, and on session deletion. A row whose session no longer exists is swept by the same health check that evicts sessions.\n+\n+#### 3.2 Contract additions (ADR-0263)\n+\n+```ts\n+/** One message waiting to be dispatched to a session. */\n+export interface QueuedMessage {\n+ id: string;\n+ content: string;\n+ disposition: MessageDisposition;\n+ enqueuedAt: number;\n+ /** The client that enqueued it, so a window can tell its own from another's. */\n+ enqueuedBy: string;\n+}\n+```\n+\n+- `SessionSnapshot` gains `queuedMessages: QueuedMessage[]`. This closes DOR-82's §7 Q8, which flagged that the snapshot has no queue field at all.\n+- A new `SessionEvent` member:\n+\n+ ```ts\n+ | {\n+ type: 'queue_update';\n+ seq: number;\n+ /** The WHOLE queue, always. */\n+ queue: QueuedMessage[];\n+ /** Present when this update was caused by an accepted message. */\n+ outcome?: MessageDeliveryOutcome;\n+ }\n+ ```\n+\n+ Full replacement rather than an incremental diff: the queue is small and bounded, and a full replacement makes every ordering and dedup bug unrepresentable.\n+\n+ > **Do not miss this:** a new `SessionEvent` member must be added to the client's event allowlist or it is dropped silently. This has bitten before.\n+\n+#### 3.3 Routes\n+\n+| Route | Behavior |\n+| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n+| `POST /api/sessions/:id/messages` | Accepts `disposition` in the body. Returns **202 immediately** with `{ sessionId, messageId, outcome, queuePosition }`. No longer returns 409 for a busy session; no longer holds the socket for a queued turn (the DOR-1088 interim behavior). |\n+| `GET /api/sessions/:id/queue` | The queue. Redundant with the snapshot, and worth having for integrations and debugging. |\n+| `PATCH /api/sessions/:id/queue/:messageId` | Edit content or move position. |\n+| `DELETE /api/sessions/:id/queue/:messageId` | Remove. |\n+| `POST /api/sessions/:id/interrupt` | Unchanged shape until `runtime-interrupt-receipts` lands. Gains `cancel_queued` semantics per D4; see §3.5. |\n+\n+**409 `SESSION_LOCKED` is retired from the message POST.** The lock survives, retargeted: it stops being \"who may POST\" and becomes the internal dispatch mutex held for one turn window. Its liveness machinery (`LockActivity`, `session-lock.ts:22-30`, DOR-782) is unchanged and is still what reclaims a dark turn. `sessions-cross-client.test.ts` clause 3 is rewritten in P2 to assert accept-and-queue, which is what its own header (`:26-27`) said was coming.\n+\n+#### 3.4 Dispatch rules\n+\n+The dispatcher is the single ingress for every caller listed in §7 of the ideation (`routes/sessions.ts:695`, `session-ui-action-handler.ts:100`, `session-command-intent-handler.ts:149`, `room-turn-runner.ts:277`, `embedded-turn-trigger.ts:80` and `:148`, `tasks/run-stream.ts`, `mesh/mcp-signin-resume.ts:196`). `executeCommandIntent` for claude-code is literally `sendMessage('/compact')` (`claude-code-runtime.ts:422-430`) and contends identically, so it goes through the dispatcher too. **A caller that bypasses the dispatcher keeps the old race**; the P2 acceptance criteria include an audit that none does.\n+\n+1. Dequeue on `turn_end`, never on `result` alone (FM6).\n+2. Never dispatch while `projector.hasPendingInteractions()` is true (FM4). That probe already exists and is already shared by the lock and the stall watchdog (`trigger-turn.ts:291`). Reuse it; do not invent a third liveness notion.\n+3. Dispatch is ordered by `position`, FIFO within a position.\n+4. Dispatch and reap share the dispatch mutex, so a reap that races a dispatch simply does not happen (FM8).\n+\n+#### 3.5 Interrupt semantics (D4)\n+\n+**Stop means stop everything queued.** The SDK's own documentation names this case: \"A Stop-means-stop-everything client (a remote UI's Stop button) sets this true\" (`sdk.d.ts:3620`, describing `cancel_queued`). A person who presses Stop with three messages queued and then watches the next one fire has been lied to.\n+\n+- The server clears the DorkOS queue for the session and passes `cancel_queued: true` to the runtime where the capability is advertised (`interrupt_cancel_queued_v1` on `system/init`, `sdk.d.ts:4613`).\n+- Cleared messages are **returned to the client, not destroyed**: they land back in the composer's draft area, the same promise `restore` makes today.\n+- The confirmation names the cost: \"Stop, and put 3 queued messages back?\"\n+- Honest reporting of what was actually cancelled depends on the interrupt receipt and therefore on `runtime-interrupt-receipts` (D7). Until then the client says \"stop requested\".\n+\n+### 4. The persistent pump\n+\n+#### 4.1 Structure\n+\n+New module `apps/server/src/services/runtimes/claude-code/sessions/session-pump.ts`, owned by the claude-code adapter. The SDK stays confined to that directory (Hard Rule 2).\n+\n+```ts\n+/** Process warmth for a runtime that keeps sessions warm. */\n+export type SessionWarmth = 'cold' | 'warming' | 'warm' | 'running' | 'crashed';\n+```\n+\n+The pump owns: the long-lived `query()`, its held input stream, the demux of its output into turn windows, the idle timer, and the crash detector. `executeSdkQuery` stops being \"the turn\" and becomes the pump's launcher. A **turn window** is a slice of the pump's output opened by a dispatch and closed by the correlated `result`.\n+\n+`sdk-utils.ts`'s `createHeldPrompt` (`:73-98`) is the seam this grows out of. The DOR-1087 branch has already converted it to a queue-driven generator with `push()`. **Adopt that conversion rather than writing a second one**; coordinate so the two do not diverge.\n+\n+#### 4.2 State machine\n+\n+| From | To | Trigger | Guard | Side effects |\n+| ------------------- | -------- | ---------------------------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------- |\n+| COLD | WARMING | first dispatch, or explicit warm | under the warm ceiling (else LRU-reap first) | `query()` called with `resume` when `hasStarted`, else fresh |\n+| WARMING | WARM | `system/init` received | — | capabilities feature-detected and cached; control methods become usable |\n+| WARMING | CRASHED | process exit or throw before init | — | dispatch fails over to RESUMING once |\n+| WARM | RUNNING | dispatch | dispatch mutex held; no pending interaction | `turn_start` ingested; stall watchdog **armed** |\n+| RUNNING | WARM | correlated `result` | — | one `turn_end` ingested; stall watchdog **disarmed**; idle timer **armed**; queue head dequeued |\n+| RUNNING | CRASHED | process exit or generator throw mid-turn | — | open window closed with `turn_end{terminalReason:'error'}`; **queue preserved** |\n+| WARM | REAPED | idle timer fires, or LRU eviction | no open turn AND no pending interaction | `close()` on the held stream; process drains and exits |\n+| WARM/RUNNING/REAPED | COLD | session eviction (`checkSessionHealth`) | — | reap first, then drop the session record |\n+| CRASHED | RESUMING | next dispatch | — | fresh `query()` with `resume` set: exactly today's path, F1 and F2 included |\n+| RESUMING | WARMING | `query()` returns | — | — |\n+\n+**WARM is the new state, and it is the whole point.** Today no such state exists: the subprocess lives only inside a turn's `try/finally` and is closed at `message-sender.ts:1017-1020`. Making it real is what buys warm cache, steering, and staging. It is also what creates every new failure mode in §5.\n+\n+**A warm session reports `idle`, not `streaming`.** The presence contract (`contributing/adding-a-runtime.md`) already forbids `streaming` with an empty `inProgressTurn`; WARM is a new way to get that wrong, and conformance case 4 (§6) pins it.\n+\n+#### 4.3 Timers, and who owns each\n+\n+| Timer | Constant | Default | Owner | Armed on | Disarmed on |\n+| ---------------------- | ---------------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------------------------------- |\n+| **Process idle** (new) | `SESSIONS.WARM_IDLE_MS` | 5 min | `SessionPump` (adapter) | turn window closes | next dispatch |\n+| **Warm ceiling** (new) | `SESSIONS.MAX_WARM_SESSIONS` | 12 | pump registry (adapter) | continuous LRU | — |\n+| Session eviction | `SESSIONS.TIMEOUT_MS` (`constants.ts:113`) | 30 min | `SessionStore.checkSessionHealth` (`session-store.ts:540-560`), swept every `INTERVALS.HEALTH_CHECK_MS` (`constants.ts:5`, 5 min) | last activity | activity |\n+| Turn stall | `SESSIONS.TURN_STALL_TIMEOUT_MS` (`constants.ts:128`) | 10 min | `withStallGuard` (`trigger-turn.ts:378-384`) | **turn window opens (changed)** | **turn window closes (changed)** |\n+| Stall interrupt bound | `SESSIONS.STALL_INTERRUPT_TIMEOUT_MS` (`constants.ts:137`) | 30 s | `stall-guard.ts` | interrupt issued | interrupt settles |\n+| Lock TTL (inactivity) | `SESSIONS.LOCK_TTL_MS` (`constants.ts:115`) | 5 min | `SessionLockManager` | acquisition | release |\n+| Interaction timeout | `SESSIONS.INTERACTION_TIMEOUT_MS` (`constants.ts:117`) | 10 min | `interactive-handlers.ts` | interaction opens | answer or timeout |\n+\n+Two changes hide in that table and both are load-bearing:\n+\n+- **The stall watchdog must arm and disarm per turn window.** Today it spans the whole `sendMessage` generator, which today equals one turn. On a pump it would span the process, and a WARM session sitting legitimately silent for 10 minutes would be interrupted for no reason.\n+- **Process idle and session eviction are different timers and must not be conflated.** Eviction implies reap; reap never implies eviction. Reaping is invisible (the next message resumes), which is exactly what makes 5 minutes safe to set.\n+\n+#### 4.4 Resource ceiling (D6)\n+\n+`SESSIONS.MAX_SESSIONS = 50` (`constants.ts:119`, enforced at `session-store.ts:211-216`) counts session **records**. A separate, lower `MAX_WARM_SESSIONS` (default 12) counts **processes**, LRU-reaped down to the ceiling regardless of the idle timer. Fifty concurrent CLI subprocesses plus their MCP children on a laptop is not a shape to ship untested, and warmth is a cache, so LRU is exactly right for it. Records stay at 50, so `ensureSession`'s existing throw stays the genuinely exceptional path it is today.\n+\n+#### 4.5 The relaunch pin list (FM9)\n+\n+A warm process pins whatever it was launched with. Any change to a pinned value must **force a reap and relaunch**, or the next turn runs under stale settings. Getting this wrong bills a paying client's conversation to the wrong account, so the list is exhaustive and each entry names its source:\n+\n+| Pinned | Source today | Change forces relaunch |\n+| ----------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |\n+| `cwd` | `message-sender.ts:349` | yes |\n+| Claude account root (`CLAUDE_CONFIG_DIR`) | `message-sender.ts:450`, spec `claude-code-accounts` D3 | **yes, unconditionally** |\n+| Resolved credential env | `message-sender.ts:429` (ADR-0315) | yes |\n+| Agent identity token | `message-sender.ts:437` | yes |\n+| `mcpServers` | `message-sender.ts:604-608` | no: use `setMcpServers` on the live query |\n+| `plugins` | `message-sender.ts:680-686` | no: use `reload_plugins`, already wired (`claude-code-runtime.ts:439-448`) |\n+| `permissionMode` | `message-sender.ts:554-567` | no: `setPermissionMode` on the live query |\n+| `model` / `effort` / `fastMode` | `message-sender.ts:577-602` | `setModel` where the SDK allows it; relaunch otherwise. **Verify per field during P3**; do not assume. |\n+| `systemPrompt` append | `message-sender.ts:401-405` | yes |\n+| `settingSources`, `env` | `message-sender.ts:461`, `:474-495` | yes |\n+\n+### 5. Turn boundaries on a long-lived query\n+\n+Today the units coincide: one `sendMessage` = one `query()` = one `result` = one `done` = one `turn_end` (`sdk-event-mapper.ts:43-46` → `result-event-mapper.ts:223-229` → `session-event-normalizer.ts:632-647`). With a pump they come apart, and the CLI can start continuations DorkOS never asked for (auto-resume continuations are named in `sdk.d.ts:3628`).\n+\n+**The rule: a DorkOS turn opens on dispatch and closes on the `result` that answers it.**\n+\n+1. **`closeTurn()` becomes idempotent.** Guard on `ended` in `feedProjector` (`session-event-normalizer.ts:623-647`). This alone closes F5 and ships first, as P0, because it is a latent bug regardless of anything else here.\n+2. **Correlation is by `messageId`, never positional.** Reasoning stated in the TSDoc in §2.2.\n+3. **A steer does not open a turn.** It joins the open window and rides a new `SessionEvent`:\n+\n+ ```ts\n+ | { type: 'turn_input'; seq: number; content: string; disposition: 'steer'; messageId: string }\n+ ```\n+\n+ The cockpit renders it inline as a user message inside the running turn, because that is what the person did. (Allowlist reminder applies.)\n+\n+4. **A stage message opens no turn at all.** It emits `context_staged` so the transcript stays honest, and merges into the next dispatch per `shouldQuery: false` (`sdk.d.ts:4764`).\n+5. **A `result` with no correlated `messageId` opens a synthetic turn tagged `origin: 'runtime'`.** Not dropped, not disguised as a person's turn. The durable stream stays a complete account of the session, which is the same honesty rule the presence contract already enforces.\n+\n+Unchanged: the ADR-0264 pipeline end to end, and `guardTurnErrors`' error-terminal translation (`trigger-turn.ts:492-530`), which must still close the open window with `status_change(error)`, a typed `error`, and exactly one `turn_end(error)`.\n+\n+---\n+\n+## User Experience\n+\n+**Typing while the agent works.** The composer stays enabled. The message is accepted (202) and appears as a queue chip, now sourced from the server, so it survives refresh, appears in every window, and can be edited, reordered, or removed from any of them. The primary action offers **Queue** (default) with **Steer** and **Add context** beside it, and Steer and Add context are hidden, not disabled, when the runtime does not declare them. A hidden affordance is honest; a dead one is not.\n+\n+**Steering.** \"Also check the tests\" reaches the running agent and renders inline inside the live turn. If the runtime cannot steer, the message is queued and the chip says so once: \"Queued. Codex can't take messages mid-turn.\"\n+\n+**Adding context.** Attaches for the agent to use, provokes nothing, renders as a quiet transcript entry.\n+\n+**Stopping.** With a queue, the confirmation names the cost: \"Stop, and put 3 queued messages back?\" The messages return to the composer. Nothing a person typed is destroyed by a stop.\n+\n+**A second window mid-turn.** Sees the same queue, can add to it, can remove from it. No 409, ever, on the message path.\n+\n+**Nothing at all for warmth.** Warm sessions are invisible. Reap and resume are invisible. The only observable difference is that the second turn in a conversation starts faster than the first.\n+\n+---\n+\n+## Testing Strategy\n+\n+### Conformance additions (`packages/test-utils/src/runtime-conformance.ts`)\n+\n+A capability that is not conformance-tested is a capability a runtime can lie about. The suite already proves the discipline works: `validatePresenceReport` exists precisely so a runtime cannot fabricate presence.\n+\n+New `RuntimeConformanceOpts`:\n+\n+```ts\n+ /**\n+ * Drives ONE turn to the point where it is OPEN, calls `midTurn`, then lets it\n+ * close. Required for the disposition cases; without it they SKIP by name\n+ * rather than passing on a manufactured absence — the same stance\n+ * `presenceTurn` takes and for the same reason.\n+ */\n+ dispositionTurn?: (\n+ runtime: AgentRuntime,\n+ sessionId: string,\n+ content: string,\n+ probes: { midTurn: () => Promise }\n+ ) => Promise;\n+\n+ /**\n+ * Drives a session to WARM (a completed turn, process still held) and hands\n+ * control back. Provided only by runtimes declaring `supportsPersistentSession`.\n+ */\n+ warmSession?: (runtime: AgentRuntime, sessionId: string) => Promise;\n+```\n+\n+New cases:\n+\n+| # | Case | Applies to |\n+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |\n+| C1 | **Disposition honesty.** For each of `steer` / `stage`: capability declared → the message reaches the model with no new `turn_start`; not declared → `deliverIntoTurn` is absent or returns `{ delivered: false, reason: 'unsupported' }`. Neither throws. | all |\n+| C2 | **Terminal exactly once.** A turn window emits exactly one `turn_end`, however many native `result`s the backend produced. | all |\n+| C3 | **Queue durability.** A message queued behind a turn that then FAILS still runs; a message never runs while a pending interaction is open. | all |\n+| C4 | **Warmth honesty.** A runtime declaring `supportsPersistentSession` reports `idle` with `inProgressTurn: null` while WARM. | persistent runtimes |\n+| C5 | **Reap transparency.** WARM, reap, send again produces a well-formed turn. The person cannot tell. | persistent runtimes |\n+| C6 | **Capability completeness.** All three new flags present and boolean. Compile-time forced, asserted anyway so a cast cannot dodge it. | all |\n+\n+C2 must be proved by **seeding the defect**: remove the idempotence guard, watch it go red. Prove the check can fail before trusting it.\n+\n+### Per phase\n+\n+| Phase | Unit | Integration | E2E / manual |\n+| ------ | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |\n+| **P0** | `session-event-normalizer` idempotent `closeTurn`, defect-seeded | a scripted double-`done` stream yields one `turn_end` on the durable stream | none |\n+| **P1** | (owned by DOR-1088) | (owned by DOR-1088) | (owned by DOR-1088) |\n+| **P2** | queue store CRUD, ordering, dispatch gating on pending interactions, ladder resolution table | full route pass over the real projector: enqueue → snapshot carries it → `queue_update` on the stream → dispatch on `turn_end` → row gone. Restart mid-queue: rows survive, dispatch resumes. `sessions-cross-client.test.ts` clause 3 rewritten to accept-and-queue | Playwright: two windows, one queue; refresh mid-queue; queue survives |\n+| **P3** | pump state machine transition-by-transition; idle timer; LRU ceiling; pin-list relaunch triggers; crash → resume | one pump, many turns: warm across turns, correlation by `messageId`, stall watchdog arms and disarms per window, reap-then-send is transparent. Live smoke behind `DORKOS_CLAUDE_LIVE=1` in the same file, per the mocking stance in `contributing/adding-a-runtime.md` | manual: 10 consecutive turns, watch process count and cache-read ratio |\n+| **P4** | `deliverIntoTurn` for both modes; degradation ladder per runtime; `turn_input` and `context_staged` normalization | conformance C1–C6 green on all four runtimes; a steer mid-turn reaches the model with no second `turn_start` | Playwright: steer mid-turn; steer on Codex shows the downgrade notice |\n+| **P5** | DOR-1087 tripwire fires on a synthetic phantom | phantom rate measured over a multi-subagent session | measurement pass (§Performance) |\n+\n+**Mocking stance is non-negotiable and unchanged:** CI never requires a backend binary. Mock the SDK with recorded fixtures, mock the dependency probe, gate live smokes behind an env flag in the same file.\n+\n+**One trap worth naming:** run every test that renders or mounts a changed component, not just the component's own suite. A component suite green with a wizard test red in CI has happened here before.\n+\n+---\n+\n+## Performance Considerations\n+\n+The performance claim is the **justification** for this work, so it must be measured rather than asserted. The ideation deliberately marked its cost estimates unverified, and this spec does not upgrade them.\n+\n+**The measurement that decides P5**, taken on the same workload with the flag off and on:\n+\n+| Metric | Source | Expectation |\n+| ---------------------------- | ------------------------------------------------------------------- | --------------------------------------------- |\n+| Time to first token, turn 2+ | span `SESSION_TURN`, already instrumented (`trigger-turn.ts:333`) | materially lower (no spawn, no MCP reconnect) |\n+| Cache-read token ratio | `session_status.cacheReadTokens` (`result-event-mapper.ts:166-181`) | materially higher |\n+| Resident subprocess count | process sampling | bounded by `MAX_WARM_SESSIONS` |\n+| Phantom-cancellation rate | DOR-1087 tripwire | zero |\n+\n+**Risks.** A warm process holds memory for its whole idle window; the ceiling bounds this. LRU thrash is possible on a host with many active sessions; the metric to watch is reap-then-immediately-rewarm frequency, and the remedy is raising the ceiling, not lengthening the idle timer.\n+\n+---\n+\n+## Security Considerations\n+\n+- **Account and credential pinning is the highest-severity item in this spec.** A warm process pins `CLAUDE_CONFIG_DIR` at launch (`message-sender.ts:450`). A session that changes account without a relaunch would run and **bill** on the wrong account. The pin list (§4.5) is a security control, not an optimization detail, and its account row is unconditional.\n+- **Credential rotation** must invalidate warm processes. A revoked credential resolved at `message-sender.ts:429` must not keep working because a process launched before the revocation is still alive.\n+- **Boundary validation** (`validateBoundaryOrDorkHome`, `message-sender.ts:351`) happens per turn today. On a pump it must happen per **dispatch**, not per launch, or a cwd change would slip past the boundary check.\n+- **Queue content is user text and is now persisted.** It lives in the same SQLite store as the rest of session metadata, under the same `~/.dork/` ownership, and never leaves the host.\n+- **A steer is a write.** `deliverIntoTurn` must be subject to the same authorization as `sendMessage`; there is no path where a caller that may not send may steer.\n+\n+---\n+\n+## Documentation\n+\n+| Doc | Change |\n+| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n+| `contributing/adding-a-runtime.md` | The three new capability flags, the ladder, `deliverIntoTurn`, and the new conformance cases with their drivers. This is the guide a runtime author reads; the flags are worthless if it does not explain how to declare them honestly. |\n+| `contributing/architecture.md` | The pump and the server queue in the hexagonal picture. |\n+| `docs/integrations/sse-protocol.mdx` | `queue_update`, `turn_input`, `context_staged`; the retirement of 409 from the message POST. This is the public integration contract. |\n+| `docs/` (user-facing) | Queue, steer, add-context, and what Stop does to queued messages. Per `writing-for-humans`. |\n+| `changelog/unreleased/` | One fragment per phase. |\n+| `decisions/` | Three ADRs (§Related ADRs). |\n+\n+---\n+\n+## Implementation Phases\n+\n+Each phase is independently shippable and independently revertable. Rollout is **per-session opt-in via config**, defaulting off, promoted later: a config field under `runtimes.claudeCode` in `packages/shared/src/config-schema.ts` plus the semver-keyed migration the `adding-config-fields` skill requires. Not a global flag and not a hard cutover, because the two paths must run side by side on one host to be comparable, and the fallback path is not going away.\n+\n+### P0 — Idempotent `closeTurn` (F5)\n+\n+**Scope.** Guard `feedProjector`'s `closeTurn()` on `ended` (`session-event-normalizer.ts:623-647`). No flag.\n+\n+**Acceptance.**\n+\n+- A stream carrying two `done` events produces exactly one `turn_end`.\n+- The defect-seeded test goes red with the guard removed.\n+- No behavior change on any single-`result` turn: the existing suite is green untouched.\n+\n+**Reverts by:** `git revert`.\n+\n+### P1 — DOR-1088 serialization\n+\n+**Scope.** Owned by `worktree-dor-1088-stream-serialize`, not by this spec. Listed so the dependency is explicit.\n+\n+**Acceptance (this spec's requirement of it).**\n+\n+- Two same-client triggers on one session run strictly in sequence; the second's turn starts only after the first's lock is released.\n+- A second **client** still meets the lock's unchanged 409-then-takeover answer.\n+- `session.activeQuery` is cleared only by the frame that owns it.\n+- A throw before the turn launches releases both the lock and the queue slot.\n+\n+**Reverts by:** flag off, back to 409.\n+\n+### P2 — Server-owned queue\n+\n+**Scope.** Queue table and migration; `QueuedMessage`, `queue_update`, snapshot field, client allowlist; queue routes; dispatcher as the single ingress with the audit of all callers in §3.4; disposition envelope accepted at ingress with all dispositions resolving to `queue`; all three capability flags declared `false` on every runtime; client cutover from the ADR-0104 queue to the server queue, preserving every existing affordance including `restore`; `sessions-cross-client.test.ts` clause 3 rewritten; ADR-0104 superseded.\n+\n+**Acceptance.**\n+\n+- A message POSTed to a busy session returns 202 with a `messageId` and a queue position. **No 409 on the message path, ever.**\n+- The queue appears in `SessionSnapshot` and updates on `queue_update` in every connected window.\n+- A queued message survives a client refresh, a second window, a **failed** turn, and a **server restart**.\n+- A queued message never dispatches while a pending interaction is open.\n+- Every trigger caller in §3.4 routes through the dispatcher; the audit is a test, not a claim.\n+- Queue mutation from window B is visible in window A.\n+\n+**Reverts by:** flag off, client falls back to its local queue.\n+\n+### P3 — Persistent pump, opt-in\n+\n+**Scope.** `session-pump.ts`; state machine; turn windowing with `messageId` correlation; idle timer and `MAX_WARM_SESSIONS` LRU; the pin list and its forced relaunches; crash detection to `CRASHED` to `RESUMING`; stall-watchdog arm/disarm per window; `getSessionWarmth` / `reapSession`; config field and migration; `supportsPersistentSession: true` for claude-code.\n+\n+**Acceptance.**\n+\n+- Ten consecutive turns in one session run on **one** subprocess; the process count does not grow.\n+- A warm session reports `idle` with `inProgressTurn: null` (conformance C4).\n+- Reap after the idle window, then send: the turn is well formed and the person cannot tell (C5).\n+- Reap never happens while a pending interaction is open.\n+- Killing the subprocess mid-turn closes that turn with `turn_end{terminalReason:'error'}`, **preserves the queue**, and the next dispatch resumes.\n+- Every pinned value in §4.5 forces a relaunch when changed; the account row is proved by a test that would otherwise bill the wrong account.\n+- The stall watchdog does not fire on a WARM session silent past `TURN_STALL_TIMEOUT_MS`.\n+- Flag off: byte-for-byte today's resume-per-message behavior.\n+\n+**Reverts by:** flag off.\n+\n+### P4 — Dispositions native, capabilities, conformance\n+\n+**Scope.** `deliverIntoTurn` for claude-code (`streamInput` for steer, `shouldQuery: false` for stage); `turn_input` and `context_staged` events plus allowlist; the degradation ladder and its downgrade notice; honest flags on all four runtimes; conformance C1–C6 with their drivers; composer affordances; interrupt-receipt integration where `runtime-interrupt-receipts` has landed.\n+\n+**Acceptance.**\n+\n+- A steer reaches the running agent with **no second `turn_start`**, and renders inline inside the live turn.\n+- A stage message provokes **no turn** and merges into the next dispatch.\n+- A steer requested against Codex or OpenCode is queued, and the outcome carries `requested: 'steer', applied: 'queue', degradedBecause: 'unsupported'`; the UI says so once.\n+- A steer requested against an idle session runs immediately and the UI stays quiet about it.\n+- Conformance C1–C6 green on claude-code, codex, opencode, test-mode.\n+- Stop clears the queue, returns the messages to the composer, and the confirmation names the count.\n+\n+**Reverts by:** capability flags to `false`; the ladder degrades everything to `queue`.\n+\n+### P5 — Default on, measure, clean up\n+\n+**Scope.** The measurement pass in §Performance; flip the config default; watch the DOR-1087 tripwire; remove the phantom detector after a quiet period.\n+\n+**Acceptance.**\n+\n+- Turn-2 time-to-first-token and cache-read ratio both improved on the same workload, with numbers recorded on the work item.\n+- Resident subprocess count bounded by `MAX_WARM_SESSIONS` under a 20-session soak.\n+- The DOR-1087 tripwire records **zero** phantoms over the quiet period. If it fires even once, P5 does not complete and the design is re-opened.\n+- The phantom detector is removed as a **scheduled task**, never as an assumption.\n+\n+**Reverts by:** flag off.\n+\n+---\n+\n+## Open Questions\n+\n+All ideation decisions D1 through D10 were approved by the coordinator and are frozen as specified: D1 envelope plus interrupt verb (§2.1), D2 queue default (§2.2), D3 no `priority` reliance (§Non-Goals N3), D4 stop cancels queued (§3.5), D5 persist the queue (§3.1), D6 separate warm ceiling (§4.4), D7 depend do not absorb (§Technical Dependencies), D8 replace ADR-0104 preserving UX (§P2), D9 stage ships last (§P4), D10 DOR-1087 tripwire through P5 (§P5).\n+\n+Three questions the drafting itself surfaced, all resolved:\n+\n+**~~Q1: can `steer` ride `sendMessage`'s return type?~~ (RESOLVED)**\n+**Answer:** No. `sendMessage` returns `AsyncGenerator` and `feedProjector` consumes one such generator as exactly one turn. A steer's events belong to a turn whose generator is already being consumed elsewhere, so a steer cannot return a turn-shaped generator without two `feedProjector` calls fighting over one turn.\n+**Rationale:** D1's intent was \"one envelope at the ingress, not three new required runtime verbs\", and that is preserved exactly: `disposition` is a single ingress field, and the runtime interface grows **one optional** method rather than three required ones. `deliverIntoTurn` returns a receipt because the events surface on the already-open turn's stream, which is the honest shape.\n+\n+**~~Q2: does DOR-1088's `SessionTurnQueue` become the server queue?~~ (RESOLVED)**\n+**Answer:** No. It stays as the internal ordering primitive; P2 builds the durable queue above it and stops holding the HTTP socket.\n+**Rationale:** DOR-1088's chain is in-memory, per-client, invisible to other windows, lost on restart, and holds a socket per waiting message. Those are correct choices for a correctness fix shipping now and wrong ones for the product feature. Keeping both, with the durable queue owning the person-facing promise and the chain owning intra-process ordering, means P2 changes behavior without rewriting a primitive that will already be proven in production.\n+\n+**~~Q3: should the stall watchdog also cover the WARM state?~~ (RESOLVED)**\n+**Answer:** No. It arms on turn-window open and disarms on close. WARM silence is bounded by the idle timer instead.\n+**Rationale:** The watchdog exists to end a turn that has gone dark (`constants.ts:120-129`). A WARM session is not a turn and has nothing to end; interrupting one would kill a healthy process for the crime of waiting. The idle timer is the right bound for silence with no turn open, and it is shorter (5 min) than the watchdog (10 min) anyway.\n+\n+---\n+\n+## Related ADRs\n+\n+### Existing, constraining\n+\n+| ADR | Relationship |\n+| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |\n+| **0264** server-owned durable resumable session stream | The seam. Trigger-only POST is where the queue belongs; its restart loss boundary is inherited (N1) |\n+| **0263** runtime-neutral snapshot + event contract | Extended by `queue_update`, `turn_input`, `context_staged`, and `queuedMessages` |\n+| **0104** client-side message queue with auto-flush | **Superseded** by ADR-c below |\n+| **0075** per-agentId promise chain for CCA concurrency | Same shape as DOR-1088's `SessionTurnQueue`, at the relay layer; the dispatcher subsumes its role for cockpit traffic |\n+| **0310** runtime-owned storage, aggregated listing | The per-runtime degradation stance the ladder follows |\n+| **0256** `features` as a typed extension point | Why the three new flags are first-class fields, not bag entries |\n+| **0273** neutral additional-context bag | How `stage` fallback content reaches a turn without mutating `content` |\n+| **0315** credential reference resolution | The credential pin (§4.5, §Security) |\n+\n+### Draft ADR candidates to seed at DECOMPOSE\n+\n+Listed here per the coordinator's instruction; **no ADR files created by this spec.**\n+\n+| Candidate | Title | Status it would carry | Notes |\n+| --------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n+| **ADR-a** | Three message dispositions at the `AgentRuntime` boundary | `draft`, `extractedFrom: persistent-session-runtime` | The envelope-plus-`deliverIntoTurn` split (§2), the three capability flags, and the degradation ladder. Records the rejected alternative (three required runtime verbs) and why Q1 forced the split. |\n+| **ADR-b** | Persistent streaming-input sessions for claude-code, with resume as the recovery path | `draft`, `extractedFrom: persistent-session-runtime` | The WARM state, the two-timer model and their owners, the warm ceiling, and the pin list. Records the rejected alternative (keep resume-per-message and queue only at our layer) and the deliberate non-goal of surviving a restart. |\n+| **ADR-c** | Server-owned durable message queue | `draft`, `extractedFrom: persistent-session-runtime` | **Supersedes ADR-0104.** Amends ADR-0264 by naming the queue as the thing behind the trigger-only POST, which ADR-0264's own context anticipated. Records the persistence decision (D5) and the retirement of 409 from the message path. |\n+\n+Whether the `priority`-field question (D3) earns its own ADR is a DECOMPOSE call. The recommendation is no: \"we measured nothing and therefore relied on nothing\" is a note in ADR-b, not a decision record of its own.\n+\n+---\n+\n+## References\n+\n+- `research/20260610_message_queuing_agent_runtimes.md` (DOR-82): the four-pattern taxonomy, the cross-runtime matrix, and the recommendation this spec executes. Its §7 questions Q1, Q2, Q4, Q5, Q8 are answered here.\n+- [`01-ideation.md`](01-ideation.md): the full evidence trace with verified `file:line` pointers at `e4b9e1a9b`.\n+- `specs/runtime-interrupt-receipts/01-ideation.md` (`260807-231651`), `specs/runtime-prompt-redelivery/01-ideation.md` (`260807-231653`): adjacent specs; boundaries in D7.\n+- `contributing/adding-a-runtime.md`: the runtime author contract, the presence-truthfulness stance, and the mocking stance.\n+- `packages/test-utils/src/runtime-conformance.ts`: the suite to extend; `RuntimeConformanceOpts` at `:44-131`, driver pattern at `presenceTurn` / `durableHistory`.\n+- `@anthropic-ai/claude-agent-sdk@0.3.224` `sdk.d.ts`: `streamInput` `:2610`, `interrupt` `:2346`, `reinitialize` `:2452`, `priority` `:4757` (still undocumented), `shouldQuery` `:4764`, `cancel_queued` `:3620`, capability feature-detection `:4613`.\n+- `worktree-dor-1088-stream-serialize`: the serialization prerequisite, read at time of writing.\n+- `worktree-dor-1087-phantom-stop`: the phantom-cancellation characterization and the `push()`-capable held prompt this spec adopts.", "status": "added"}, {"additions": 462, "deletions": 0, "filename": "specs/persistent-session-runtime/03-tasks.json", "patch": "@@ -0,0 +1,462 @@\n+{\n+ \"spec\": \"specs/persistent-session-runtime/02-specification.md\",\n+ \"slug\": \"persistent-session-runtime\",\n+ \"generatedAt\": \"2026-08-10T00:45:00Z\",\n+ \"mode\": \"full\",\n+ \"lastDecomposeDate\": null,\n+ \"notes\": {\n+ \"sizeToPoints\": \"small=2-3, medium=5, large=8, xl=13. No task is xl, so the default subIssueThreshold ('xl') fires for none of them: every task stays a checklist line rather than its own tracker sub-issue.\",\n+ \"trackerMirror\": \"Not performed by this decomposition. Every `issue` field is deliberately null; tracker projection happens outside this scope.\",\n+ \"phaseOwnership\": \"Phase 1 is owned by the in-flight DOR-1088 branch (worktree-dor-1088-stream-serialize). Task 1.1 tracks that dependency and creates no new work.\"\n+ },\n+ \"tasks\": [\n+ {\n+ \"id\": \"0.1\",\n+ \"phase\": 0,\n+ \"phaseName\": \"P0 — Idempotent closeTurn\",\n+ \"subject\": \"[persistent-session-runtime] [P0] Make feedProjector's closeTurn idempotent so a multi-result turn emits one turn_end\",\n+ \"description\": \"`feedProjector` in `apps/server/src/services/session/session-event-normalizer.ts` calls `closeTurn()` on EVERY `done` event it sees (the `if (event.type === 'done') { closeTurn(); ended = true; continue; }` branch around line 636), and its `finally` calls it again when the stream ended without one. There is no guard against `closeTurn()` running twice, so a stream carrying two `done` events ingests two `turn_end` events into the projector for one logical turn.\\n\\nThis never fires today because the claude-code runtime maps exactly one SDK `result` per turn: `sdk-event-mapper.ts` routes `result` to `mapResultEvent`, and `event-mappers/result-event-mapper.ts` unconditionally yields `{ type: 'done' }` at the end of that branch (around line 227). One query, one result, one done. It fires immediately once a query stays open across turns, which is what the persistent pump does, so it is a latent blocker for every later phase as well as a bug on its own merits.\\n\\nWhat to build: introduce a guard so `closeTurn()` ingests at most one `turn_end` per `feedProjector` call. The existing `ended` flag is close but is set only in the `done` branch and consulted only in the `finally`; make `closeTurn` itself the thing that checks and sets, so both call sites are covered by one rule. Keep the existing `terminalReason` resolution intact: an explicit reason from `session_status`/`done` still wins, and the `sawError` latch still fills an undefined reason with 'error'. The FIRST close is the one that counts; a second `done` must be a no-op, not an overwrite, because the second one carries no reason that belongs to this turn.\\n\\nAcceptance criteria:\\n1. A scripted StreamEvent sequence containing two `done` events produces exactly ONE `turn_end` on the projector.\\n2. A stream that ends without any `done` still produces exactly one `turn_end` from the `finally` (unchanged behavior).\\n3. A stream with one `done` followed by nothing produces exactly one `turn_end` and the `finally` does not add a second (unchanged behavior).\\n4. terminalReason resolution is unchanged: explicit reason wins; typed `error` with no explicit reason still closes as `terminalReason: 'error'`.\\n5. The test is proved able to fail: remove the guard, watch the double-`done` case go red, restore it. Record that in the PR description.\\n6. The existing server test suite is green with no other file touched.\\n\\nNo feature flag. This is a pure correctness fix and reverts by `git revert`.\",\n+ \"activeForm\": \"Making closeTurn idempotent\",\n+ \"size\": \"small\",\n+ \"points\": 2,\n+ \"priority\": \"high\",\n+ \"dependencies\": [],\n+ \"parallelWith\": [\"1.1\", \"3.1\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"1.1\",\n+ \"phase\": 1,\n+ \"phaseName\": \"P1 — DOR-1088 serialization (external dependency)\",\n+ \"subject\": \"[persistent-session-runtime] [P1] Track DOR-1088 turn serialization landing and verify its four guarantees\",\n+ \"description\": \"TRACKING TASK. No new implementation work. DOR-1088 is being implemented on `worktree-dor-1088-stream-serialize` and must land before phase 2 dispatch work begins. This task exists so the dependency is explicit and verifiable rather than assumed.\\n\\nWhat DOR-1088 lands (read from that branch): a new `apps/server/src/services/session/turn-queue.ts` exporting `SessionTurnQueue.reserve(sessionId, clientId) -> TurnSlot { ready, release }`, a per-(session, client) promise chain in the same shape as `RuntimeAdapter.enqueueForSession` (ADR-0075). `trigger-turn.ts` reserves the slot before anything else and awaits `slot.ready`, releasing it inside `releaseOnce` and on the launch-throw path. `session-lock.ts`'s `acquireLock` refuses ANY live lock including the same client's, which removes the same-client re-acquire that let one browser tab start a second turn beside its own. `message-sender.ts`'s `finally` clears `session.activeQuery` only when the frame still owns it.\\n\\nWhat this task does: when DOR-1088 merges, verify the four guarantees below hold on `main`, then unblock the dependent tasks. If any fails, raise it on the DOR-1088 work item rather than patching it here.\\n\\nAcceptance criteria:\\n1. Two triggers from the SAME client on one session run strictly in sequence: the second turn's `turn_start` is ingested only after the first turn's lock has been released.\\n2. A second, DIFFERENT client still gets the unchanged answer: 409 SESSION_LOCKED naming the holder while the turn is alive, and an accepted takeover once the holder's lock has expired past its inactivity TTL.\\n3. `session.activeQuery` is cleared only by the frame that installed it; a late-settling frame does not strand its successor with `activeQuery: undefined`.\\n4. A throw before the turn is launched (e.g. context assembly failing) releases BOTH the write lock and the queue slot, so the session is not wedged for that client.\\n\\nNote for phase 2: DOR-1088's chain is in-memory, per-client, invisible to other windows, lost on restart, and holds an HTTP socket open per waiting message. Task 2.3 keeps it as the intra-process ordering primitive and builds the durable queue above it; it is not replaced and it is not the server queue.\",\n+ \"activeForm\": \"Tracking the DOR-1088 serialization landing\",\n+ \"size\": \"small\",\n+ \"points\": 0,\n+ \"priority\": \"high\",\n+ \"dependencies\": [],\n+ \"parallelWith\": [\"0.1\", \"3.1\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"2.1\",\n+ \"phase\": 2,\n+ \"phaseName\": \"P2 — Server-owned queue\",\n+ \"subject\": \"[persistent-session-runtime] [P2] Add the disposition and queue types to shared, plus the three capability flags declared false everywhere\",\n+ \"description\": \"Land the whole type surface first, with no behavior change, so every later task compiles against a settled contract.\\n\\nIn `packages/shared/src/agent-runtime.ts` add:\\n- `export type MessageDisposition = 'queue' | 'steer' | 'stage'` with TSDoc stating that it is ignored when the session is idle (every disposition then means run it now) and that it defaults to 'queue' at every ingress.\\n- `export type DispositionDowngradeReason = 'unsupported' | 'session-idle' | 'no-open-turn' | 'pending-interaction'`.\\n- `export interface MessageDeliveryOutcome { messageId: string; requested: MessageDisposition; applied: MessageDisposition; degradedBecause?: DispositionDowngradeReason }`.\\n- `export interface QueuedMessage { id: string; content: string; disposition: MessageDisposition; enqueuedAt: number; enqueuedBy: string }`.\\n- Two optional fields on `MessageOpts`: `disposition?: MessageDisposition` and `messageId?: string`. The `messageId` TSDoc must state that correlation is by id and NEVER positional, because the SDK coalesces a dequeued batch into one turn and several dispatched ids can therefore share one `result`.\\n- Three REQUIRED booleans on `RuntimeCapabilities`: `supportsPersistentSession`, `supportsSteer`, `supportsContextStaging`. Required rather than optional, following the `commandIntents` and `settings` precedent (ADR-0256), so no adapter can silently omit one. There is deliberately no `supportsQueue`: the server always owns the queue, so every runtime supports queueing by construction.\\n\\nIn `packages/shared/src/session-stream.ts` add the `queue_update` member to the `SessionEvent` union: `{ type: 'queue_update'; seq: number; queue: QueuedMessage[]; outcome?: MessageDeliveryOutcome }`. The whole queue every time, never a diff: it is small and bounded, and full replacement makes ordering and dedup bugs unrepresentable. Add `queuedMessages: QueuedMessage[]` to `SessionSnapshot`.\\n\\nAdd Zod schemas for every new type alongside the existing ones in `packages/shared/src/schemas.ts` / `session-stream.ts`, matching how the neighbouring event members are validated.\\n\\nDeclare all three capability flags as `false` on all four runtimes: `claude-code/runtime-constants.ts`, `codex/runtime-constants.ts`, `opencode/runtime-constants.ts`, and the test-mode capabilities object. Also update `packages/test-utils/src/fake-agent-runtime.ts` if it carries a capabilities literal.\\n\\nAcceptance criteria:\\n1. `pnpm --filter @dorkos/shared typecheck` and the full server typecheck pass; the required flags force a compile error if any adapter omits one (verify by deleting one flag from one adapter and seeing it fail).\\n2. `queue_update` is added to the CLIENT event allowlist in the same PR. A new SessionEvent member that is not allowlisted is dropped silently, and that has bitten this repo before. Include a test asserting a `queue_update` survives the client's event handling path.\\n3. Existing conformance suites are green: the capability-shape assertions accept the three new booleans.\\n4. No behavior change: no route, dispatcher, or adapter logic is touched.\",\n+ \"activeForm\": \"Adding the disposition and queue types to shared\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"0.1\"],\n+ \"parallelWith\": [\"3.1\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"2.2\",\n+ \"phase\": 2,\n+ \"phaseName\": \"P2 — Server-owned queue\",\n+ \"subject\": \"[persistent-session-runtime] [P2] Build the durable queue store: Drizzle table, migration, and repository\",\n+ \"description\": \"Create the persisted queue that makes a typed message survive a refresh, a second window, a failed turn, and a server restart.\\n\\nAdd a table in `packages/db` beside `session_metadata`, with a Drizzle migration:\\n\\n| column | type | notes |\\n| --- | --- | --- |\\n| `id` | text, primary key | the `messageId`, a server-minted uuid |\\n| `session_id` | text, indexed | canonical session id |\\n| `position` | integer | SPARSE ordering (e.g. steps of 1000) so a reorder is an UPDATE of one row, not a rewrite of all of them |\\n| `content` | text | the person's words, pristine; context never mutates it |\\n| `disposition` | text | 'queue' / 'steer' / 'stage' as REQUESTED, not as applied |\\n| `client_id` | text | who enqueued it, so a window can tell its own from another's |\\n| `enqueued_at` | integer | epoch ms |\\n| `context_json` | text, nullable | the `ClientContext` captured at enqueue time |\\n\\nBuild a repository module (suggested `apps/server/src/services/session/message-queue-store.ts`) exposing: `enqueue`, `list(sessionId)` ordered by position, `remove(id)`, `updateContent(id, content)`, `move(id, beforeId | afterId)` using sparse positions with a renumber fallback when the gap closes, `clear(sessionId)` returning the removed rows (Stop needs them back, see 4.7), and `rekeySession(fromId, toId)`.\\n\\n`rekeySession` is load-bearing and easy to miss: a brand-new session gains its canonical SDK id mid-first-turn, and every row keyed by the request UUID must move with it. The existing rebind already moves the `session_metadata` row; this join that move. A queue left behind at the old key is invisible forever.\\n\\nSweeping: rows whose session no longer exists are removed by the same health check that evicts sessions, so an abandoned session cannot accumulate queue rows for the life of the install.\\n\\nWhy persist at all: ADR-0264 accepts losing an in-flight TURN on restart. Losing a message somebody typed and was told was accepted is a different and worse promise to break. DOR-480 already established that this class of loss is unacceptable, which is why the client queue carries a `restore` handle today.\\n\\nAcceptance criteria:\\n1. Enqueue, list, remove, edit, reorder, and clear all round-trip through SQLite with correct ordering.\\n2. A reorder is a single-row UPDATE while sparse gaps remain; the renumber fallback is exercised by a test that closes a gap.\\n3. `rekeySession(from, to)` moves every row and is idempotent when the ids match or the source has no rows.\\n4. `clear(sessionId)` returns the rows it removed, in order.\\n5. The migration applies cleanly to an existing dev database with sessions in it, and is keyed to a version strictly greater than the newest released `v*` tag.\\n6. No route or dispatcher is wired yet; this task is storage only.\",\n+ \"activeForm\": \"Building the durable queue store\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"2.1\"],\n+ \"parallelWith\": [\"3.1\", \"3.2\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"2.3\",\n+ \"phase\": 2,\n+ \"phaseName\": \"P2 — Server-owned queue\",\n+ \"subject\": \"[persistent-session-runtime] [P2] Build the dispatcher as the single ingress, and audit every trigger caller through it\",\n+ \"description\": \"The dispatcher is where a message stops being a request and becomes a turn. It is the one place that decides whether to run now, queue, or degrade, and every caller that can start a turn must go through it or that caller keeps the old race.\\n\\nBuild it (suggested `apps/server/src/services/session/message-dispatcher.ts`) with these rules:\\n1. Accept a message with a requested disposition; mint a `messageId`; write the row via the store from task 2.2; return a `MessageDeliveryOutcome` plus the queue position.\\n2. Resolve the disposition against the resolved runtime's capabilities and the session's live state. In THIS phase every disposition resolves to 'queue' (the capability flags are all false from task 2.1), so `steer` and `stage` come back as `applied: 'queue', degradedBecause: 'unsupported'`. The ladder's shape lands now; its native branches land in phase 4.\\n3. Dispatch the head of the queue when a turn ends. Dequeue on `turn_end`, NEVER on a bare `result`: premature dequeue is a known failure in every queue-capable tool (OpenCode #15696) and dequeuing on `result` is exactly how you get it.\\n4. Never dispatch while `projector.hasPendingInteractions()` is true. That probe already exists and is already shared by the write lock and the stall watchdog in `trigger-turn.ts`; reuse it rather than inventing a third liveness notion. Firing a queued prompt into an open permission ask is the other known failure (Gemini #17719, OpenCode #2609).\\n5. Order by `position`, FIFO within a position.\\n6. Keep DOR-1088's `SessionTurnQueue` as the intra-process ordering primitive underneath. It is not replaced. What changes is that the HTTP request no longer waits on it (task 2.4).\\n7. Dispatch and reap share the dispatch mutex, so a reap racing a dispatch simply does not happen. (The reaper arrives in phase 3; leave the seam.)\\n\\nAudit and migrate every existing trigger caller to route through the dispatcher: `routes/sessions.ts` (the message POST), `routes/session-ui-action-handler.ts`, `routes/session-command-intent-handler.ts`, `services/rooms/room-turn-runner.ts`, `services/session/embedded-turn-trigger.ts` (two call sites), `services/tasks/run-stream.ts`, and `services/mesh/mcp-signin-resume.ts`. Note that claude-code's `executeCommandIntent` is literally `sendMessage('/compact')`, so command intents contend identically and go through the dispatcher too.\\n\\nAcceptance criteria:\\n1. A message sent to a BUSY session is accepted and queued; it dispatches automatically when the running turn's `turn_end` lands.\\n2. A message sent to an IDLE session runs immediately, with `applied: 'queue', requested: 'queue'` and no degradation notice.\\n3. A queued message does NOT dispatch while a pending interaction is open, and DOES dispatch once that interaction is resolved.\\n4. A queued message behind a turn that FAILS still dispatches; a failed turn does not eat the queue.\\n5. The caller audit is a TEST, not a claim: assert that no module outside the dispatcher calls `runtime.sendMessage` or `runtime.executeCommandIntent` for a person-initiated turn (an import-graph or grep-based guard test in the same shape as the existing SDK-confinement checks).\\n6. `steer` and `stage` requests return `applied: 'queue'` with `degradedBecause: 'unsupported'`.\",\n+ \"activeForm\": \"Building the dispatcher as the single ingress\",\n+ \"size\": \"large\",\n+ \"points\": 8,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"2.2\", \"1.1\"],\n+ \"parallelWith\": [\"3.2\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"2.4\",\n+ \"phase\": 2,\n+ \"phaseName\": \"P2 — Server-owned queue\",\n+ \"subject\": \"[persistent-session-runtime] [P2] Retire 409 from the message POST and add the queue routes\",\n+ \"description\": \"Change what `POST /api/sessions/:id/messages` means, and give the queue an HTTP surface.\\n\\nThe POST accepts an optional `disposition` in the body, defaulting to 'queue'. It returns 202 IMMEDIATELY with `{ sessionId, messageId, outcome, queuePosition }`. Two behaviors go away with this change:\\n- The 409 SESSION_LOCKED answer on the message path. A busy session is no longer a refusal; it is a queue.\\n- DOR-1088's interim behavior of holding the HTTP socket open until the queued turn actually starts. The 202 now resolves at acceptance, and the client learns the turn started from the durable stream like everything else.\\n\\nThe canonical-id contract is unchanged: the 202's `sessionId` is still best effort, resolved by tapping the runtime's stream with a 5-second bound, and it still converges later via the retire announce.\\n\\nAdd:\\n- `GET /api/sessions/:id/queue` returning the queue. Redundant with the snapshot on purpose, and worth having for integrations and debugging.\\n- `PATCH /api/sessions/:id/queue/:messageId` to edit content or move position.\\n- `DELETE /api/sessions/:id/queue/:messageId` to remove one.\\n\\nThe write lock survives, retargeted. It stops being 'who may POST' and becomes the internal dispatch mutex held for one turn window. Its inactivity-TTL machinery (`LockActivity`, DOR-782) is unchanged and is still what reclaims a dark turn, so a crashed holder still frees its session.\\n\\nRewrite clause 3 of `apps/server/src/routes/__tests__/sessions-cross-client.test.ts`. That test's own header already says this is coming: 'DOR-82 will replace this incidental semantics with explicit queue/steer/interrupt dispositions'. It currently asserts 409-while-alive and takeover-once-dark on the message path. It becomes: a second client's mid-turn POST is ACCEPTED (202) and queued, both clients see the same queue on their streams, and the message runs when the first turn ends. Preserve the DOR-782 lesson in the rewritten comment so the next reader does not re-derive it.\\n\\nAcceptance criteria:\\n1. A POST to a busy session returns 202 with a `messageId` and a queue position. There is NO code path on the message route that returns 409 SESSION_LOCKED.\\n2. The POST returns without waiting for the turn ahead of it: measure that the response settles while the prior turn is still streaming.\\n3. Queue GET/PATCH/DELETE work and reject unknown ids with 404 and malformed ids with 400, matching the route conventions already in that file.\\n4. `sessions-cross-client.test.ts` clause 3 asserts accept-and-queue and is green.\\n5. A second client can remove or edit a message the FIRST client queued; the queue is per session, not per client.\\n6. Express 5 semantics respected: an empty POST body leaves `req.body` undefined and is rejected as a 400, not a crash.\",\n+ \"activeForm\": \"Retiring 409 and adding the queue routes\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"2.3\"],\n+ \"parallelWith\": [\"2.5\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"2.5\",\n+ \"phase\": 2,\n+ \"phaseName\": \"P2 — Server-owned queue\",\n+ \"subject\": \"[persistent-session-runtime] [P2] Surface the queue on the snapshot and the durable stream, and rehydrate it after restart\",\n+ \"description\": \"Make the queue visible to every window through the mechanism ADR-0264 already provides, and make it come back after a restart.\\n\\nWire `SessionStateProjector` (`apps/server/src/services/session/session-state-projector.ts`) so that:\\n1. `getSessionSnapshot` includes `queuedMessages`, read from the store, so a cold connect sees the queue in the same payload as messages, status, and pending interactions. A client that has just hydrated must never have to make a second request to know what is queued.\\n2. Every queue mutation (enqueue, edit, reorder, remove, dispatch, clear) emits a `queue_update` event carrying the WHOLE queue and, when the update was caused by an accepted message, the `MessageDeliveryOutcome`. The event takes a `seq` like any other, so the client's existing idempotent-apply-by-seq logic covers it with no new rules.\\n3. On projector creation for a session that has queue rows on disk, the queue is loaded so a post-restart snapshot is correct. This is the restart half of the durability promise and it is easy to forget: the rows survive, but a projector that never reads them reports an empty queue and the dispatcher never fires.\\n\\nAcceptance criteria:\\n1. A cold `GET /api/sessions/:id/events` connect returns a snapshot whose `queuedMessages` matches the store exactly, in order.\\n2. Enqueueing from window A produces a `queue_update` on window B's stream within the normal event latency, carrying the full queue.\\n3. Removing from window B produces a `queue_update` on window A.\\n4. A `queue_update` caused by a degraded acceptance carries the outcome with `requested`, `applied`, and `degradedBecause` populated.\\n5. Server restart with three messages queued: after restart, a cold connect's snapshot shows all three in the original order, and they dispatch normally when a turn ends.\\n6. Reconnect with `Last-Event-ID` still replays gap-free with `queue_update` events in the sequence; the epoch check and the `StaleResumeCursorError` fallback are unaffected.\",\n+ \"activeForm\": \"Surfacing the queue on the snapshot and stream\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"2.2\", \"2.3\"],\n+ \"parallelWith\": [\"2.4\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"2.6\",\n+ \"phase\": 2,\n+ \"phaseName\": \"P2 — Server-owned queue\",\n+ \"subject\": \"[persistent-session-runtime] [P2] Cut the cockpit over from the local queue to the server queue, preserving every affordance\",\n+ \"description\": \"Replace the client-owned queue (ADR-0104) with a view of the server's, without losing a single thing the composer can do today.\\n\\nThe current implementation is `apps/client/src/layers/features/chat/model/use-message-queue.ts` plus `use-chat-queue.ts` and the session-entity queue store. It is ephemeral React state: lost on refresh, invisible to a second window, and flushed on the streaming-to-idle edge. What it gets RIGHT and must be preserved exactly:\\n- Queue chips with edit-in-place, keyed by a stable `editingId` that survives queue mutations rather than a positional cursor.\\n- Reorder and remove.\\n- Send-now.\\n- The `restore` handle. It exists because a refused trigger once destroyed a person's typed words (DOR-480). In the server world the equivalent promise is that a failed enqueue puts the text back in the composer rather than dropping it.\\n\\nWhat changes: the queue is read from the session snapshot and kept current by `queue_update` events; mutations go to the queue routes; the streaming-to-idle auto-flush disappears entirely because the server dispatches. Delete the local FIFO and its auto-flush effect rather than leaving it dormant. Two queues means two sources of truth and a reconciliation bug waiting to happen.\\n\\nAlso surface, quietly: a chip queued by another window is visibly not this window's (the `enqueuedBy` field carries the client id). It stays fully editable; it just does not pretend to be yours.\\n\\nThe degradation notice slot lands here but stays unused until phase 4: when an outcome carries `degradedBecause`, the chip can say what happened. The one case that must stay SILENT is `degradedBecause: 'session-idle'`, because 'it ran immediately' is not a degradation anybody needs told.\\n\\nAcceptance criteria:\\n1. Type three messages while the agent works: all three appear as chips, survive a hard refresh, and appear in a second window.\\n2. Edit a chip in window A; window B shows the edit.\\n3. Remove a chip in window B; window A's list updates.\\n4. Reorder in either window; both agree on the order and the dispatch order matches.\\n5. When the turn ends, the head dispatches automatically and its chip disappears in both windows.\\n6. A failed enqueue (network down) returns the text to the composer; nothing typed is lost.\\n7. `use-message-queue.ts`'s local FIFO and its auto-flush effect are DELETED, not left dormant. Knip reports no orphaned queue code.\\n8. Every existing queue test either migrates to the server-backed behavior or is deleted with its reason recorded; none is left asserting the old local semantics.\",\n+ \"activeForm\": \"Cutting the cockpit over to the server queue\",\n+ \"size\": \"large\",\n+ \"points\": 8,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"2.4\", \"2.5\"],\n+ \"parallelWith\": [\"3.4\", \"3.5\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"2.7\",\n+ \"phase\": 2,\n+ \"phaseName\": \"P2 — Server-owned queue\",\n+ \"subject\": \"[persistent-session-runtime] [P2] Write ADR-c (server-owned durable message queue), supersede ADR-0104, and update the integration docs\",\n+ \"description\": \"Record the decision and tell integrators what changed.\\n\\nWrite the ADR at `decisions/-server-owned-durable-message-queue.md` using an id from `.claude/scripts/id.ts`, and add its `decisions/manifest.json` entry. Content:\\n- Context: the queue lived in the browser as ephemeral React state (ADR-0104), lost on refresh, invisible to a second window, with a `409 SESSION_LOCKED` refusal standing in for coordination between clients.\\n- Decision: the server owns the queue, persisted, keyed by canonical session id, surfaced on the snapshot and the durable stream, mutable from any window. Native runtime queuing stays an adapter-level optimization and never the contract.\\n- This AMENDS ADR-0264 by naming the queue as the thing that sits behind the trigger-only POST, which ADR-0264's own context anticipated but did not build.\\n- This SUPERSEDES ADR-0104. Edit ADR-0104's front matter to set `superseded-by` and add a line explaining what replaced it and why (durability and multi-window, not dissatisfaction with the original design, which was correct for its time).\\n- Consequences, honestly including the negative: a persisted queue is a migration and a new sweep obligation, and the 202 now means 'accepted' rather than 'running', which is a real semantic change for any integrator polling on it.\\n\\nUpdate `docs/integrations/sse-protocol.mdx`: the `queue_update` event, the `queuedMessages` snapshot field, and the retirement of 409 from the message POST. This file is the public integration contract, so the change must be described from an integrator's point of view, not the implementation's.\\n\\nAdd a changelog fragment in `changelog/unreleased/` (`-.md`) written per the `writing-for-humans` standard: plain enough for a smart 9th grader who does not code. Describe what happens for the person ('messages you type while an agent is working now wait safely on the server, so they survive a refresh and show up in every window'), never the mechanism.\\n\\nAcceptance criteria:\\n1. ADR-c exists with a timestamp id, is registered in `decisions/manifest.json`, and follows the repo's ADR shape (Status / Context / Decision / Consequences with Positive and Negative).\\n2. ADR-0104's front matter carries `superseded-by` pointing at ADR-c.\\n3. `docs/integrations/sse-protocol.mdx` documents `queue_update`, `queuedMessages`, and the 409 retirement.\\n4. A changelog fragment exists and passes the `fragment-present` CI gate.\\n5. No user-facing copy uses hype language or describes internals.\",\n+ \"activeForm\": \"Writing ADR-c and updating the integration docs\",\n+ \"size\": \"small\",\n+ \"points\": 3,\n+ \"priority\": \"medium\",\n+ \"dependencies\": [\"2.6\"],\n+ \"parallelWith\": [],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.1\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Adopt the push()-capable held prompt into sdk-utils as the pump's input seam\",\n+ \"description\": \"Convert the held streaming-input prompt from a one-shot into a queue-driven generator that can accept more messages while it is open. This is the seam the whole pump grows out of, and it can land independently and early.\\n\\nToday `createHeldPrompt` in `apps/server/src/services/runtimes/claude-code/sdk/sdk-utils.ts` yields each of its `messages` and then parks on a single `held` promise until `close()` resolves it. It cannot accept anything after construction.\\n\\nThe DOR-1087 branch (`worktree-dor-1087-phantom-stop`) has ALREADY written this conversion: the generator drains an internal queue, parks on a `wake` promise, and `push(content)` appends and wakes it, returning `false` once closed. ADOPT THAT IMPLEMENTATION rather than writing a second one, and coordinate with whoever is finishing DOR-1087 so the two do not diverge into subtly different generators. If DOR-1087 has landed by the time this task starts, this task is a no-op verification; if it has not, lift the conversion and let DOR-1087 rebase onto it.\\n\\nThe contract to land:\\n- `HeldUserPrompt` gains `push(content: string): boolean` documented as: the CLI queues the message and delivers it at its next opportunity within the live turn; returns false and sends nothing once `close()` has been called.\\n- `close()` stays idempotent and still terminates the generator so the subprocess drains and exits.\\n- `createIdlePrompt()` (zero messages, an intentional idle probe used to read a session's command set at zero token cost) keeps working unchanged.\\n\\nAcceptance criteria:\\n1. `push` before the generator is consumed, and `push` while it is parked, both deliver in FIFO order.\\n2. `push` after `close` returns `false` and yields nothing.\\n3. `close` is idempotent and always terminates the generator, including when the queue is non-empty at close time (define and TEST the chosen behavior: drain-then-close is the recommendation, so nothing already accepted is silently dropped).\\n4. `createIdlePrompt()` still yields nothing and still holds the stream open.\\n5. Existing `sdk-utils.test.ts` cases are green, plus new cases for each behavior above.\\n6. No caller behavior changes yet: `message-sender.ts` still uses one message and closes on the first `result`.\",\n+ \"activeForm\": \"Adopting the push-capable held prompt\",\n+ \"size\": \"small\",\n+ \"points\": 3,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"1.1\"],\n+ \"parallelWith\": [\"0.1\", \"2.1\", \"2.2\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.2\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Build the SessionPump: state machine, warmth reporting, and launch/teardown\",\n+ \"description\": \"Create the long-lived process owner. New module `apps/server/src/services/runtimes/claude-code/sessions/session-pump.ts`, inside the claude-code adapter so the SDK stays confined there (Hard Rule 2).\\n\\nThe pump owns: the long-lived `query()`, its held input stream (from task 3.1), the demux of its output, the idle timer (task 3.4), and the crash detector (task 3.6). `executeSdkQuery` stops being 'the turn' and becomes the pump's launcher.\\n\\nStates and transitions to implement exactly:\\n\\n| From | To | Trigger | Guard | Side effects |\\n| --- | --- | --- | --- | --- |\\n| COLD | WARMING | first dispatch or explicit warm | under the warm ceiling | `query()` with `resume` when `hasStarted`, else fresh |\\n| WARMING | WARM | `system/init` received | | capabilities feature-detected and cached; control methods usable |\\n| WARMING | CRASHED | exit or throw before init | | dispatch fails over to RESUMING once |\\n| WARM | RUNNING | dispatch | dispatch mutex held; no pending interaction | `turn_start` ingested; stall watchdog armed |\\n| RUNNING | WARM | correlated `result` | | one `turn_end`; watchdog disarmed; idle timer armed; queue head dequeued |\\n| RUNNING | CRASHED | exit or throw mid-turn | | open window closed with `turn_end{terminalReason:'error'}`; queue preserved |\\n| WARM | REAPED | idle timer or LRU eviction | no open turn AND no pending interaction | `close()` on the held stream |\\n| any | COLD | session eviction | | reap first, then drop the session record |\\n| CRASHED | RESUMING | next dispatch | | fresh `query()` with `resume`: today's path exactly |\\n| RESUMING | WARMING | `query()` returns | | |\\n\\nAdd to `AgentRuntime` in `packages/shared/src/agent-runtime.ts`, both OPTIONAL so runtimes with no warm concept simply omit them:\\n- `export type SessionWarmth = 'cold' | 'warming' | 'warm' | 'running' | 'crashed'`\\n- `getSessionWarmth?(sessionId: string): SessionWarmth`\\n- `reapSession?(sessionId: string): Promise` documented as: closes the warm process without touching the session record or its transcript; idempotent; a no-op when not warm; NEVER called while a pending interaction is open.\\n\\nCapability feature detection: read the `capabilities` array from `system/init` and cache it per pump. Feature-detect, never version-sniff; the SDK's own docs instruct this, and it is what lets an older CLI degrade honestly instead of crashing.\\n\\nWire teardown into `shutdownServices()` in `apps/server/src/index.ts` so no warm subprocess survives DorkOS. The OpenCode sidecar teardown (SIGTERM, then SIGKILL after a grace window, no-op when never booted) is the model.\\n\\nAcceptance criteria:\\n1. Every transition in the table is unit-tested by driving the pump directly, including the guards (a dispatch is refused while a pending interaction is open; a warm is refused over the ceiling).\\n2. `getSessionWarmth` returns the state the machine is actually in at each point, and `'cold'` for an unknown id.\\n3. `reapSession` is idempotent and a no-op when cold.\\n4. `shutdownServices()` leaves zero orphan subprocesses; assert by process inspection in an integration test.\\n5. Nothing is wired to the dispatcher yet, and the flag is off by default, so this task changes no runtime behavior.\",\n+ \"activeForm\": \"Building the SessionPump state machine\",\n+ \"size\": \"large\",\n+ \"points\": 8,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.1\", \"2.1\"],\n+ \"parallelWith\": [\"2.3\", \"2.4\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.3\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Window the pump's output into turns, correlated by messageId\",\n+ \"description\": \"Turn the pump's single continuous output into the discrete turns the durable stream expects.\\n\\nThe rule: a DorkOS turn OPENS on dispatch and CLOSES on the `result` that answers it.\\n\\nToday the units coincide, which is why nothing needed windowing: one `sendMessage` equals one `query()` equals one `result` equals one `done` equals one `turn_end`. With a pump they come apart, and the CLI can also start continuations DorkOS never asked for (auto-resume continuations are named in the SDK's own `still_queued` documentation).\\n\\nImplement:\\n1. Each dispatch stamps its `SDKUserMessage` with the server-minted `messageId` as the message `uuid` and opens a turn window.\\n2. A `result` is correlated back to the window by that id. Correlation is by id and NEVER positional: the SDK coalesces a dequeued batch into ONE turn, so several dispatched ids can share one `result`. Text matching was already rejected for this exact ambiguity when the room runner needed turn identity; do not reintroduce it.\\n3. On the correlated `result`, close the window: exactly one `turn_end`, with `terminalReason` resolved by the existing rules. Task 0.1's idempotence guard is what makes a second `result` harmless rather than a second close.\\n4. A `result` with NO correlated `messageId` opens a synthetic turn tagged `origin: 'runtime'`. It is not dropped and it is not disguised as a person's turn. The durable stream must stay a complete account of the session; this is the same honesty rule the presence contract already enforces on every runtime.\\n5. `session.contextBreakdown` and the subscription-usage fetch currently happen once, at the first `result`, immediately before `heldPrompt.close()`. They must now happen per window close, WITHOUT closing the stream.\\n\\nAcceptance criteria:\\n1. Three dispatches through one pump produce exactly three `turn_start`/`turn_end` pairs on the durable stream, in order, with no overlap.\\n2. A coalesced batch (two dispatched ids, one `result`) closes BOTH windows correctly rather than leaving one open forever.\\n3. An uncorrelated `result` produces a turn tagged `origin: 'runtime'` and is visible on the stream.\\n4. `context_usage` is emitted before `done` within every window, not just the first.\\n5. The subprocess is still alive after a window closes: `getSessionWarmth` reports `'warm'`, and a control method (e.g. `getContextUsage`) still answers.\\n6. Killing the process mid-window closes that window with `turn_end{terminalReason:'error'}` and exactly one of them.\",\n+ \"activeForm\": \"Windowing the pump output into turns\",\n+ \"size\": \"large\",\n+ \"points\": 8,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.2\", \"0.1\"],\n+ \"parallelWith\": [\"2.5\", \"2.6\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.4\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Add the process idle timer and the warm-session LRU ceiling\",\n+ \"description\": \"Bound how long a warm process lives and how many exist at once. These are two DIFFERENT timers from session eviction, and conflating them is the trap this task exists to avoid.\\n\\nAdd to `apps/server/src/config/constants.ts` under `SESSIONS`:\\n- `WARM_IDLE_MS: 5 * 60 * 1000` with a TSDoc explaining it governs WARM to REAPED (how long a live subprocess sits with no turn open) and is NOT session eviction. Long enough that a person thinking between turns keeps their cache; short enough that abandoned sessions do not hold subprocesses.\\n- `MAX_WARM_SESSIONS: 12` with a TSDoc explaining it counts PROCESSES, while the existing `MAX_SESSIONS: 50` counts session RECORDS. Warmth is a cache, so it is LRU-evicted down to the ceiling regardless of the idle timer. Records stay at 50 so `ensureSession`'s existing throw stays the genuinely exceptional path it is today.\\n\\nImplement in the pump registry:\\n1. The idle timer arms when a turn window closes and disarms on the next dispatch. On fire: reap.\\n2. LRU eviction: when a new pump would exceed `MAX_WARM_SESSIONS`, reap the least recently used WARM pump first.\\n3. REAP IS FORBIDDEN while `projector.hasPendingInteractions()` is true. `INTERACTION_TIMEOUT_MS` is 10 minutes, LONGER than the 5-minute idle window, so this is not a theoretical race: a person can walk away from an approval card and have the reaper fire under them, and a reaped process cannot answer the approval they come back to. Reuse the existing probe; do not invent a third liveness notion.\\n4. Reap is forbidden while a turn window is open, enforced by the shared dispatch mutex so a reap racing a dispatch simply does not happen.\\n5. Hook the sweep into the existing `checkSessionHealth` cadence (`INTERVALS.HEALTH_CHECK_MS`, 5 minutes) rather than adding another interval. Session eviction continues to imply reap; reap never implies eviction.\\n\\nAcceptance criteria:\\n1. A warm session with no dispatch for `WARM_IDLE_MS` is reaped; `getSessionWarmth` goes to `'cold'` and the subprocess exits.\\n2. A warm session with a PENDING INTERACTION open is NOT reaped, even well past `WARM_IDLE_MS`; it is reaped once the interaction resolves and the window closes.\\n3. Warming a 13th session with `MAX_WARM_SESSIONS: 12` reaps the least recently used one first; the session RECORD count is unaffected and stays bounded by 50.\\n4. Session eviction at `TIMEOUT_MS` reaps the pump before dropping the record; no subprocess outlives its session record.\\n5. A reap and a dispatch racing on the same session cannot interleave: assert with a deterministic scheduling test, not a sleep.\\n6. Both new constants have TSDoc that names what they are NOT, so the next reader does not conflate them.\",\n+ \"activeForm\": \"Adding the idle timer and warm ceiling\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.2\"],\n+ \"parallelWith\": [\"3.5\", \"3.6\", \"2.6\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.5\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Implement the relaunch pin list, including the unconditional account pin\",\n+ \"description\": \"A warm process pins whatever it was launched with. Any change to a pinned value must force a reap and relaunch, or the next turn runs under stale settings. This is the highest-severity task in the phase: getting the account row wrong bills a paying client's conversation to the wrong account.\\n\\nToday every one of these is resolved PER TURN inside `executeSdkQuery`. On a pump they are resolved once, at launch, so each needs a decision and an enforcement point.\\n\\nMust force a REAP AND RELAUNCH when changed:\\n- `cwd` (the effective working directory resolved from message opts, session cwd, then default).\\n- The Claude account root, i.e. `CLAUDE_CONFIG_DIR` from `claudeConfigDirEnv(session.accountRoot ?? resolveActiveClaudeRoot())`. UNCONDITIONAL. A session's transcript exists under exactly one account and only that account may resume it and bill for it.\\n- The resolved credential env from `resolveClaudeCredentialEnv()` (ADR-0315). A revoked credential must not keep working because the process that holds it launched before the revocation.\\n- The agent identity token from `resolveAgentTokenEnv(...)`.\\n- The system-prompt append (built from the agent manifest's tool-group settings plus any caller-supplied append).\\n- `settingSources` and the process `env` block generally.\\n\\nMust NOT force a relaunch; mutate the live query instead:\\n- `mcpServers`: use `setMcpServers` on the live query.\\n- `plugins`: use `reload_plugins`, which is already wired for the live-session propagation path.\\n- `permissionMode`: use `setPermissionMode`. Keep the existing auto-to-default coercion guard for models that do not support auto, and keep it a per-dispatch coercion that never mutates the stored preference.\\n- `model` / `effort` / `fastMode`: use `setModel` where the SDK genuinely supports the change on a live query, and relaunch otherwise. VERIFY PER FIELD against the live SDK during this task; do not assume all three behave alike, and record what you verified in the adapter's `NOTES.md` alongside the other live-verified facts.\\n\\nImplementation shape: compute a launch fingerprint from the must-relaunch set, store it on the pump, and compare on every dispatch. A mismatch reaps and relaunches BEFORE the turn opens, transparently to the person.\\n\\nAcceptance criteria:\\n1. Each must-relaunch value, changed between two dispatches, causes exactly one reap-and-relaunch and the second turn observes the new value.\\n2. The ACCOUNT case has a dedicated test that would otherwise bill the wrong account: a session whose `accountRoot` differs from the active root must launch under its own, and a change must relaunch.\\n3. Each live-mutable value, changed between two dispatches, causes NO relaunch and is observed by the second turn.\\n4. The per-field `setModel` verdicts are recorded in `claude-code/NOTES.md` with what was verified and how.\\n5. A relaunch preserves the queue and the session record; only the process is replaced.\\n6. Boundary validation is not in this task (see 3.9) but the fingerprint must not be mistaken for it: a fingerprint match is not a boundary check.\",\n+ \"activeForm\": \"Implementing the relaunch pin list\",\n+ \"size\": \"large\",\n+ \"points\": 8,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.2\"],\n+ \"parallelWith\": [\"3.4\", \"3.6\", \"2.6\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.6\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Detect process death and fall back to the resume path with the queue intact\",\n+ \"description\": \"Make the persistent path degrade into the old path instead of failing.\\n\\nWith resume-per-message, a crash cost one turn and the next message trivially restarted. With a pump the blast radius is the SESSION: warm cache, the in-flight turn, and every message queued behind it. The queue surviving a crash is the entire justification for it being server-owned, so this task is where that promise is kept.\\n\\nImplement:\\n1. Detect the process ending: subprocess exit, the SDK generator throwing, or the stream closing unexpectedly, both mid-window and while WARM.\\n2. Mid-window: close the open turn with `turn_end{terminalReason:'error'}` and a typed `error` event carrying the failure, exactly as `guardTurnErrors` does today for a thrown `sendMessage`. The durable stream must show `status_change(error)`, then the typed `error`, then one `turn_end(error)`, and never a frozen `streaming`.\\n3. PRESERVE THE QUEUE. A crash must not clear it. Queued messages dispatch after recovery.\\n4. Transition to CRASHED. The next dispatch goes to RESUMING: a fresh `query()` with `resume` set. This is today's path exactly, F1 (`resumeSessionAt` anchoring) and F2 (`isResumeFailure` retry) included, and both are deliberately retained HERE rather than deleted, because this is the recovery route the spec keeps them for.\\n5. Bound the failover: one automatic resume attempt per crash. A second consecutive crash surfaces as a turn error rather than looping, so a genuinely broken session cannot spin.\\n\\nAcceptance criteria:\\n1. Killing the subprocess mid-turn closes that turn with `turn_end{terminalReason:'error'}` and exactly one of them; the session is not left `streaming`.\\n2. Two messages queued behind the crashed turn are still in the queue afterwards, in order, and dispatch once the session recovers.\\n3. The next dispatch after a crash resumes the conversation, and the transcript is continuous: the recovered turn sees the prior conversation.\\n4. A crash while WARM (no turn open) is detected and reported as warmth `'crashed'`, with no spurious turn on the stream: nothing was running, so nothing should appear to have failed.\\n5. Two consecutive crashes surface an error to the person rather than looping.\\n6. The resume fallback still applies its anchor and its stale-session retry, unchanged, and the existing tests covering both are green.\",\n+ \"activeForm\": \"Detecting process death and falling back to resume\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.2\", \"2.3\"],\n+ \"parallelWith\": [\"3.4\", \"3.5\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.7\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Arm and disarm the stall watchdog per turn window instead of per generator\",\n+ \"description\": \"Stop the stall watchdog from shooting a healthy warm session.\\n\\nToday `withStallGuard` (composed inside `guardTurnErrors` in `apps/server/src/services/session/trigger-turn.ts`) wraps the whole `sendMessage` generator, which today equals exactly one turn. Its inactivity window is `SESSIONS.TURN_STALL_TIMEOUT_MS`, 10 minutes, and it pauses while the session is parked on a person. On a stall it interrupts the runtime and injects the typed-error terminal sequence.\\n\\nOn a pump the generator spans the PROCESS, not a turn. Left as is, a WARM session sitting legitimately silent for 10 minutes would be interrupted for no reason: the watchdog exists to end a turn that has gone dark, and a warm session is not a turn and has nothing to end.\\n\\nImplement: arm on turn-window OPEN, disarm on turn-window CLOSE. Silence with no window open is bounded by the idle timer from task 3.4 instead, which is both the right mechanism and shorter anyway (5 minutes versus 10).\\n\\nEverything else about the guard is unchanged and must stay: the pause while `hasPendingInteractions()` is true, the bounded interrupt (`STALL_INTERRUPT_TIMEOUT_MS`, 30 seconds, so a wedged `interruptQuery` cannot itself hang the thing meant to unstick a hung turn), and the clean stream ending so `feedProjector` settles and the lock releases as on any turn.\\n\\nAcceptance criteria:\\n1. A WARM session silent past `TURN_STALL_TIMEOUT_MS` is NOT interrupted; it is reaped by the idle timer instead.\\n2. A turn window that goes silent past the timeout IS interrupted and closes with the typed-error terminal sequence, exactly as today.\\n3. A turn parked on a pending interaction is not interrupted for as long as the person takes, bounded by `INTERACTION_TIMEOUT_MS`.\\n4. The bounded-interrupt path still applies: a wedged interrupt closes the turn anyway after `STALL_INTERRUPT_TIMEOUT_MS`.\\n5. Existing stall-guard tests pass unchanged where they describe within-turn behavior.\",\n+ \"activeForm\": \"Rearming the stall watchdog per turn window\",\n+ \"size\": \"small\",\n+ \"points\": 3,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.3\"],\n+ \"parallelWith\": [\"3.8\", \"3.9\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.8\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Add the per-session opt-in config field and its migration\",\n+ \"description\": \"Give the persistent path an off switch, defaulting off.\\n\\nAdd a boolean under `runtimes.claudeCode` in `packages/shared/src/config-schema.ts` (suggested `persistentSession`), defaulting `false`, with Zod as the authoritative schema. Then add a semver-keyed backfill to `CONFIG_MIGRATIONS` in `apps/server/src/services/core/config-manager.ts`, following `backfillRuntimesDefaults` as the pattern.\\n\\nMigration rules that bite if ignored: key the migration to a NEW version strictly greater than the newest `v*` tag (`git tag -l 'v*' | sort -V | tail -1`), and never extend a key that has already shipped. `conf` runs a key only in `(storedVersion, projectVersion]`, so a key at or below a released version, or a body appended to one, never runs for anybody already on it. A guard test compares every key's source text against the newest release and reddens CI if this is wrong.\\n\\nWhy per-session opt-in rather than a global flag: the two paths must run side by side on one host, because that is the only way to compare them on the same workload, and because the resume path is not going away (it is the recovery route). The flag is read at pump launch, so a session that started on one path stays on it until its process is replaced.\\n\\nUpdate `contributing/configuration.md` with the new field and what it does.\\n\\nAcceptance criteria:\\n1. The field exists in the Zod schema with a `false` default and a TSDoc sentence describing the user-visible effect, not the mechanism.\\n2. The migration is keyed above the newest release tag and the migration-safety guard is green.\\n3. With the flag off, claude-code behaves byte-for-byte as it does today: resume-per-message, one process per turn. Assert this with the existing adapter suite unchanged.\\n4. With the flag on, the pump is used.\\n5. Two sessions on one host, one with the flag on and one off, both work.\\n6. `contributing/configuration.md` documents the field.\",\n+ \"activeForm\": \"Adding the opt-in config field and migration\",\n+ \"size\": \"small\",\n+ \"points\": 3,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.2\"],\n+ \"parallelWith\": [\"3.7\", \"3.9\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.9\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Move boundary validation from launch to dispatch\",\n+ \"description\": \"Keep the directory boundary check on the path a cwd can actually change.\\n\\n`executeSdkQuery` currently calls `validateBoundaryOrDorkHome(effectiveCwd)` at the top of every turn, yielding a typed boundary-violation error and returning when it fails. That is per-turn today because every turn is a fresh launch.\\n\\nOn a pump, launch happens once. If the boundary check moves to launch along with everything else, a cwd change between dispatches would slip past it. The pin list (task 3.5) forces a relaunch on a cwd change, which mostly covers it, but 'mostly' is not the standard for a security boundary: the check must be its own guarantee and not a side effect of a fingerprint comparison.\\n\\nImplement: run `validateBoundaryOrDorkHome` per DISPATCH, before the turn window opens. On failure, yield the same typed error and do not open a window. Keep the existing carve-out semantics exactly: the agents-subtree seam stays allowed (the system agent and marketplace agents legitimately run outside a narrow boundary), while dork-home siblings such as the credential store and boundary-external paths stay denied.\\n\\nAcceptance criteria:\\n1. A dispatch with an out-of-boundary cwd is refused with the existing typed error, and no turn window opens.\\n2. A session that dispatches in-boundary, then out-of-boundary, is refused on the second dispatch even though the process is already warm.\\n3. The agents-subtree carve-out still permits a DorkBot or marketplace-agent turn in its own home directory.\\n4. The credential-store sibling path is still denied.\\n5. A refused dispatch does not reap or crash the pump; the session stays usable for a subsequent in-boundary message.\",\n+ \"activeForm\": \"Moving boundary validation to dispatch\",\n+ \"size\": \"small\",\n+ \"points\": 2,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.3\"],\n+ \"parallelWith\": [\"3.7\", \"3.8\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.10\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Declare supportsPersistentSession and add the warmth conformance cases\",\n+ \"description\": \"Turn the flag on for claude-code and hold it to the contract.\\n\\nSet `supportsPersistentSession: true` in `claude-code/runtime-constants.ts`. The other two flags stay `false` until phase 4.\\n\\nAdd to `RuntimeConformanceOpts` in `packages/test-utils/src/runtime-conformance.ts`:\\n\\n```ts\\n /**\\n * Drives a session to WARM (a completed turn with the process still held) and\\n * hands control back. Provided ONLY by runtimes declaring\\n * `supportsPersistentSession`. Omit it and the warmth cases SKIP by name\\n * rather than passing on an absence the suite manufactured.\\n */\\n warmSession?: (runtime: AgentRuntime, sessionId: string) => Promise;\\n```\\n\\nAdd two cases:\\n- **C4 warmth honesty.** A runtime declaring `supportsPersistentSession` must report `lifecycle: 'idle'` with `inProgressTurn: null` while WARM. The presence contract already forbids `streaming` with an empty `inProgressTurn` because an empty array is absence wearing the shape of presence; WARM is a NEW way to get that wrong, since the process is alive while nothing is running. The strip omits rather than lies.\\n- **C5 reap transparency.** Drive to WARM, reap via `reapSession`, dispatch again: the resulting turn is well formed and indistinguishable from one on a warm process. The person cannot tell.\\n\\nFollow the established driver stance: a case with no driver registers as a NAMED SKIP, never a silent pass. A runtime's `sendMessage` is a pure event producer that moves no projector, so a warmth assertion read off it alone would report the same thing for every runtime and assert nothing.\\n\\nAcceptance criteria:\\n1. C4 and C5 are green for claude-code with the flag on, and SKIP by name for codex, opencode, and test-mode (none of which declares the capability yet).\\n2. C4 is proved able to fail: make the pump report `streaming` while WARM and watch it go red.\\n3. The existing presence cases stay green; the new cases do not weaken or duplicate them.\\n4. `contributing/adding-a-runtime.md` documents `supportsPersistentSession`, `getSessionWarmth`, `reapSession`, and the `warmSession` driver, in the same voice as the existing presence section.\\n5. Ten consecutive turns in one session run on ONE subprocess: assert process identity, not just the absence of an error.\",\n+ \"activeForm\": \"Declaring persistence and adding warmth conformance\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.4\", \"3.5\", \"3.6\", \"3.7\", \"3.8\", \"3.9\"],\n+ \"parallelWith\": [],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"3.11\",\n+ \"phase\": 3,\n+ \"phaseName\": \"P3 — Persistent pump\",\n+ \"subject\": \"[persistent-session-runtime] [P3] Write ADR-b (persistent streaming-input sessions with resume as the recovery path)\",\n+ \"description\": \"Record the process-model decision.\\n\\nWrite the ADR at `decisions/-persistent-streaming-input-sessions.md` using an id from `.claude/scripts/id.ts`, and add its `decisions/manifest.json` entry. Content:\\n- Context: claude-code ran resume-per-message plus held-stream-within-turn. Every turn paid a fresh subprocess, a fresh MCP connection, and a cold prompt cache, and the shape produced a family of fragilities: anchor hacking to stop the CLI's resume classifier injecting a synthetic continue turn, substring-matched resume-failure retries that restart a session as new, and a canonical-id rebind that must move every consumer mid-turn.\\n- Decision: one persistent `query()` per ACTIVE session with WARM as a real state; an idle timer that closes the process; resume DEMOTED to the crash, restart, and cold-start recovery path rather than deleted.\\n- Record the two-timer model explicitly and why they must not be conflated: process idle (WARM to REAPED, 5 minutes) versus session eviction (30 minutes). Eviction implies reap; reap never implies eviction. Reaping is invisible, which is what makes the short window safe.\\n- Record the warm ceiling as a SEPARATE number from the session ceiling, and why: warmth is a cache, so it is LRU-rationed, while session records are not.\\n- Record the relaunch pin list, and name the account pin as a security control rather than an optimization detail.\\n- Rejected alternative: keep resume-per-message and queue only at our layer. It leaves steering impossible and every turn cold, which is most of the motivation.\\n- Non-goal recorded deliberately: the process does NOT survive a DorkOS restart. ADR-0264 already accepts in-flight turn loss on restart and the pump inherits that boundary.\\n- Include the D3 note: the SDK's `priority` field carries no prose documentation even at 0.3.224, so nothing was built on it. 'We measured nothing and therefore relied on nothing' belongs here rather than in an ADR of its own.\\n\\nAcceptance criteria:\\n1. ADR-b exists with a timestamp id, is registered in `decisions/manifest.json`, and follows the repo's ADR shape.\\n2. The two-timer distinction, the warm ceiling rationale, the pin list, and the restart non-goal are all recorded.\\n3. The rejected alternative is stated with its reason.\\n4. A changelog fragment exists for the phase and passes the `fragment-present` gate.\",\n+ \"activeForm\": \"Writing ADR-b\",\n+ \"size\": \"small\",\n+ \"points\": 2,\n+ \"priority\": \"medium\",\n+ \"dependencies\": [\"3.10\"],\n+ \"parallelWith\": [],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"4.1\",\n+ \"phase\": 4,\n+ \"phaseName\": \"P4 — Dispositions native\",\n+ \"subject\": \"[persistent-session-runtime] [P4] Add deliverIntoTurn to AgentRuntime and implement steer for claude-code via streamInput\",\n+ \"description\": \"Give the interface a way to reach a turn that is already running, and implement it.\\n\\nAdd to `packages/shared/src/agent-runtime.ts`:\\n\\n```ts\\nexport type DeliverMode = 'steer' | 'stage';\\n\\nexport interface DeliverIntoTurnOpts {\\n mode: DeliverMode;\\n messageId: string;\\n additionalContext?: AdditionalContext;\\n}\\n\\nexport interface RuntimeDeliveryResult {\\n delivered: boolean;\\n reason?: 'no-open-turn' | 'stream-closed' | 'unsupported';\\n}\\n```\\n\\nand the OPTIONAL method `deliverIntoTurn?(sessionId, content, opts): Promise`.\\n\\nThe TSDoc must state three things, because each one is a trap: (a) it returns a RECEIPT rather than a generator, because the resulting events surface on the already-open turn's stream and a second turn-shaped generator would mean two `feedProjector` calls fighting over one turn; (b) it is called ONLY when the matching capability is declared, and optional on the interface so a runtime that can do neither simply omits it; (c) it MUST NOT throw for an ordinary refusal, because the server's job is to degrade rather than fail the person's message.\\n\\nImplement `mode: 'steer'` for claude-code by pushing the content into the pump's held input stream (the `push` seam from task 3.1), which reaches the CLI's own queue and is delivered within the live turn. Return `{ delivered: false, reason: 'no-open-turn' }` when no window is open and `{ delivered: false, reason: 'stream-closed' }` when the prompt has already closed.\\n\\nContext handling matches a turn's: the server assembles the neutral `additionalContext` bag and the adapter renders it; `content` is passed through pristine and is never mutated.\\n\\nAuthorization: a steer is a WRITE. It must be subject to the same authorization as `sendMessage`; there must be no path where a caller that may not send may steer.\\n\\nAcceptance criteria:\\n1. A steer during an open window reaches the model and influences the turn, with NO second `turn_start` on the durable stream.\\n2. A steer with no open window returns `{ delivered: false, reason: 'no-open-turn' }` and does NOT throw.\\n3. A steer after the pump's stream closed returns `{ delivered: false, reason: 'stream-closed' }`.\\n4. The turn's single `turn_end` still arrives; a steer does not close or duplicate the turn.\\n5. `content` is byte-identical to what the person typed in the transcript; context arrives out of band.\\n6. An unauthorized caller cannot steer a session it could not send to.\",\n+ \"activeForm\": \"Adding deliverIntoTurn and implementing steer\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.3\", \"2.3\"],\n+ \"parallelWith\": [],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"4.2\",\n+ \"phase\": 4,\n+ \"phaseName\": \"P4 — Dispositions native\",\n+ \"subject\": \"[persistent-session-runtime] [P4] Implement stage via shouldQuery:false, plus the fold-into-next fallback\",\n+ \"description\": \"Let a person attach information without provoking a turn.\\n\\nImplement `mode: 'stage'` for claude-code by sending an `SDKUserMessage` with `shouldQuery: false`. The SDK documents this precisely: the message is appended to the transcript WITHOUT triggering an assistant turn, and it is merged into the next user message that does query. That is exactly the semantics wanted, so the native path is a single field rather than any machinery of ours.\\n\\nUnlike steer, stage requires NO open turn: it is legal on a warm or even cold session (a cold one warms first, since the message has to reach the transcript).\\n\\nBuild the fallback for runtimes without the capability: hold the text server-side and fold it into the NEXT dispatched message as an `additionalContext` entry. The `queue_note` kind is the precedent for exactly this shape, and it matters that the fallback rides the neutral context bag rather than being concatenated into `content`: injected context must never render as user-authored text, and the adapter strips its tags on render (ADR-0273).\\n\\nEmit a `context_staged` event so the transcript stays honest. A person who attached a file and saw nothing happen needs some evidence it landed; a silent success is indistinguishable from a dropped message. Add the event to the `SessionEvent` union with a Zod schema AND to the client event allowlist in the same PR.\\n\\nAcceptance criteria:\\n1. A staged message on claude-code provokes NO turn: no `turn_start`, no `turn_end`, no model call, no cost.\\n2. The next dispatched message carries the staged content into the model's context, and the model can act on it.\\n3. A staged message emits `context_staged` on the durable stream and appears as a quiet transcript entry rather than as a user turn.\\n4. The fallback path (capability off) folds the text into the next dispatch as an `additionalContext` entry, and the person's `content` for that next message is unmodified.\\n5. Two staged messages before one dispatch both arrive, in order.\\n6. Staging on a cold session warms it and works, without running a turn.\",\n+ \"activeForm\": \"Implementing stage and its fallback\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"medium\",\n+ \"dependencies\": [\"4.1\"],\n+ \"parallelWith\": [\"4.3\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"4.3\",\n+ \"phase\": 4,\n+ \"phaseName\": \"P4 — Dispositions native\",\n+ \"subject\": \"[persistent-session-runtime] [P4] Add the turn_input event so a steer renders inside the live turn\",\n+ \"description\": \"Make a steer visible where it happened.\\n\\nA steer joins an open turn rather than opening one, so it has nowhere to render today: `turn_start` carries a single `userMessage` and has no slot for a second one. Without a carrier, the person types something, the agent visibly changes course, and the transcript shows no reason why.\\n\\nAdd to the `SessionEvent` union in `packages/shared/src/session-stream.ts`:\\n\\n```ts\\n| { type: 'turn_input'; seq: number; content: string; disposition: 'steer'; messageId: string }\\n```\\n\\nwith a Zod schema beside the neighbouring members, normalization in `session-event-normalizer.ts` so it is ingested into the OPEN turn (never opening or closing one), inclusion in log-backed history reconstruction so a steer survives in the transcript of runtimes that rebuild from the EventLog, and addition to the CLIENT EVENT ALLOWLIST. A new `SessionEvent` member that is not allowlisted is dropped silently; this has bitten before, and a steer that renders in dev and vanishes in prod is exactly that bug.\\n\\nClient rendering: the steer appears inline inside the running turn as a user message, in reading order at the point it arrived, because that is what the person did. It is not a separate turn and must not look like one.\\n\\nAcceptance criteria:\\n1. A steer emits exactly one `turn_input` on the durable stream, ingested into the open turn.\\n2. The turn's `turn_start` and `turn_end` counts are unchanged: one each, no matter how many steers it received.\\n3. Reconnecting mid-turn with `Last-Event-ID` replays the `turn_input` in the right position, gap-free.\\n4. A cold hydrate after the turn completes shows the steer inline in the transcript, in the right place.\\n5. The event is allowlisted: a client-side test asserts a `turn_input` survives the event handling path rather than being dropped.\\n6. Log-backed history reconstruction includes `turn_input` content.\",\n+ \"activeForm\": \"Adding the turn_input event\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"4.1\"],\n+ \"parallelWith\": [\"4.2\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"4.4\",\n+ \"phase\": 4,\n+ \"phaseName\": \"P4 — Dispositions native\",\n+ \"subject\": \"[persistent-session-runtime] [P4] Wire the degradation ladder end to end and declare honest flags on every runtime\",\n+ \"description\": \"Make an unsupported disposition degrade visibly instead of silently.\\n\\nImplement the ladder in the dispatcher (which already has its shape from task 2.3):\\n\\n```\\nsteer -> runtime declares supportsSteer AND a window is open AND no pending interaction\\n -> deliverIntoTurn({ mode: 'steer' })\\n else -> queue\\nstage -> runtime declares supportsContextStaging\\n -> deliverIntoTurn({ mode: 'stage' })\\n else -> hold and fold into the next dispatch as an additionalContext entry\\nqueue -> always available\\n```\\n\\nEvery downgrade emits a `queue_update` carrying the `MessageDeliveryOutcome` with `requested`, `applied`, and `degradedBecause` populated. The ONE case the UI must stay silent about is `degradedBecause: 'session-idle'`: the message ran immediately, which is not a degradation anybody needs told.\\n\\nDeclare the flags honestly:\\n- `claude-code`: `supportsSteer: true`, `supportsContextStaging: true`.\\n- `codex`: both `false`. Its adapter uses the SDK's thread API whose only interrupt primitive is an `AbortSignal`, and whether `@openai/codex-sdk` exposes `turn/steer` at all is UNVERIFIED. Before declaring, run a live probe against a real `codex` binary and record the result in `codex/NOTES.md` alongside the other live-verified facts. If steer turns out to be reachable, that is a follow-up task, not a scope expansion here; declare what you measured.\\n- `opencode`: both `false`. Interrupt is `POST /session/{id}/abort`, and the DOR-82 survey found OpenCode's queue lives in its own TUI rather than its server.\\n- `test-mode`: both `true`, deterministically, because it exists to exercise the contract.\\n\\nAcceptance criteria:\\n1. A steer requested against claude-code with an open window is delivered natively; the outcome shows `requested: 'steer', applied: 'steer'` and no downgrade.\\n2. A steer requested against codex or opencode is queued; the outcome shows `applied: 'queue', degradedBecause: 'unsupported'`.\\n3. A steer requested against an IDLE session runs immediately with `degradedBecause: 'session-idle'`, and the UI stays quiet.\\n4. A steer requested while a pending interaction is open is queued with `degradedBecause: 'pending-interaction'` and does NOT fire into the open ask.\\n5. A stage requested against a runtime without the capability folds into the next dispatch and says so.\\n6. The codex live-probe result is recorded in `codex/NOTES.md` with what was run and what was observed. A declared `false` that was never probed is not acceptable.\",\n+ \"activeForm\": \"Wiring the degradation ladder and honest flags\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"4.1\", \"4.2\"],\n+ \"parallelWith\": [\"4.3\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"4.5\",\n+ \"phase\": 4,\n+ \"phaseName\": \"P4 — Dispositions native\",\n+ \"subject\": \"[persistent-session-runtime] [P4] Extend the conformance suite with the disposition, terminal, queue, and capability cases\",\n+ \"description\": \"Hold every runtime to the contract, because a capability that is not conformance-tested is a capability a runtime can lie about. The suite already proves this discipline works: `validatePresenceReport` exists precisely so a runtime cannot fabricate presence.\\n\\nAdd to `RuntimeConformanceOpts` in `packages/test-utils/src/runtime-conformance.ts`:\\n\\n```ts\\n /**\\n * Drives ONE turn to the point where it is OPEN, calls `midTurn`, then lets it\\n * close. Required for the disposition cases; without it they SKIP by name\\n * rather than passing on a manufactured absence.\\n */\\n dispositionTurn?: (\\n runtime: AgentRuntime,\\n sessionId: string,\\n content: string,\\n probes: { midTurn: () => Promise }\\n ) => Promise;\\n```\\n\\nAdd four cases:\\n- **C1 disposition honesty.** For each of steer and stage: capability declared means the message reaches the model with no new `turn_start`; not declared means `deliverIntoTurn` is absent or returns `{ delivered: false, reason: 'unsupported' }`. Neither branch throws.\\n- **C2 terminal exactly once.** A turn window emits exactly one `turn_end`, however many native `result` messages the backend produced. PROVE IT CAN FAIL: remove task 0.1's idempotence guard, watch C2 go red, restore it, and record that in the PR.\\n- **C3 queue durability.** A message queued behind a turn that FAILS still runs; a message never runs while a pending interaction is open.\\n- **C6 capability completeness.** All three new flags present and boolean. Compile-time forced already, asserted anyway so a cast cannot dodge it.\\n\\nWire the drivers for all four runtimes where they apply, following the established stance: a case with no driver registers as a NAMED SKIP rather than passing on an absence the suite manufactured.\\n\\nUpdate `contributing/adding-a-runtime.md` with the new capability flags, the ladder, `deliverIntoTurn`, and the new cases and drivers, written in the same voice as the existing presence-truthfulness section.\\n\\nAcceptance criteria:\\n1. C1, C2, C3, C6 are green for claude-code, codex, opencode, and test-mode, with skips named where a driver legitimately does not apply.\\n2. C2's defect-seeded proof is documented in the PR description.\\n3. C1 is proved able to fail: declare `supportsSteer: true` on a runtime that cannot steer and watch it go red.\\n4. `contributing/adding-a-runtime.md` documents everything a runtime author must now declare, including the instruction to declare from MEASURED behavior rather than from a capability's name.\\n5. The full suite runtime does not regress noticeably; the new cases reuse existing harnesses rather than booting more.\",\n+ \"activeForm\": \"Extending the conformance suite\",\n+ \"size\": \"large\",\n+ \"points\": 8,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"4.4\"],\n+ \"parallelWith\": [\"4.6\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"4.6\",\n+ \"phase\": 4,\n+ \"phaseName\": \"P4 — Dispositions native\",\n+ \"subject\": \"[persistent-session-runtime] [P4] Build the composer's Queue / Steer / Add context affordances and the downgrade notice\",\n+ \"description\": \"Give the person the three verbs, and never a dead button.\\n\\nIn the composer, the primary action offers Queue (the default) with Steer and Add context beside it. When the session is idle every disposition means 'run it now', so the split action collapses to a plain Send: offering three ways to do the same thing is noise.\\n\\nSteer and Add context are HIDDEN, not disabled, when the resolved runtime does not declare the capability. A hidden affordance is honest; a dead one invites the person to wonder what they did wrong. This follows the repo's existing stance that a runtime with a missing capability adapts the UI rather than showing something that does nothing.\\n\\nThe downgrade notice: when an outcome carries `degradedBecause`, the queue chip says what happened, once, in plain words. 'Queued. Codex can't take messages mid-turn.' Never a code, never a field name. The `session-idle` reason renders NOTHING.\\n\\nA steer renders inline inside the running turn (the `turn_input` event from task 4.3) as a user message at the point it arrived. A staged message renders as a quiet transcript entry, visibly not a turn.\\n\\nKeyboard: Steer and Add context need shortcuts consistent with the existing composer bindings, documented in `docs/guides/keyboard-shortcuts.mdx` and `contributing/keyboard-shortcuts.md`.\\n\\nAll copy follows the `writing-for-humans` standard: plain enough for a smart 9th grader who does not code. Describe what happens for the person, never the mechanism.\\n\\nAcceptance criteria:\\n1. On an idle session the composer shows a plain Send; on a busy session it shows Queue plus the supported extras.\\n2. Against codex or opencode, Steer and Add context are ABSENT, not greyed out.\\n3. A steer renders inline inside the live turn, in reading order.\\n4. A downgraded steer shows its notice once on the chip, in plain words, and the `session-idle` case shows nothing at all.\\n5. The dev playground carries a showcase for the new composer states (idle, busy-with-steer, busy-without-steer, downgraded chip).\\n6. Every changed component's full test set runs, including the tests of parents that mount it, not just the component's own suite.\\n7. Keyboard shortcuts are documented in both the user guide and the contributing guide.\",\n+ \"activeForm\": \"Building the composer disposition affordances\",\n+ \"size\": \"large\",\n+ \"points\": 8,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"4.3\", \"4.4\", \"2.6\"],\n+ \"parallelWith\": [\"4.5\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"4.7\",\n+ \"phase\": 4,\n+ \"phaseName\": \"P4 — Dispositions native\",\n+ \"subject\": \"[persistent-session-runtime] [P4] Make Stop clear the queue and hand the messages back\",\n+ \"description\": \"Make Stop mean what a person thinks it means, without destroying anything they typed.\\n\\nToday `POST /api/sessions/:id/interrupt` calls `runtime.interruptQuery` and answers `{ ok }` best effort. With a queue, a person who presses Stop and then watches the next queued message fire has been lied to.\\n\\nDecision: Stop means stop everything queued. The SDK's own documentation names this exact case, describing `cancel_queued: true` as what a remote UI's Stop button sets so one round trip halts the session.\\n\\nImplement:\\n1. Stop clears the DorkOS queue for the session, and `clear` RETURNS the removed rows (task 2.2 built it that way for this reason).\\n2. The cleared messages go back to the person: they land in the composer's draft area, the same promise `restore` makes today. Nothing typed is destroyed by a stop. This is the whole point of the task.\\n3. Pass `cancel_queued: true` to the runtime where the capability is advertised. Feature-detect it from `interrupt_cancel_queued_v1` in the `system/init` capabilities array; never version-sniff. A CLI that does not advertise it gets the documented older behavior, where queued commands SURVIVE the interrupt, and the person is told that honestly rather than being promised a stop that did not happen.\\n4. The confirmation names the cost before it happens: 'Stop, and put 3 queued messages back?' A confirmation that hides the consequence is not a confirmation.\\n5. Emit `queue_update` with the now-empty queue so every window agrees.\\n\\nHonest reporting of exactly what was cancelled depends on the interrupt receipt, which is owned by the `runtime-interrupt-receipts` spec. Until that lands, the client says 'stop requested' rather than 'stopped'. Consume that spec's typed result when it exists; do NOT redefine it here.\\n\\nAcceptance criteria:\\n1. Stop with three messages queued clears all three and returns their text to the composer, in order, and nothing is lost.\\n2. Stop with an empty queue behaves exactly as today, with no confirmation dialog for a queue that does not exist.\\n3. The confirmation names the message count.\\n4. Every window sees the queue empty via `queue_update`.\\n5. Against a CLI that does not advertise `interrupt_cancel_queued_v1`, the DorkOS queue is still cleared and the client does not claim more than happened.\\n6. Stop mid-turn still ends the turn; the queue behavior is additive and does not regress the existing interrupt path.\",\n+ \"activeForm\": \"Making Stop clear the queue\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"4.6\"],\n+ \"parallelWith\": [],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"4.8\",\n+ \"phase\": 4,\n+ \"phaseName\": \"P4 — Dispositions native\",\n+ \"subject\": \"[persistent-session-runtime] [P4] Write ADR-a (three message dispositions at the AgentRuntime boundary)\",\n+ \"description\": \"Record the contract decision.\\n\\nWrite the ADR at `decisions/-message-dispositions-at-the-runtime-boundary.md` using an id from `.claude/scripts/id.ts`, and add its `decisions/manifest.json` entry. Content:\\n- Context: `sendMessage` was the only ingress and `interruptQuery` the only mid-turn control. There was no way to accept a message mid-turn, no disposition, no steer. Concurrency was refused crudely at HTTP with a 409, and all queueing intelligence lived in the browser as ephemeral state. The industry has converged on queue, interrupt, and steer as distinct verbs (Codex models `turn/steer` separately from `turn/interrupt`; Amp uses a `{steer: true}` envelope flag beside a separate interrupt).\\n- Decision: three dispositions (queue, steer, stage) expressed ONCE at the server ingress as an envelope field, resolved by the server against declared capabilities, with interrupt remaining a separate verb because it carries no content and can be issued with nothing to send after it.\\n- Record the refinement that drafting forced, and why it is not a departure: a steer cannot ride `sendMessage`'s return type, because that returns an `AsyncGenerator` which the projector feed consumes as exactly one turn, and a steer's events belong to a turn another feed is already consuming. So the envelope stays single at the ingress and the runtime interface grows ONE OPTIONAL method, `deliverIntoTurn`, returning a receipt.\\n- Record the three capability flags and why there is deliberately no `supportsQueue`: the server always owns the queue, so every runtime supports queueing by construction.\\n- Record the degradation ladder and the rule that every downgrade is REPORTED. Silent degradation is the failure this design exists to prevent.\\n- Rejected alternative: three explicit required runtime verbs (`enqueueMessage` / `steer(turnId, content)` / `interrupt`). More surface for every future runtime author to implement, and it makes the common case (queue, which no adapter implements at all) look like adapter work.\\n- Rejected alternative: relying on the SDK's `priority: 'now' | 'next' | 'later'`. The field still carries no prose documentation at 0.3.224, so its scheduling is inferred from three words. Steering rides `streamInput`, whose behavior IS documented.\\n\\nAcceptance criteria:\\n1. ADR-a exists with a timestamp id, is registered in `decisions/manifest.json`, and follows the repo's ADR shape.\\n2. Both rejected alternatives are recorded with their reasons.\\n3. The `deliverIntoTurn` refinement is recorded as a consequence of the type system, not presented as a change of mind.\\n4. A changelog fragment exists for the phase and passes the `fragment-present` gate.\",\n+ \"activeForm\": \"Writing ADR-a\",\n+ \"size\": \"small\",\n+ \"points\": 2,\n+ \"priority\": \"medium\",\n+ \"dependencies\": [\"4.5\", \"4.7\"],\n+ \"parallelWith\": [],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"5.1\",\n+ \"phase\": 5,\n+ \"phaseName\": \"P5 — Default on, measure, clean up\",\n+ \"subject\": \"[persistent-session-runtime] [P5] Run the flag-off versus flag-on measurement pass\",\n+ \"description\": \"Produce the numbers that decide whether the default flips. The performance claim is the JUSTIFICATION for this whole programme, so it must be measured rather than asserted. Neither the ideation nor the spec made a performance claim; both marked the estimates unverified deliberately, and this task is where that debt is paid.\\n\\nRun the same workload twice on one host, once with `runtimes.claudeCode.persistentSession` off and once on. A representative workload means a multi-turn session with tool use and at least one subagent, not a single hello-world turn.\\n\\nMeasure:\\n\\n| Metric | Source |\\n| --- | --- |\\n| Time to first token, turn 2 and later | the `SESSION_TURN` span, already instrumented at the trigger seam |\\n| Cache-read token ratio | `cacheReadTokens` on the `session_status` the result mapper emits |\\n| Resident subprocess count | process sampling during a 20-session soak |\\n| Phantom-cancellation rate | the DOR-1087 tripwire counter from task 5.2 |\\n\\nExpectations to confirm or refute honestly: TTFT materially lower from turn 2 (no spawn, no MCP reconnect), cache-read ratio materially higher, subprocess count bounded by `MAX_WARM_SESSIONS`, phantom rate zero. A refuted expectation is a finding, not a failure to hide: report it and let it re-open the design.\\n\\nAlso watch for LRU thrash: reap-then-immediately-rewarm frequency. If it is high, the remedy is raising the warm ceiling, NOT lengthening the idle timer, because a longer idle timer holds more processes for longer without improving the hit rate for the sessions actually in use.\\n\\nAcceptance criteria:\\n1. All four metrics captured on both configurations, on the same workload and host, with the method written down so it can be repeated.\\n2. Numbers recorded on the work item, not just in a PR description.\\n3. Subprocess count under a 20-session soak stays bounded by `MAX_WARM_SESSIONS`.\\n4. Reap-then-rewarm frequency reported with a recommendation on the ceiling.\\n5. If any expectation is refuted, the finding is written up plainly and the phase does not proceed to 5.3 until it is resolved.\",\n+ \"activeForm\": \"Running the measurement pass\",\n+ \"size\": \"medium\",\n+ \"points\": 5,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"4.7\"],\n+ \"parallelWith\": [\"5.2\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"5.2\",\n+ \"phase\": 5,\n+ \"phaseName\": \"P5 — Default on, measure, clean up\",\n+ \"subject\": \"[persistent-session-runtime] [P5] Keep the DOR-1087 phantom detector as an instrumented regression tripwire\",\n+ \"description\": \"Keep the phantom-cancellation detector alive as a tripwire, and make it count.\\n\\nDOR-1087's detector recognizes the CLI's interrupt sentinel written as a tool_result when the CLI cancels a pending tool call itself, and distinguishes it from a real refusal: a UI deny carries its own wording and an operator stop goes through `interruptQuery`, so a sentinel matching neither is the CLI talking to itself. Observed on 2026-08-09: eight phantoms in one session, zero real denies.\\n\\nThe HYPOTHESIS is that persistence removes this class entirely, because DorkOS stops racing the CLI's internal queue: with a persistent stream, DorkOS controls when messages enter it and holds dispatch until the turn window closes. That hypothesis is UNVERIFIED and must not be assumed. A detector that never fires is cheap; a silently returned phantom is expensive and would be invisible without one.\\n\\nWhat to build:\\n1. Keep the detector on the persistent path, not just the resume path.\\n2. Add a counter and a structured warning log so the rate is measurable rather than anecdotal, and feed it to task 5.1's measurement.\\n3. Add a unit test that seeds a synthetic phantom (a sentinel tool_result with no matching operator deny and no recent `interruptQuery`) and asserts the tripwire fires. A tripwire nobody has watched fire is not a tripwire.\\n4. Keep the corrective-steering behavior only if it is still reachable; on the persistent path the correction may be unnecessary. Whichever way, make the choice explicit in the code comment rather than leaving dead machinery.\\n\\nAcceptance criteria:\\n1. The detector runs on the persistent path.\\n2. A synthetic phantom fires the tripwire; the seeded test proves it can fire.\\n3. A REAL operator deny does NOT fire it; a real operator stop within the suppression window does NOT fire it. Both are tested, because a tripwire that cries wolf gets ignored and then it is not a tripwire either.\\n4. The counter is queryable for the measurement pass.\\n5. No behavior change on the resume path.\",\n+ \"activeForm\": \"Instrumenting the phantom tripwire\",\n+ \"size\": \"small\",\n+ \"points\": 3,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"3.3\"],\n+ \"parallelWith\": [\"5.1\", \"4.5\"],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"5.3\",\n+ \"phase\": 5,\n+ \"phaseName\": \"P5 — Default on, measure, clean up\",\n+ \"subject\": \"[persistent-session-runtime] [P5] Flip the persistent-session default on and write the user-facing docs\",\n+ \"description\": \"Make the persistent path the default, once the numbers say it should be.\\n\\nGATED on task 5.1's measurement supporting the change and on task 5.2's tripwire reporting zero phantoms over the observation window. If either fails, this task does not run and the design is re-opened. That gate is the point of the phase; flipping the default on schedule rather than on evidence would waste the measurement.\\n\\nWhat to do:\\n1. Change the config default for `runtimes.claudeCode.persistentSession` to `true`. Because the field already shipped at `false`, this needs a NEW semver-keyed migration key strictly greater than the newest release tag, not an edit to the existing one: `conf` runs a key only in `(storedVersion, projectVersion]`, so extending a shipped key never runs for anybody already on it.\\n2. Respect an explicit user choice. Somebody who deliberately set it `false` keeps `false`; the migration backfills only the unset case.\\n3. Write the changelog fragment and the user-facing docs per the `writing-for-humans` standard: what happens for the person, never the mechanism. 'Agents now stay warm between messages, so replies start faster', plus the queue, steer, and add-context verbs, plus what Stop does to queued messages.\\n4. Update `contributing/architecture.md` with the pump and the server queue in the hexagonal picture.\\n\\nAcceptance criteria:\\n1. A fresh install gets the persistent path.\\n2. An existing install with no explicit setting is migrated to on; an install with an explicit `false` stays off.\\n3. The migration is keyed above the newest release tag and the migration-safety guard is green.\\n4. The changelog fragment passes the `fragment-present` gate and reads plainly, with no hype and no internals.\\n5. User docs cover queue, steer, add context, and Stop's effect on the queue.\\n6. `contributing/architecture.md` shows the pump and the queue.\",\n+ \"activeForm\": \"Flipping the default and writing the docs\",\n+ \"size\": \"small\",\n+ \"points\": 3,\n+ \"priority\": \"high\",\n+ \"dependencies\": [\"5.1\", \"5.2\"],\n+ \"parallelWith\": [],\n+ \"issue\": null\n+ },\n+ {\n+ \"id\": \"5.4\",\n+ \"phase\": 5,\n+ \"phaseName\": \"P5 — Default on, measure, clean up\",\n+ \"subject\": \"[persistent-session-runtime] [P5] After a quiet period, remove the phantom detector and the retired resume machinery from the hot path\",\n+ \"description\": \"Delete what the new design made unnecessary, on evidence rather than on assumption.\\n\\nThis is deliberately a SCHEDULED task and not a step inside another one. The temptation is to delete the phantom detector at cutover, on the reasoning that persistence should have removed the class. That reasoning is exactly the kind that survives unexamined, and a silently returned phantom is invisible without the detector.\\n\\nGATE: the tripwire from task 5.2 must record ZERO phantoms across a real observation window on the default-on build, including at least one multi-subagent session of the kind that produced eight phantoms in one sitting on 2026-08-09. If it fires even once, this task does not run, the finding is written up, and the design is re-opened.\\n\\nOnce the gate passes:\\n1. Remove `messaging/phantom-cancellation.ts` and its tests, and the session fields that exist only for it (`operatorDeniedToolIds`, `interruptRequestedAt`) if nothing else reads them. Verify with `pnpm knip` after building dists, and verify-before-remove rather than trusting the report.\\n2. Audit the resume-path machinery and confirm it is still reachable ONLY from the recovery route. `resumeSessionAt` anchoring and the `isResumeFailure` retry are RETAINED deliberately: they are what the crash and cold-start path needs. What must go is any hot-path caller left behind. Do not delete them wholesale; a comment explaining why they survive is worth more than their removal.\\n3. Leave a note in ADR-b recording that the phantom class was closed and how it was confirmed, so the next person does not re-derive the question.\\n\\nAcceptance criteria:\\n1. The quiet-period evidence is recorded on the work item: what was run, for how long, with what result.\\n2. Zero phantoms over the window, or this task does not complete.\\n3. Knip reports no orphaned code after removal, and every removal was verified rather than trusted.\\n4. Resume machinery is still reachable from the recovery path, with a test proving a crashed session recovers through it.\\n5. ADR-b carries the confirmation note.\\n6. `pnpm verify` is green.\",\n+ \"activeForm\": \"Removing the phantom detector after the quiet period\",\n+ \"size\": \"small\",\n+ \"points\": 2,\n+ \"priority\": \"low\",\n+ \"dependencies\": [\"5.3\"],\n+ \"parallelWith\": [],\n+ \"issue\": null\n+ }\n+ ]\n+}", "status": "added"}, {"additions": 8, "deletions": 0, "filename": "specs/persistent-session-runtime/manifest.json", "patch": "@@ -0,0 +1,8 @@\n+{\n+ \"id\": \"260810-003853\",\n+ \"slug\": \"persistent-session-runtime\",\n+ \"title\": \"Persistent session runtime, and the queue / steer / interrupt contract\",\n+ \"created\": \"2026-08-09\",\n+ \"status\": \"specified\",\n+ \"linearIssue\": \"DOR-1089\"\n+}", "status": "added"}], "message": "docs(specs): persistent-session runtime programme — ideation, frozen spec, 32-task decomposition (DOR-1089)\n\nIDEATE + SPECIFY + DECOMPOSE artifacts for moving the claude-code runtime\nfrom resume-per-message to persistent streaming-input sessions, with the\nqueue / steer / interrupt disposition contract at the AgentRuntime boundary.\nBuilds on research/20260610_message_queuing_agent_runtimes.md (DOR-82).\n\nCo-Authored-By: Claude Fable 5 ", "sha": "e1daf4bb10274709bddd07481f725d4f6532e8fd"}], "post_review_commits": ["693dfd783f7bec2c6a6f964b6cea1e6cdc5d7472", "981eaa6abdf8873656a848547b0bec5982924417"], "pr_author": "doriancollier", "pr_title": "docs(specs): persistent-session runtime programme spec (DOR-1089)", "repo_name": "dork-labs/dorkos"}, "repo": "dork-labs/dorkos", "snapshot": "snapshots/51bbfc099e0f38160ef7f6f8ccd7ad03d8f577fa1a465a9f076a14e839b249d7.pack", "split": "rl", "task_id": "0522f303bf1305a7acecb81eeda9aead9d140bab8dab0a9c26bf5890b0ff6ddd"} {"base_sha": "5a258c12d422fffcc70a02374a481dc030267b7b", "cohort": null, "context": {"canonical_pr_url": "https://github.com/wcpos/mollie-terminal-for-woocommerce/pull/16", "id": "0558c6cf315cfc15029a8e2da216a64268bda52aa0e3d8e3cd1ca99765cbc699", "preparation_mode": "source-only", "snapshot": {"base_ref": "5a258c12d422fffcc70a02374a481dc030267b7b", "base_sha": "5a258c12d422fffcc70a02374a481dc030267b7b", "body": "", "head_ref": "eae81b00a7f0995da3e821d643f8e3f95767c983", "head_sha": "eae81b00a7f0995da3e821d643f8e3f95767c983", "name": "mollie-terminal-for-woocommerce", "number": 16, "owner": "wcpos", "pr_url": "https://github.com/wcpos/mollie-terminal-for-woocommerce/pull/16", "title": ""}}, "head_sha": "eae81b00a7f0995da3e821d643f8e3f95767c983", "metadata": {"group_id": "7e1f4fb0f03f5133266c29b10b9bddbbe9bf14047bfbc9d15fa84d9cc2b90a1a", "snapshot": {"base_sha": "5a258c12d422fffcc70a02374a481dc030267b7b", "external_requirements": [], "head_sha": "eae81b00a7f0995da3e821d643f8e3f95767c983", "objects": 105, "objects_sha256": "115e36c5043dc9cd4f5be08f2c3f6f25a304ff399851bae615e8468b00d5d95f", "patch_sha256": "29c5d3bc446582cd02424ab2c0970f3c1288f7fe66109d450b3859763471acc8"}}, "pr_number": 16, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "34e9ea5e16ad", "description": "POS enablement lookup relied solely on the deprecated woocommerce_pos_get_settings() alias. When only the maintained wcpos_get_settings() helper was available, POS-only gateway requests were incorrectly treated as disabled.", "file_path": "includes/Settings.php"}, {"action_id": "A2", "action_type": "improvement", "category": "other", "commit_sha": "34e9ea5e16ad", "description": "The AJAX gateway regression fixture stubbed only the deprecated POS settings helper, so it did not test the maintained-helper path used by current WCPOS installations.", "file_path": "tests/regression/ajax-gateway-disabled.php"}], "commits_under_review": [{"author": "kilbot", "date": "2026-09-05T10:54:22Z", "files": [{"additions": 7, "deletions": 0, "filename": "CHANGELOG.md", "patch": "@@ -2,6 +2,13 @@\n \n All notable changes to Mollie Terminal for WooCommerce will be documented in this file.\n \n+## 0.5.3 - 2026-09-05\n+\n+### Fixed\n+\n+- **POS payments were refused when the WooCommerce → Payments checkbox was off.** The 0.5.1 guard treated that checkbox as the only gateway switch, but WooCommerce POS enables gateways from POS → Settings → Checkout and ignores the WooCommerce one, so every POS-only setup (the recommended configuration) got \"Mollie Terminal is disabled.\" when starting a payment or listing terminals. The guard now honours either switch: a gateway enabled in WooCommerce or in WooCommerce POS can take payments; one switched off in both places is still refused.\n+- The Enable/Disable checkbox is relabelled \"Enable Mollie Terminal for web checkout (not necessary for WooCommerce POS)\" with a description explaining where the POS switch lives, matching the other WCPOS terminal plugins. The old \"for checkout/POS\" label implied the POS needed it.\n+\n ## 0.5.2 - 2026-09-03\n \n ### Fixed", "status": "modified"}, {"additions": 12, "deletions": 0, "filename": "docs/releases/0.5.3.md", "patch": "@@ -0,0 +1,12 @@\n+# Mollie Terminal for WooCommerce 0.5.3\n+\n+Fixes a regression introduced in 0.5.1 that locked POS-only shops out of taking payments, and corrects the settings label that suggested the POS needed the WooCommerce checkbox.\n+\n+## Fixed\n+\n+- **POS payments were refused when the WooCommerce → Payments checkbox was off.** The 0.5.1 guard treated that checkbox as the only gateway switch, but WooCommerce POS enables gateways from POS → Settings → Checkout and ignores the WooCommerce one. Every POS-only setup, which is the recommended configuration, got \"Mollie Terminal is disabled.\" when starting a payment or listing terminals. The guard now honours either switch: a gateway enabled in WooCommerce or in WooCommerce POS can take payments, and one switched off in both places is still refused.\n+- **Settings label corrected.** The Enable/Disable checkbox now reads \"Enable Mollie Terminal for web checkout (not necessary for WooCommerce POS)\", with a description explaining that the POS switch lives under POS → Settings → Checkout. This matches the other WCPOS terminal plugins.\n+\n+## Upgrade\n+\n+No configuration changes are required. If you ticked the WooCommerce checkbox as a workaround and do not sell online, you can untick it again; the POS keeps working from its own setting.", "status": "added"}, {"additions": 8, "deletions": 4, "filename": "includes/AjaxHandler.php", "patch": "@@ -151,15 +151,19 @@ private function can_access_order( int $order_id ): bool {\n \t}\n \n \t/**\n-\t * \"Disabled\" in WooCommerce → Payments must mean disabled: the checkout\n-\t * actions stay registered while the plugin is active, so starting a\n-\t * payment and listing terminals check the gateway switch themselves.\n+\t * A gateway switched off everywhere must stay off: the checkout actions\n+\t * stay registered while the plugin is active, so starting a payment and\n+\t * listing terminals check the switches themselves. There are two: the\n+\t * WooCommerce → Payments checkbox (online store) and POS → Settings →\n+\t * Checkout (WooCommerce POS), and either one counts — POS merchants\n+\t * routinely leave the WooCommerce one off (the 0.5.1 guard only looked at\n+\t * that one and locked every such POS out of taking payments).\n \t * Poll and cancel are deliberately not gated (nor is the webhook): a\n \t * payment already in flight must still settle, and the cashier must keep\n \t * the ability to cancel it, even if the gateway was switched off meanwhile.\n \t */\n \tprivate function require_gateway_enabled(): void {\n-\t\tif ( ! $this->settings()->enabled() ) {\n+\t\tif ( ! $this->settings()->active() ) {\n \t\t\twp_send_json_error( __( 'Mollie Terminal is disabled.', 'mollie-terminal-for-woocommerce' ), 403 );\n \t\t}\n \t}", "status": "modified"}, {"additions": 14, "deletions": 1, "filename": "includes/Gateway.php", "patch": "@@ -26,7 +26,20 @@ public static function register_gateway( array $methods ): array { $methods[] =\n \n \tpublic function init_form_fields(): void {\n \t\t$this->form_fields = array(\n-\t\t\t'enabled' => array( 'title' => __( 'Enable/Disable', 'mollie-terminal-for-woocommerce' ), 'type' => 'checkbox', 'label' => __( 'Enable Mollie Terminal for checkout/POS.', 'mollie-terminal-for-woocommerce' ), 'default' => 'no' ),\n+\t\t\t'enabled' => array(\n+\t\t\t\t'title' => __( 'Enable/Disable', 'mollie-terminal-for-woocommerce' ),\n+\t\t\t\t'type' => 'checkbox',\n+\t\t\t\t// This switch governs the online store only. WooCommerce POS enables\n+\t\t\t\t// the gateway from POS → Settings → Checkout, whether or not it is\n+\t\t\t\t// enabled here; a bare \"for checkout/POS\" implied the POS needed it.\n+\t\t\t\t'label' => sprintf(\n+\t\t\t\t\t/* translators: %s: link to WooCommerce POS. */\n+\t\t\t\t\t__( 'Enable Mollie Terminal for web checkout (not necessary for %s)', 'mollie-terminal-for-woocommerce' ),\n+\t\t\t\t\t'WooCommerce POS'\n+\t\t\t\t),\n+\t\t\t\t'description' => __( 'This enables the gateway for online store checkout. WooCommerce POS uses this gateway once it is enabled under POS → Settings → Checkout, whether or not it is enabled here.', 'mollie-terminal-for-woocommerce' ),\n+\t\t\t\t'default' => 'no',\n+\t\t\t),\n \t\t\t'title' => array( 'title' => __( 'Title', 'mollie-terminal-for-woocommerce' ), 'type' => 'text', 'default' => __( 'Mollie Terminal', 'mollie-terminal-for-woocommerce' ) ),\n \t\t\t'description' => array( 'title' => __( 'Description', 'mollie-terminal-for-woocommerce' ), 'type' => 'textarea', 'default' => __( 'Pay in person using Mollie Terminal.', 'mollie-terminal-for-woocommerce' ) ),\n \t\t\t'mode' => array( 'title' => __( 'Mode', 'mollie-terminal-for-woocommerce' ), 'type' => 'select', 'default' => 'test', 'options' => array( 'test' => __( 'Test', 'mollie-terminal-for-woocommerce' ), 'live' => __( 'Live', 'mollie-terminal-for-woocommerce' ) ) ),", "status": "modified"}, {"additions": 16, "deletions": 1, "filename": "includes/Settings.php", "patch": "@@ -40,8 +40,23 @@ private function mollie_plugin_api_key(): string {\n \t\treturn trim( (string) get_option( $option, '' ) );\n \t}\n \n-\t/** Whether the merchant has the gateway switched on in WooCommerce → Payments. */\n+\t/** Whether the merchant has the gateway switched on in WooCommerce → Payments (online store only). */\n \tpublic function enabled(): bool { return 'yes' === $this->get( 'enabled', 'no' ); }\n+\n+\t/**\n+\t * Whether WooCommerce POS has this gateway switched on under\n+\t * POS → Settings → Checkout. WooCommerce POS forces a gateway enabled from its\n+\t * own settings and ignores the WooCommerce → Payments switch, so merchants\n+\t * routinely leave that switch off for a POS-only terminal.\n+\t */\n+\tpublic function enabled_for_pos(): bool {\n+\t\tif ( ! function_exists( 'woocommerce_pos_get_settings' ) ) { return false; }\n+\t\t$settings = woocommerce_pos_get_settings( 'payment_gateways' );\n+\t\treturn is_array( $settings ) && ! empty( $settings['gateways'][ self::GATEWAY_ID ]['enabled'] );\n+\t}\n+\n+\t/** Whether the gateway is switched on anywhere: online store or WooCommerce POS. */\n+\tpublic function active(): bool { return $this->enabled() || $this->enabled_for_pos(); }\n \tpublic function api_key_source(): string { return 'mollie' === $this->get( 'api_key_source', 'own' ) ? 'mollie' : 'own'; }\n \tpublic function profile_id(): string { return (string) $this->get( 'profile_id', '' ); }\n \tpublic function mode(): string { return 'live' === $this->get( 'mode', 'test' ) ? 'live' : 'test'; }", "status": "modified"}, {"additions": 0, "deletions": 0, "filename": "languages/mollie-terminal-for-woocommerce-nl_NL.mo", "patch": null, "status": "modified"}, {"additions": 7, "deletions": 2, "filename": "languages/mollie-terminal-for-woocommerce-nl_NL.po", "patch": "@@ -61,9 +61,14 @@ msgstr \"Standaardterminal\"\n msgid \"Description\"\n msgstr \"Omschrijving\"\n \n+#. translators: %s: link to WooCommerce POS.\n #: includes/Gateway.php:29\n-msgid \"Enable Mollie Terminal for checkout/POS.\"\n-msgstr \"Mollie Terminal inschakelen voor afrekenen/kassa.\"\n+msgid \"Enable Mollie Terminal for web checkout (not necessary for %s)\"\n+msgstr \"Mollie Terminal inschakelen voor de webshop (niet nodig voor %s)\"\n+\n+#: includes/Gateway.php:29\n+msgid \"This enables the gateway for online store checkout. WooCommerce POS uses this gateway once it is enabled under POS → Settings → Checkout, whether or not it is enabled here.\"\n+msgstr \"Hiermee schakel je de gateway in voor de webshop. WooCommerce POS gebruikt deze gateway zodra hij is ingeschakeld onder POS → Instellingen → Afrekenen, ongeacht of hij hier is ingeschakeld.\"\n \n #: includes/Gateway.php:29\n msgid \"Enable/Disable\"", "status": "modified"}, {"additions": 7, "deletions": 2, "filename": "languages/mollie-terminal-for-woocommerce.pot", "patch": "@@ -2,7 +2,7 @@\n # This file is distributed under the GPL v3 or later.\n msgid \"\"\n msgstr \"\"\n-\"Project-Id-Version: Mollie Terminal for WooCommerce 0.5.0\\n\"\n+\"Project-Id-Version: Mollie Terminal for WooCommerce 0.5.3\\n\"\n \"Report-Msgid-Bugs-To: https://github.com/wcpos/mollie-terminal-for-woocommerce/issues\\n\"\n \"MIME-Version: 1.0\\n\"\n \"Content-Type: text/plain; charset=UTF-8\\n\"\n@@ -57,8 +57,13 @@ msgstr \"\"\n msgid \"Description\"\n msgstr \"\"\n \n+#. translators: %s: link to WooCommerce POS.\n #: includes/Gateway.php:29\n-msgid \"Enable Mollie Terminal for checkout/POS.\"\n+msgid \"Enable Mollie Terminal for web checkout (not necessary for %s)\"\n+msgstr \"\"\n+\n+#: includes/Gateway.php:29\n+msgid \"This enables the gateway for online store checkout. WooCommerce POS uses this gateway once it is enabled under POS → Settings → Checkout, whether or not it is enabled here.\"\n msgstr \"\"\n \n #: includes/Gateway.php:29", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "mollie-terminal-for-woocommerce.php", "patch": "@@ -2,7 +2,7 @@\n /**\n * Plugin Name: Mollie Terminal for WooCommerce\n * Description: Adds Mollie Terminal support to WooCommerce for in-person payments.\n- * Version: 0.5.2\n+ * Version: 0.5.3\n * Author: kilbot\n * Author URI: https://kilbot.com/\n * Update URI: https://github.com/wcpos/mollie-terminal-for-woocommerce\n@@ -19,7 +19,7 @@\n \texit;\n }\n \n-define( 'MTFWC_VERSION', '0.5.2' );\n+define( 'MTFWC_VERSION', '0.5.3' );\n define( 'MTFWC_PLUGIN_FILE', __FILE__ );\n define( 'MTFWC_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );\n define( 'MTFWC_PLUGIN_URL', plugin_dir_url( __FILE__ ) );", "status": "modified"}, {"additions": 24, "deletions": 0, "filename": "tests/regression/ajax-gateway-disabled.php", "patch": "@@ -6,6 +6,11 @@ function expect( $condition, $message = 'expectation failed' ) { if ( ! $conditi\n \n $options = array();\n function get_option( $key, $default = false ) { global $options; return array_key_exists( $key, $options ) ? $options[ $key ] : $default; }\n+\n+// WooCommerce POS → Settings → Checkout stub. POS forces a gateway enabled from\n+// this blob and ignores the WooCommerce → Payments checkbox entirely.\n+$pos_settings = array();\n+function woocommerce_pos_get_settings( $id, $key = null ) { global $pos_settings; return $pos_settings; }\n function absint( $value ) { return abs( (int) $value ); }\n function sanitize_text_field( $value ) { return (string) $value; }\n function wp_unslash( $value ) { return $value; }\n@@ -92,6 +97,25 @@ function call_action( string $action, array $settings, array $post = array() ):\n // gateway's own default.\n expect( 403 === call_action( 'mtfwc_start_payment', array() )->status, 'an unsaved gateway must be treated as disabled' );\n \n+// The WooCommerce → Payments checkbox governs the online store only. A POS-only\n+// merchant leaves it off and enables the gateway under POS → Settings →\n+// Checkout instead, so that switch alone must let payments start and\n+// terminals list (the 0.5.1 guard ignored it and locked those shops out).\n+$pos_settings = array( 'default_gateway' => 'pos_cash', 'gateways' => array( 'mollie_terminal_for_woocommerce' => array( 'enabled' => true, 'order' => 2 ) ) );\n+$pos_only = call_action( 'mtfwc_start_payment', $disabled, array( 'channel' => 'qr', 'qr_method' => 'bancontact' ) );\n+expect( 400 === $pos_only->status, 'the POS switch alone must let start_payment past the gateway guard' );\n+expect( 'Mollie Terminal is disabled.' !== $pos_only->data, 'start_payment must not report the gateway as disabled when POS has it on' );\n+$pos_only_list = call_action( 'mtfwc_list_terminals', array() );\n+expect( 'Mollie Terminal is disabled.' !== $pos_only_list->data, 'the POS switch alone must let list_terminals past the gateway guard' );\n+\n+// POS lists the gateway but has it switched off: that is not enabled.\n+$pos_settings['gateways']['mollie_terminal_for_woocommerce']['enabled'] = false;\n+expect( 403 === call_action( 'mtfwc_start_payment', $disabled )->status, 'a gateway switched off in both places must be refused' );\n+// Unknown-section errors from WooCommerce POS (e.g. WP_Error) never count as enabled.\n+$pos_settings = 'not-an-array';\n+expect( 403 === call_action( 'mtfwc_start_payment', $disabled )->status, 'a non-array POS settings result must not enable the gateway' );\n+$pos_settings = array();\n+\n // With the gateway enabled the request proceeds past the guard: the QR method\n // check is the next gate, so a disabled QR method now yields 400, not 403.\n $enabled = call_action( 'mtfwc_start_payment', array( 'enabled' => 'yes' ), array( 'channel' => 'qr', 'qr_method' => 'ideal' ) );", "status": "modified"}], "message": "fix: honour the POS gateway switch in the AJAX guard and relabel the enable checkbox (v0.5.3)\n\nThe 0.5.1 guard refused start_payment and list_terminals whenever the\nWooCommerce → Payments checkbox was off. WooCommerce POS enables gateways\nfrom POS → Settings → Checkout and ignores that checkbox, so every POS-only\nsetup was locked out of taking payments. The guard now accepts either switch.\n\nThe checkbox is relabelled to match the other WCPOS terminal plugins: it\ngoverns web checkout only and is not necessary for WooCommerce POS.", "sha": "eae81b00a7f0995da3e821d643f8e3f95767c983"}], "post_review_commits": ["34e9ea5e16ad497808aa4fb44fdad1e7a0b99d5e"], "pr_author": "kilbot", "pr_title": "fix: honour the POS gateway switch in the AJAX guard and relabel the enable checkbox (v0.5.3)", "repo_name": "wcpos/mollie-terminal-for-woocommerce"}, "repo": "wcpos/mollie-terminal-for-woocommerce", "snapshot": "snapshots/7e1f4fb0f03f5133266c29b10b9bddbbe9bf14047bfbc9d15fa84d9cc2b90a1a.pack", "split": "rl", "task_id": "0558c6cf315cfc15029a8e2da216a64268bda52aa0e3d8e3cd1ca99765cbc699"} {"base_sha": "7afdf5bc5ca36bb17a999dba53ef84fc49c9b13e", "cohort": null, "context": {"canonical_pr_url": "https://github.com/basnijholt/adaptive-lighting/pull/1489", "id": "08f3246256fd4175c2ff0bdf2c65c0cae73a015b82ad77a16e7b88a9ad5908bc", "preparation_mode": "source-only", "snapshot": {"base_ref": "7afdf5bc5ca36bb17a999dba53ef84fc49c9b13e", "base_sha": "7afdf5bc5ca36bb17a999dba53ef84fc49c9b13e", "body": "", "head_ref": "b6f340a43d7bde47b86b633d697abb0b295c3634", "head_sha": "b6f340a43d7bde47b86b633d697abb0b295c3634", "name": "adaptive-lighting", "number": 1489, "owner": "basnijholt", "pr_url": "https://github.com/basnijholt/adaptive-lighting/pull/1489", "title": ""}}, "head_sha": "b6f340a43d7bde47b86b633d697abb0b295c3634", "metadata": {"group_id": "2c19e17c38064fd11c4f21d77f1716e1d18a91fd94ccf602ba2e7bd4876f7217", "snapshot": {"base_sha": "7afdf5bc5ca36bb17a999dba53ef84fc49c9b13e", "external_requirements": [], "head_sha": "b6f340a43d7bde47b86b633d697abb0b295c3634", "objects": 160, "objects_sha256": "3581d67ff802fe3dd956a8e7b7d1dd24175d893bce614157e621daf45626f7d3", "patch_sha256": "d994a11a6e22556f7b12ef75b2d0444a5bcfe694a197b43257392b5a3b58920a"}}, "pr_number": 1489, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "83bcee8c5839", "description": "Large configured sunrise or sunset offsets could move synthetic polar events past solar noon or midnight, inverting the event order and breaking adaptation.", "file_path": "custom_components/adaptive_lighting/color_and_brightness.py"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "83bcee8c5839", "description": "Midnight-sun sunset was calculated as 24 hours after the previous solar midnight rather than relative to the actual next solar midnight, making the synthetic event inaccurate.", "file_path": "custom_components/adaptive_lighting/color_and_brightness.py"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "70882bfbf2e8", "description": "Redundant-command filtering required exact brightness equality, so lights reporting quantized brightness values received repeated commands despite already reaching the target.", "file_path": "custom_components/adaptive_lighting/adaptation_utils.py"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "70882bfbf2e8", "description": "Redundant-command filtering required exact Kelvin equality, so mired-quantized lights received repeated color-temperature commands despite already reaching the target.", "file_path": "custom_components/adaptive_lighting/adaptation_utils.py"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "70882bfbf2e8", "description": "Clamping with intentionally inverted minimum and maximum brightness or color-temperature bounds always returned the configured minimum, preventing the value from adapting.", "file_path": "custom_components/adaptive_lighting/color_and_brightness.py"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "70882bfbf2e8", "description": "For UI-configured entries, stale initial settings in config-entry data overrode newer options-flow changes, silently discarding user updates.", "file_path": "custom_components/adaptive_lighting/switch.py"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "70882bfbf2e8", "description": "Switch names were not device-relative, producing inconsistent device and entity names and incorrectly ordered entity IDs on fresh installations.", "file_path": "custom_components/adaptive_lighting/switch.py"}, {"action_id": "A8", "action_type": "fix", "category": "bug", "commit_sha": "70882bfbf2e8", "description": "An auto-reset callback could cancel its own running timer task while clearing manual control, preventing the remainder of the callback from re-adapting the light.", "file_path": "custom_components/adaptive_lighting/switch.py"}], "commits_under_review": [{"author": "basnijholt", "date": "2026-07-09T04:04:47Z", "files": [{"additions": 45, "deletions": 2, "filename": "custom_components/adaptive_lighting/color_and_brightness.py", "patch": "@@ -35,6 +35,11 @@ class SunEvent(str, Enum):\n _ORDER = (SunEvent.SUNRISE, SunEvent.NOON, SunEvent.SUNSET, SunEvent.MIDNIGHT)\n _ALLOWED_ORDERS = {_ORDER[i:] + _ORDER[:i] for i in range(len(_ORDER))}\n \n+# On polar days without a sunrise/sunset, synthetic sun events are placed this\n+# far from solar noon (polar night) or solar midnight (midnight sun), giving a\n+# 1-hour synthetic \"day\" or \"night\" so the adaptation cycle keeps working.\n+_POLAR_SUN_EVENT_OFFSET = timedelta(minutes=30)\n+\n utcnow: partial[datetime.datetime] = partial(datetime.datetime.now, UTC)\n utcnow.__doc__ = \"Get now in UTC time.\"\n \n@@ -57,10 +62,48 @@ class SunEvents:\n sunset_offset: datetime.timedelta = datetime.timedelta()\n timezone: datetime.tzinfo = UTC\n \n+ def _astral_sunrise_or_sunset(\n+ self,\n+ dt: datetime.date,\n+ event: Literal[SunEvent.SUNRISE, SunEvent.SUNSET],\n+ ) -> datetime.datetime:\n+ \"\"\"Return the astral sunrise/sunset, with a fallback for polar regions.\n+\n+ Above the polar circle the sun never crosses the horizon during polar\n+ night and midnight sun, and `astral` raises a `ValueError` (see #1485).\n+ On such days, synthesize a 1-hour \"day\" around solar noon (polar night)\n+ or a 1-hour \"night\" around solar midnight (midnight sun), so the\n+ adaptation cycle keeps working. The `(min/max)_(sunrise/sunset)_time`\n+ options are applied on top of these synthetic times and can be used to\n+ shape the resulting schedule.\n+ \"\"\"\n+ astral_event = (\n+ astral.sun.sunrise if event == SunEvent.SUNRISE else astral.sun.sunset\n+ )\n+ try:\n+ return astral_event(self.astral_observer, dt)\n+ except ValueError:\n+ noon = astral.sun.noon(self.astral_observer, dt)\n+ midnight = astral.sun.midnight(self.astral_observer, dt)\n+ noon_elevation = astral.sun.elevation(self.astral_observer, noon)\n+ midnight_elevation = astral.sun.elevation(self.astral_observer, midnight)\n+ # The sum of the sun's highest and lowest elevation of the day is\n+ # ≈2x the solar declination, so its sign robustly distinguishes\n+ # midnight sun from polar night, even on the boundary days where\n+ # one elevation hovers around the horizon.\n+ if noon_elevation + midnight_elevation > 0:\n+ # Midnight sun: the sun stays above the horizon all day.\n+ if event == SunEvent.SUNRISE:\n+ return midnight + _POLAR_SUN_EVENT_OFFSET\n+ return midnight + timedelta(hours=24) - _POLAR_SUN_EVENT_OFFSET\n+ # Polar night: the sun stays below the horizon all day.\n+ sign = -1 if event == SunEvent.SUNRISE else 1\n+ return noon + sign * _POLAR_SUN_EVENT_OFFSET\n+\n def sunrise(self, dt: datetime.date) -> datetime.datetime:\n \"\"\"Return the (adjusted) sunrise time for the given datetime.\"\"\"\n sunrise = (\n- astral.sun.sunrise(self.astral_observer, dt)\n+ self._astral_sunrise_or_sunset(dt, SunEvent.SUNRISE)\n if self.sunrise_time is None\n else self._replace_time(dt, self.sunrise_time)\n ) + self.sunrise_offset\n@@ -75,7 +118,7 @@ def sunrise(self, dt: datetime.date) -> datetime.datetime:\n def sunset(self, dt: datetime.date) -> datetime.datetime:\n \"\"\"Return the (adjusted) sunset time for the given datetime.\"\"\"\n sunset = (\n- astral.sun.sunset(self.astral_observer, dt)\n+ self._astral_sunrise_or_sunset(dt, SunEvent.SUNSET)\n if self.sunset_time is None\n else self._replace_time(dt, self.sunset_time)\n ) + self.sunset_offset", "status": "modified"}, {"additions": 140, "deletions": 0, "filename": "tests/test_color_and_brightness.py", "patch": "@@ -1,12 +1,15 @@\n import datetime as dt\n import zoneinfo\n \n+import astral.sun\n import pytest\n from astral import LocationInfo\n from astral.location import Location\n from homeassistant.components.adaptive_lighting.color_and_brightness import (\n+ _POLAR_SUN_EVENT_OFFSET,\n SunEvent,\n SunEvents,\n+ SunLightSettings,\n )\n \n # Create a mock astral location object (its `.observer` is passed to `SunEvents`)\n@@ -207,3 +210,140 @@ def test_closest_event(tzinfo_and_location):\n event_name, ts = sun_events.closest_event(sunrise)\n assert event_name == SunEvent.SUNRISE\n assert ts == location.sunrise(sunrise.date()).timestamp()\n+\n+\n+# Tromsø, Norway (69.6°N) has polar night (Nov-Jan) and midnight sun (May-Jul).\n+TROMSO = Location(\n+ LocationInfo(\n+ name=\"Tromsø\",\n+ region=\"Norway\",\n+ timezone=\"Europe/Oslo\",\n+ latitude=69.6489,\n+ longitude=18.9551,\n+ ),\n+)\n+POLAR_NIGHT_DATE = dt.date(2026, 1, 7)\n+MIDNIGHT_SUN_DATE = dt.date(2026, 7, 7)\n+\n+\n+def _tromso_sun_events(**kwargs):\n+ defaults = {\n+ \"name\": \"test\",\n+ \"astral_observer\": TROMSO.observer,\n+ \"sunrise_time\": None,\n+ \"min_sunrise_time\": None,\n+ \"max_sunrise_time\": None,\n+ \"sunset_time\": None,\n+ \"min_sunset_time\": None,\n+ \"max_sunset_time\": None,\n+ \"timezone\": zoneinfo.ZoneInfo(\"Europe/Oslo\"),\n+ }\n+ return SunEvents(**{**defaults, **kwargs})\n+\n+\n+def test_polar_night_synthesizes_short_day():\n+ # `astral` cannot compute sunrise/sunset (the sun never rises), see #1485\n+ with pytest.raises(ValueError): # noqa: PT011\n+ astral.sun.sunrise(TROMSO.observer, POLAR_NIGHT_DATE)\n+ sun_events = _tromso_sun_events()\n+ noon = astral.sun.noon(TROMSO.observer, POLAR_NIGHT_DATE)\n+ assert sun_events.sunrise(POLAR_NIGHT_DATE) == noon - _POLAR_SUN_EVENT_OFFSET\n+ assert sun_events.sunset(POLAR_NIGHT_DATE) == noon + _POLAR_SUN_EVENT_OFFSET\n+\n+\n+def test_midnight_sun_synthesizes_short_night():\n+ # `astral` cannot compute sunrise/sunset (the sun never sets), see #1485\n+ with pytest.raises(ValueError): # noqa: PT011\n+ astral.sun.sunset(TROMSO.observer, MIDNIGHT_SUN_DATE)\n+ sun_events = _tromso_sun_events()\n+ midnight = astral.sun.midnight(TROMSO.observer, MIDNIGHT_SUN_DATE)\n+ assert sun_events.sunrise(MIDNIGHT_SUN_DATE) == midnight + _POLAR_SUN_EVENT_OFFSET\n+ assert (\n+ sun_events.sunset(MIDNIGHT_SUN_DATE)\n+ == midnight + dt.timedelta(hours=24) - _POLAR_SUN_EVENT_OFFSET\n+ )\n+\n+\n+def test_boundary_day_with_real_sunrise_and_synthetic_sunset():\n+ # At the start of the midnight sun period, `astral` computes a real\n+ # sunrise for this date but raises for sunset (this exact date depends on\n+ # astral's numerics). The synthetic sunset must stay consistent with the\n+ # nearly 24-hour day instead of collapsing into a polar-night day.\n+ date = dt.date(2026, 5, 18)\n+ astral.sun.sunrise(TROMSO.observer, date) # does not raise\n+ with pytest.raises(ValueError): # noqa: PT011\n+ astral.sun.sunset(TROMSO.observer, date)\n+ sun_events = _tromso_sun_events()\n+ day_length = sun_events.sunset(date) - sun_events.sunrise(date)\n+ assert day_length > dt.timedelta(hours=22)\n+\n+\n+@pytest.mark.parametrize(\"date\", [POLAR_NIGHT_DATE, MIDNIGHT_SUN_DATE])\n+def test_sun_position_on_polar_days(date):\n+ sun_events = _tromso_sun_events()\n+ datetime = dt.datetime(date.year, date.month, date.day, tzinfo=dt.timezone.utc)\n+ noon, midnight = sun_events.noon_and_midnight(datetime)\n+ assert sun_events.sun_position(noon) == 1\n+ assert sun_events.sun_position(midnight) == -1\n+ assert sun_events.sun_position(sun_events.sunrise(date)) == 0\n+ assert sun_events.sun_position(sun_events.sunset(date)) == 0\n+\n+\n+def test_polar_night_min_max_times_shape_the_synthetic_day():\n+ # The (min/max)_(sunrise/sunset)_time options apply on top of the\n+ # synthetic sun events, so users can still shape their schedule.\n+ sun_events = _tromso_sun_events(\n+ max_sunrise_time=dt.time(9, 0),\n+ min_sunset_time=dt.time(17, 0),\n+ timezone=dt.timezone.utc,\n+ )\n+ expected_sunrise = dt.datetime(2026, 1, 7, 9, 0, tzinfo=dt.timezone.utc)\n+ expected_sunset = dt.datetime(2026, 1, 7, 17, 0, tzinfo=dt.timezone.utc)\n+ assert sun_events.sunrise(POLAR_NIGHT_DATE) == expected_sunrise\n+ assert sun_events.sunset(POLAR_NIGHT_DATE) == expected_sunset\n+\n+\n+def test_sun_position_all_year_in_polar_region():\n+ # Covers the transitions into and out of polar night and midnight sun;\n+ # `sun_position` internally validates the order of the sun events.\n+ sun_events = _tromso_sun_events()\n+ datetime = dt.datetime(2026, 1, 1, tzinfo=dt.timezone.utc)\n+ end = dt.datetime(2027, 1, 1, tzinfo=dt.timezone.utc)\n+ while datetime < end:\n+ position = sun_events.sun_position(datetime)\n+ assert -1 <= position <= 1\n+ datetime += dt.timedelta(hours=8)\n+\n+\n+@pytest.mark.parametrize(\"date\", [POLAR_NIGHT_DATE, MIDNIGHT_SUN_DATE])\n+def test_brightness_and_color_on_polar_days(date):\n+ settings = SunLightSettings(\n+ name=\"test\",\n+ astral_observer=TROMSO.observer,\n+ adapt_until_sleep=False,\n+ max_brightness=100,\n+ max_color_temp=5500,\n+ min_brightness=30,\n+ min_color_temp=2000,\n+ sleep_brightness=1,\n+ sleep_rgb_or_color_temp=\"color_temp\",\n+ sleep_color_temp=1000,\n+ sleep_rgb_color=(255, 56, 0),\n+ sunrise_time=None,\n+ min_sunrise_time=None,\n+ max_sunrise_time=None,\n+ sunset_time=None,\n+ min_sunset_time=None,\n+ max_sunset_time=None,\n+ brightness_mode_time_dark=dt.timedelta(hours=1),\n+ brightness_mode_time_light=dt.timedelta(hours=1),\n+ timezone=zoneinfo.ZoneInfo(\"Europe/Oslo\"),\n+ )\n+ datetime = dt.datetime(date.year, date.month, date.day, tzinfo=dt.timezone.utc)\n+ noon, midnight = settings.sun.noon_and_midnight(datetime)\n+ at_noon = settings.brightness_and_color(noon, is_sleep=False)\n+ assert at_noon[\"brightness_pct\"] == 100\n+ assert at_noon[\"color_temp_kelvin\"] == 5500\n+ at_midnight = settings.brightness_and_color(midnight, is_sleep=False)\n+ assert at_midnight[\"brightness_pct\"] == 30\n+ assert at_midnight[\"color_temp_kelvin\"] == 2000", "status": "modified"}], "message": "fix: keep adapting during polar night and midnight sun\n\nAbove the polar circle, `astral.sun.sunrise()`/`sunset()` raise a\n`ValueError` on days when the sun never crosses the horizon, which\ncrashed every adaptation cycle for months at a time.\n\nWhen astral cannot compute a sunrise/sunset, synthesize one instead:\na 1-hour \"day\" around solar noon during polar night, and a 1-hour\n\"night\" around solar midnight during midnight sun. The regime is\npicked by the sign of the sun's noon+midnight elevation sum (~2x the\nsolar declination), which stays robust on boundary days where one\nelevation hovers at the horizon. The existing\n`(min/max)_(sunrise/sunset)_time` options apply on top of the\nsynthetic times, so users can still shape their schedule; previously\nthese options did not prevent the crash because astral was called\nbefore the clamps.\n\nFixes #1485\nFixes #138", "sha": "b6f340a43d7bde47b86b633d697abb0b295c3634"}], "post_review_commits": ["57ef0d57aa5bc111acb6c485e2262b26ccfdfd78", "83bcee8c58398afadeec9b9f7241ab43faf93d0e", "70882bfbf2e853144dbe1700c1b8ada0a3ddc5d2"], "pr_author": "basnijholt", "pr_title": "fix: keep adapting during polar night and midnight sun", "repo_name": "basnijholt/adaptive-lighting"}, "repo": "basnijholt/adaptive-lighting", "snapshot": "snapshots/2c19e17c38064fd11c4f21d77f1716e1d18a91fd94ccf602ba2e7bd4876f7217.pack", "split": "rl", "task_id": "08f3246256fd4175c2ff0bdf2c65c0cae73a015b82ad77a16e7b88a9ad5908bc"} {"base_sha": "f788565a993397977ba8b493fdfa47af53886b50", "cohort": null, "context": {"canonical_pr_url": "https://github.com/ShipfoxHQ/shipfox/pull/596", "id": "0c855af94d3993d5bce8b8dee3fec64545da401fd567c25d89b88421fb059e7e", "preparation_mode": "source-only", "snapshot": {"base_ref": "f788565a993397977ba8b493fdfa47af53886b50", "base_sha": "f788565a993397977ba8b493fdfa47af53886b50", "body": "", "head_ref": "2f307c9c1f30bfca4c576ffc9252db42a0bfc790", "head_sha": "2f307c9c1f30bfca4c576ffc9252db42a0bfc790", "name": "shipfox", "number": 596, "owner": "ShipfoxHQ", "pr_url": "https://github.com/ShipfoxHQ/shipfox/pull/596", "title": ""}}, "head_sha": "2f307c9c1f30bfca4c576ffc9252db42a0bfc790", "metadata": {"group_id": "82fd8056e4cdb303bc21fe4f495b7dd11c2687a6c390d648b1dc4e1e34c58b89", "snapshot": {"base_sha": "f788565a993397977ba8b493fdfa47af53886b50", "external_requirements": [], "head_sha": "2f307c9c1f30bfca4c576ffc9252db42a0bfc790", "objects": 3590, "objects_sha256": "213b5384724d92b6ae7f39b37ce331ed11e22f2dac5fd0dff6725509fec35f6c", "patch_sha256": "a62265095d1a35fcec3c918b5ba0db1cb3af1abe8e6de5f17ef9e388dab7d0a9"}}, "pr_number": 596, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "538cf091b0ad", "description": "If compaction published a new object key after the first prefix cleanup, the guarded row deletion failed and left the expired stream for a later sweep instead of cleaning the newly published object and deleting the row.", "file_path": "libs/api/logs/src/core/retention.ts"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "d26e09c93150", "description": "A failure while reloading a stream after a guarded deletion failed was not handled per stream, so it could abort the sweep and prevent later expired streams from being processed.", "file_path": "libs/api/logs/src/core/retention.ts"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "0ddd269de309", "description": "The reload-failure test mock called the spied method for healthy streams, recursively invoking itself instead of the original implementation.", "file_path": "libs/api/logs/src/core/retention.test.ts"}], "commits_under_review": [{"author": "noe-charmet", "date": "2026-07-04T14:58:51Z", "files": [{"additions": 5, "deletions": 0, "filename": ".changeset/eng-783-logs-retention-retry.md", "patch": "@@ -0,0 +1,5 @@\n+---\n+\"@shipfox/api-logs\": patch\n+---\n+\n+Makes log retention delete object prefixes before stream rows so transient object-storage delete failures leave rows discoverable for a later sweep instead of permanently orphaning billed objects.", "status": "added"}, {"additions": 55, "deletions": 1, "filename": "libs/api/logs/src/core/retention.test.ts", "patch": "@@ -1,6 +1,7 @@\n import {Buffer} from 'node:buffer';\n import {HeadObjectCommand, PutObjectCommand} from '@aws-sdk/client-s3';\n import {eq, sql} from 'drizzle-orm';\n+import * as objectStorage from '#api/object-storage.js';\n import {s3Client} from '#api/object-storage.js';\n import {config} from '#config.js';\n import {logObjectKey} from '#core/entities/log-object.js';\n@@ -153,7 +154,7 @@ describe('runRetentionSweep', () => {\n expect(await findAccounting(shared.jobId)).toBeNull();\n });\n \n- it('deletes a closed-but-never-compacted stream (object_key null), doing no object work', async () => {\n+ it('deletes a closed-but-never-compacted stream (object_key null)', async () => {\n const id = newIdentity();\n const stream = await arrangeClosedStream(id, {chunks: [ndjsonBody(outputLine('x'))]});\n await backdateClosedAt(stream.id, '100 days');\n@@ -165,6 +166,32 @@ describe('runRetentionSweep', () => {\n expect(result.failed).toBe(0);\n });\n \n+ it('keeps the row when prefix deletion fails, so a later sweep can rediscover the object', async () => {\n+ const poison = newIdentity();\n+ const healthy = newIdentity();\n+ const poisonStream = await arrangeClosedStream(poison);\n+ const healthyStream = await arrangeClosedStream(healthy);\n+ const poisonKey = `${attemptPrefix(poison)}/${crypto.randomUUID()}`;\n+ await putObject(poisonKey, Buffer.from('poison'));\n+ await setObjectKey(poisonStream.id, poisonKey);\n+ await backdateClosedAt(poisonStream.id, '200 days');\n+ await backdateClosedAt(healthyStream.id, '100 days');\n+ const poisonPrefix = `${attemptPrefix(poison)}/`;\n+ const realDeleteObjectsByPrefix = objectStorage.deleteObjectsByPrefix;\n+ vi.spyOn(objectStorage, 'deleteObjectsByPrefix').mockImplementation((prefix) =>\n+ prefix === poisonPrefix\n+ ? Promise.reject(new Error('object delete failed'))\n+ : realDeleteObjectsByPrefix(prefix),\n+ );\n+\n+ const result = await sweep({batchLimit: 1});\n+\n+ expect(await findStream(poison)).not.toBeNull();\n+ expect(await objectExists(poisonKey)).toBe(true);\n+ expect(await findStream(healthy)).toBeNull();\n+ expect(result.failed).toBeGreaterThanOrEqual(1);\n+ });\n+\n it('deletes the whole attempt prefix, reclaiming a lost compaction attempt orphan leaf', async () => {\n const id = newIdentity();\n const stream = await arrangeClosedStream(id);\n@@ -187,6 +214,9 @@ describe('runRetentionSweep', () => {\n const healthy = newIdentity();\n const poisonStream = await arrangeClosedStream(poison);\n const healthyStream = await arrangeClosedStream(healthy);\n+ const poisonKey = `${attemptPrefix(poison)}/${crypto.randomUUID()}`;\n+ await putObject(poisonKey, Buffer.from('poison'));\n+ await setObjectKey(poisonStream.id, poisonKey);\n await backdateClosedAt(poisonStream.id, '200 days');\n await backdateClosedAt(healthyStream.id, '100 days');\n const realDeleteExpiredStream = streams.deleteExpiredStream;\n@@ -200,9 +230,33 @@ describe('runRetentionSweep', () => {\n \n expect(await findStream(healthy)).toBeNull();\n expect(await findStream(poison)).not.toBeNull();\n+ expect(await objectExists(poisonKey)).toBe(false);\n expect(result.failed).toBeGreaterThanOrEqual(1);\n });\n \n+ it('self-heals a row delete failure after the object prefix was already deleted', async () => {\n+ const id = newIdentity();\n+ const stream = await arrangeClosedStream(id);\n+ const key = `${attemptPrefix(id)}/${crypto.randomUUID()}`;\n+ await putObject(key, Buffer.from('compacted'));\n+ await setObjectKey(stream.id, key);\n+ await backdateClosedAt(stream.id, '300 days');\n+ vi.spyOn(streams, 'deleteExpiredStream').mockImplementationOnce(() =>\n+ Promise.reject(new Error('row delete failed')),\n+ );\n+\n+ const failed = await sweep({batchLimit: 1});\n+\n+ expect(await objectExists(key)).toBe(false);\n+ expect(await findStream(id)).not.toBeNull();\n+ expect(failed.failed).toBe(1);\n+\n+ const recovered = await sweep({batchLimit: 1});\n+\n+ expect(await findStream(id)).toBeNull();\n+ expect(recovered.failed).toBe(0);\n+ });\n+\n it('does not reset a live job budget: deletes its expired streams but keeps fresh accounting', async () => {\n const id = newIdentity();\n const stream = await arrangeClosedStream(id);", "status": "modified"}, {"additions": 17, "deletions": 15, "filename": "libs/api/logs/src/core/retention.ts", "patch": "@@ -11,11 +11,11 @@ import {\n } from '#db/streams.js';\n \n export interface RetentionSweepResult {\n- /** Streams whose row was deleted; their objects are reclaimed after (a rare object-cleanup failure is logged). */\n+ /** Streams whose objects and row were deleted. */\n deleted: number;\n /** Streams skipped because compaction changed `object_key` after we read it (retried next run). */\n raced: number;\n- /** Streams whose guarded row delete threw; logged, skipped, and retried next run. */\n+ /** Streams whose object cleanup or guarded row delete threw; logged, skipped, and retried next run. */\n failed: number;\n accountingPruned: number;\n iterations: number;\n@@ -38,9 +38,9 @@ export interface RunRetentionSweepParams {\n * Deletes expired closed streams and prunes accounting for emptied jobs.\n *\n * The loop self-bounds because a Temporal `startToCloseTimeout` marks the activity failed but\n- * does not stop already-running JS. Rows are deleted before objects, guarded on the observed\n- * `object_key`, so a racing compaction publish leaves the stream for the next sweep instead of\n- * deleting its fresh object.\n+ * does not stop already-running JS. Objects are deleted before rows so a cleanup failure leaves\n+ * the row discoverable for the next sweep; the row delete stays guarded on the observed\n+ * `object_key`, so a racing compaction publish leaves the stream for the next sweep.\n */\n export async function runRetentionSweep(\n params: RunRetentionSweepParams,\n@@ -81,6 +81,18 @@ export async function runRetentionSweep(\n break;\n }\n \n+ try {\n+ await deleteObjectsByPrefix(`${logObjectKey(config.LOG_STORAGE_S3_PREFIX, stream)}/`);\n+ } catch (error) {\n+ result.failed += 1;\n+ skip.add(stream.id);\n+ logger().error(\n+ {err: error, streamId: stream.id},\n+ 'Failed to delete expired log stream objects',\n+ );\n+ continue;\n+ }\n+\n let outcome: {deleted: boolean; prunedAccounting: boolean};\n try {\n outcome = await db().transaction(async (tx) => {\n@@ -116,16 +128,6 @@ export async function runRetentionSweep(\n \n result.deleted += 1;\n if (outcome.prunedAccounting) result.accountingPruned += 1;\n-\n- // The guarded row delete won, so reclaim the recorded object plus orphan leaves.\n- try {\n- await deleteObjectsByPrefix(`${logObjectKey(config.LOG_STORAGE_S3_PREFIX, stream)}/`);\n- } catch (error) {\n- logger().error(\n- {err: error, streamId: stream.id},\n- 'Deleted expired stream row but failed to delete its objects',\n- );\n- }\n }\n \n if (timedOutMidBatch) break;", "status": "modified"}], "message": "Fix log retention object cleanup ordering\n\nDelete expired log object prefixes before hard-deleting their stream rows so transient object-storage failures leave rows discoverable for a later retention sweep instead of permanently orphaning billed objects.\n\nFixes ENG-783", "sha": "2f307c9c1f30bfca4c576ffc9252db42a0bfc790"}], "post_review_commits": ["538cf091b0ade9ab6f76d33e7e9e743ea6c7ff30", "d26e09c931507e4a6eb727aa71f8f3e916cc0a3e", "0ddd269de309f74a475a5f9248ede047de45b975"], "pr_author": "noe-charmet", "pr_title": "[api/logs] Fix retention object cleanup ordering", "repo_name": "ShipfoxHQ/shipfox"}, "repo": "ShipfoxHQ/shipfox", "snapshot": "snapshots/82fd8056e4cdb303bc21fe4f495b7dd11c2687a6c390d648b1dc4e1e34c58b89.pack", "split": "rl", "task_id": "0c855af94d3993d5bce8b8dee3fec64545da401fd567c25d89b88421fb059e7e"} {"base_sha": "f726bad90d796452eecb311f57829e072616418d", "cohort": null, "context": {"canonical_pr_url": "https://github.com/igcodinap/go-eval/pull/20", "id": "0d526cf4efb2e56708abc8424ea7051f77950dc84ae6f599dcc781d87624a0ab", "preparation_mode": "source-only", "snapshot": {"base_ref": "f726bad90d796452eecb311f57829e072616418d", "base_sha": "f726bad90d796452eecb311f57829e072616418d", "body": "", "head_ref": "69aa07c660de9c4a86079d3cef77e427041fb82d", "head_sha": "69aa07c660de9c4a86079d3cef77e427041fb82d", "name": "go-eval", "number": 20, "owner": "igcodinap", "pr_url": "https://github.com/igcodinap/go-eval/pull/20", "title": ""}}, "head_sha": "69aa07c660de9c4a86079d3cef77e427041fb82d", "metadata": {"group_id": "a33df83486d0a3e38604b5e47c12ca6a1c73bcc5d5dc8526a7fc6139eec46d04", "snapshot": {"base_sha": "f726bad90d796452eecb311f57829e072616418d", "external_requirements": [], "head_sha": "69aa07c660de9c4a86079d3cef77e427041fb82d", "objects": 114, "objects_sha256": "949ba6f3032c1bccb8a4eeddb11997d148c1ce668a311942114805b2402f65cf", "patch_sha256": "ff0f234820de86ef012dde079d757dec9fed3d1429bdfac438cb90b8af061640"}}, "pr_number": 20, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "e2bbecfbfdd7", "description": "The getting-started faithfulness benchmark did not enable the evaluation gate, so its evaluation could be skipped when run without the environment variable set.", "file_path": "docs/getting_started_test.go"}], "commits_under_review": [{"author": "igcodinap", "date": "2026-04-28T23:20:57Z", "files": [{"additions": 1, "deletions": 0, "filename": "CHANGELOG.md", "patch": "@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n - `compare` package for baseline-vs-current JSONL result regression diffs\n - Minimal `goeval` CLI with `test`, `compare`, and `version` commands\n - JSON dataset loader (`LoadCases`, `LoadNamedCases`, `LoadDataset`) for external golden cases\n+- Getting Started guide covering local judges, OpenAI, metrics, JSONL results, and benchmarks\n \n ## [v0.2.0] - 2026-04-22\n ", "status": "modified"}, {"additions": 3, "deletions": 0, "filename": "README.md", "patch": "@@ -27,6 +27,9 @@ go install github.com/igcodinap/go-eval/cmd/goeval@latest\n \n ## Quickstart\n \n+For a full walkthrough with copyable evals, an OpenAI-backed judge, JSONL\n+results, and benchmarks, see the [Getting Started guide](docs/getting-started.md).\n+\n ```go\n package yourpkg_test\n ", "status": "modified"}, {"additions": 288, "deletions": 0, "filename": "docs/getting-started.md", "patch": "@@ -0,0 +1,288 @@\n+# Getting Started\n+\n+This guide starts with a local, deterministic eval you can copy into any Go\n+project. Then it shows the same shape with an OpenAI-backed judge, RAG metrics,\n+deterministic checks, `Compound`, `Precheck`, JSONL result output, and\n+benchmarks.\n+\n+`go-eval` runs inside `go test`. Eval runs are opt-in: `Runner.Run` and\n+`eval.Bench` skip unless `GOEVAL=1` is set. This keeps normal local runs and CI\n+fast by default.\n+\n+## Install\n+\n+```bash\n+go get github.com/igcodinap/go-eval\n+```\n+\n+The optional OpenAI judge adapter is a separate module so the core package stays\n+stdlib-only:\n+\n+```bash\n+go get github.com/igcodinap/go-eval/adapters/openai github.com/sashabaranov/go-openai\n+```\n+\n+## Copy a Minimal Eval\n+\n+Create `answer_eval_test.go` next to the code you want to evaluate.\n+\n+```go\n+package yourpkg_test\n+\n+import (\n+\t\"context\"\n+\t\"testing\"\n+\n+\teval \"github.com/igcodinap/go-eval\"\n+)\n+\n+type deterministicJudge struct{}\n+\n+func (deterministicJudge) Evaluate(ctx context.Context, prompt string) (eval.JudgeResponse, error) {\n+\t_ = ctx\n+\t_ = prompt\n+\treturn eval.JudgeResponse{\n+\t\tScore: 0.95,\n+\t\tReason: \"local deterministic judge response\",\n+\t\tTokens: 12,\n+\t}, nil\n+}\n+\n+func TestAnswerEval(t *testing.T) {\n+\tjudge := deterministicJudge{}\n+\tr := eval.NewRunner(judge, eval.WithResultSink(eval.DefaultResultSink()))\n+\n+\tc := eval.Case{\n+\t\tInput: \"What is the capital of France?\",\n+\t\tOutput: \"Paris is the capital of France.\",\n+\t\tExpected: \"Paris\",\n+\t\tContext: []string{\"Paris is the capital of France.\"},\n+\t\tMetadata: map[string]any{\n+\t\t\t\"flow\": \"rag.answer\",\n+\t\t\t\"tier\": \"critical\",\n+\t\t\t\"dataset\": \"getting-started/v1\",\n+\t\t},\n+\t}\n+\n+\tr.Run(t, eval.Contains{}, c)\n+\tr.Run(t, eval.Faithfulness{Threshold: 0.8}, c)\n+\tr.Run(t, eval.Hallucination{Threshold: 0.9}, c)\n+\tr.Run(t, eval.AnswerRelevancy{Threshold: 0.7}, c)\n+}\n+```\n+\n+Run it:\n+\n+```bash\n+go test ./...\n+GOEVAL=1 go test ./...\n+```\n+\n+Without `GOEVAL=1`, the eval calls skip. With `GOEVAL=1`, `Runner` executes each\n+metric and reports low scores with `t.Errorf`. Judge or metric execution errors\n+are fatal.\n+\n+## Use an OpenAI Judge\n+\n+Use the adapter when you want actual LLM-as-judge scoring. This is a snippet:\n+drop it into a test that imports your application code and builds real\n+`eval.Case` values.\n+\n+```go\n+package yourpkg_test\n+\n+import (\n+\t\"os\"\n+\t\"testing\"\n+\n+\topenai \"github.com/sashabaranov/go-openai\"\n+\n+\teval \"github.com/igcodinap/go-eval\"\n+\topenaieval \"github.com/igcodinap/go-eval/adapters/openai\"\n+)\n+\n+func TestOpenAIEval(t *testing.T) {\n+\tif os.Getenv(eval.EnvVar) == \"\" {\n+\t\tt.Skip(\"eval skipped, set GOEVAL=1 to run\")\n+\t}\n+\n+\tjudge, err := openaieval.NewJudgeFromEnv(openai.GPT4oMini)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\tr := eval.NewRunner(judge, eval.WithResultSink(eval.DefaultResultSink()))\n+\tc := eval.Case{\n+\t\tInput: \"What is the capital of France?\",\n+\t\tOutput: \"Paris is the capital of France.\",\n+\t\tContext: []string{\"Paris is the capital of France.\"},\n+\t}\n+\n+\tr.Run(t, eval.Faithfulness{Threshold: 0.8}, c)\n+}\n+```\n+\n+Run it with both gates:\n+\n+```bash\n+OPENAI_API_KEY=sk-... GOEVAL=1 go test ./...\n+```\n+\n+The early `GOEVAL` skip keeps ordinary `go test ./...` runs from requiring an\n+API key.\n+\n+## Pick Metrics\n+\n+RAG evals usually start with these metrics:\n+\n+```go\n+r.Run(t, eval.Faithfulness{Threshold: 0.8}, c) // output is supported by context\n+r.Run(t, eval.Hallucination{Threshold: 0.9}, c) // output avoids unsupported claims\n+r.Run(t, eval.AnswerRelevancy{Threshold: 0.7}, c) // output answers the input\n+r.Run(t, eval.ContextPrecision{Threshold: 0.7}, c) // retrieved context is relevant\n+```\n+\n+Use deterministic metrics for cheap format and content checks before paying for\n+an LLM judge:\n+\n+```go\n+r.Run(t, eval.Contains{}, eval.Case{\n+\tOutput: \"Paris is the capital of France.\",\n+\tExpected: \"Paris\",\n+})\n+\n+r.Run(t, eval.Regex{Pattern: `(?i)\\bparis\\b`}, eval.Case{\n+\tOutput: \"Paris is the capital of France.\",\n+})\n+\n+r.Run(t, eval.MustJSONPath(\"answer.city\"), eval.Case{\n+\tOutput: `{\"answer\":{\"city\":\"Paris\",\"country\":\"France\"}}`,\n+\tExpected: \"Paris\",\n+})\n+\n+r.Run(t, eval.FieldCount{MinFields: 2}, eval.Case{\n+\tOutput: `{\"answer\":\"Paris\",\"confidence\":0.98}`,\n+})\n+```\n+\n+`Contains`, `Regex`, `JSONPath`, and `FieldCount` ignore the judge argument, but\n+they still benefit from `Runner` behavior: the same `GOEVAL` gate, case filters,\n+result sinks, and test assertions.\n+\n+## Score Multiple Dimensions\n+\n+`Compound` asks a raw judge for several rubric dimensions in one call. The\n+OpenAI adapter implements both `eval.Judge` and `eval.RawJudge`, so it can run\n+`Compound` directly.\n+\n+```go\n+r.Run(t, eval.Compound{\n+\tDimensions: []eval.Dimension{\n+\t\t{\n+\t\t\tName: \"grounding\",\n+\t\t\tRubric: \"Every factual claim is supported by the provided context.\",\n+\t\t\tThreshold: 0.8,\n+\t\t},\n+\t\t{\n+\t\t\tName: \"directness\",\n+\t\t\tRubric: \"The answer directly addresses the user question without extra digressions.\",\n+\t\t\tThreshold: 0.7,\n+\t\t},\n+\t},\n+}, c)\n+```\n+\n+The result contains an overall score plus per-dimension scores. If any dimension\n+with a threshold fails, the `Compound` result fails.\n+\n+## Short-Circuit with Precheck\n+\n+`Precheck` runs a cheap metric first and only runs the expensive metric when the\n+precheck passes. This snippet checks that the output looks like JSON before\n+running a judge-backed custom rubric.\n+\n+```go\n+r.Run(t, eval.Precheck{\n+\tPre: eval.Regex{Pattern: `^\\s*\\{`},\n+\tMain: eval.GEval{\n+\t\tCriteria: \"The JSON answer should be grounded in the provided context.\",\n+\t\tThreshold: 0.8,\n+\t},\n+}, c)\n+```\n+\n+If `Pre` fails, `Main` is skipped and the test receives a failed result that\n+explains the precheck failure.\n+\n+## Save JSONL Results\n+\n+Add the default sink when creating the runner:\n+\n+```go\n+r := eval.NewRunner(judge, eval.WithResultSink(eval.DefaultResultSink()))\n+```\n+\n+Then set `GOEVAL_RESULTS_DIR` during the run:\n+\n+```bash\n+GOEVAL=1 GOEVAL_RESULTS_DIR=.eval-results go test ./...\n+```\n+\n+`DefaultResultSink` writes `.eval-results/results.jsonl`. Each row includes the\n+test name, metric, score, pass/fail status, reason, latency, token counts,\n+optional `Compound` dimensions, and `Case.Metadata`.\n+\n+You can compare two runs with the optional CLI:\n+\n+```bash\n+go install github.com/igcodinap/go-eval/cmd/goeval@latest\n+goeval compare old/results.jsonl new/results.jsonl\n+```\n+\n+## Benchmark an Eval\n+\n+Use `eval.Bench` when you want benchmark output for latency, token usage, and\n+score stability.\n+\n+```go\n+func BenchmarkAnswerFaithfulness(b *testing.B) {\n+\tr := eval.NewRunner(deterministicJudge{})\n+\tc := eval.Case{\n+\t\tInput: \"What is the capital of France?\",\n+\t\tOutput: \"Paris is the capital of France.\",\n+\t\tContext: []string{\"Paris is the capital of France.\"},\n+\t}\n+\n+\teval.Bench(b, r, eval.Faithfulness{Threshold: 0.8}, c)\n+}\n+```\n+\n+Run:\n+\n+```bash\n+GOEVAL=1 go test -bench=. -count=5\n+```\n+\n+Benchmark output includes the normal Go benchmark timing plus:\n+\n+- `tokens/op`: mean tokens consumed per iteration\n+- `score_mean`: mean score across iterations\n+- `score_stddev`: population standard deviation of scores\n+\n+This makes prompt or model changes easier to compare with `benchstat`.\n+\n+## Grow into a Suite\n+\n+For more than a couple of cases, keep cases in a JSON dataset and load them with\n+`eval.LoadNamedCases`. Use `Case.Metadata` consistently:\n+\n+| Key | Type | Example |\n+| --- | --- | --- |\n+| `flow` | string | `rag.answer` |\n+| `tier` | string | `critical`, `standard`, or `extended` |\n+| `dataset` | string | `support-faq/v1` |\n+\n+The repo also ships a canonical authoring guide for teams and coding agents\n+building larger suites: [`docs/agent-skills/authoring-go-eval-suites/`](agent-skills/authoring-go-eval-suites/).\n+It covers case design, metric selection, JSONL reports, and common failure\n+patterns without requiring any specific agent runtime.", "status": "added"}, {"additions": 112, "deletions": 0, "filename": "docs/getting_started_test.go", "patch": "@@ -0,0 +1,112 @@\n+package docs_test\n+\n+import (\n+\t\"context\"\n+\t\"testing\"\n+\n+\teval \"github.com/igcodinap/go-eval\"\n+)\n+\n+type deterministicJudge struct{}\n+\n+func (deterministicJudge) Evaluate(ctx context.Context, prompt string) (eval.JudgeResponse, error) {\n+\t_ = ctx\n+\t_ = prompt\n+\treturn eval.JudgeResponse{\n+\t\tScore: 0.95,\n+\t\tReason: \"local deterministic judge response\",\n+\t\tTokens: 12,\n+\t}, nil\n+}\n+\n+func (deterministicJudge) EvaluateRaw(ctx context.Context, prompt string) (eval.RawJudgeResponse, error) {\n+\t_ = ctx\n+\t_ = prompt\n+\treturn eval.RawJudgeResponse{\n+\t\tContent: `{\n+\t\t\t\"grounding\": {\"score\": 0.95, \"reason\": \"claims are supported by context\"},\n+\t\t\t\"directness\": {\"score\": 0.90, \"reason\": \"answer is direct\"}\n+\t\t}`,\n+\t\tTokens: 18,\n+\t}, nil\n+}\n+\n+func TestGettingStartedPatterns(t *testing.T) {\n+\tt.Setenv(eval.EnvVar, \"1\")\n+\n+\tjudge := deterministicJudge{}\n+\tr := eval.NewRunner(judge, eval.WithResultSink(eval.DefaultResultSink()))\n+\n+\tc := eval.Case{\n+\t\tInput: \"What is the capital of France?\",\n+\t\tOutput: \"Paris is the capital of France.\",\n+\t\tExpected: \"Paris\",\n+\t\tContext: []string{\"Paris is the capital of France.\"},\n+\t\tMetadata: map[string]any{\n+\t\t\t\"flow\": \"rag.answer\",\n+\t\t\t\"tier\": \"critical\",\n+\t\t\t\"dataset\": \"getting-started/v1\",\n+\t\t},\n+\t}\n+\n+\tr.Run(t, eval.Contains{}, c)\n+\tr.Run(t, eval.Faithfulness{Threshold: 0.8}, c)\n+\tr.Run(t, eval.Hallucination{Threshold: 0.9}, c)\n+\tr.Run(t, eval.AnswerRelevancy{Threshold: 0.7}, c)\n+\tr.Run(t, eval.Compound{\n+\t\tDimensions: []eval.Dimension{\n+\t\t\t{\n+\t\t\t\tName: \"grounding\",\n+\t\t\t\tRubric: \"Every factual claim is supported by the provided context.\",\n+\t\t\t\tThreshold: 0.8,\n+\t\t\t},\n+\t\t\t{\n+\t\t\t\tName: \"directness\",\n+\t\t\t\tRubric: \"The answer directly addresses the user question.\",\n+\t\t\t\tThreshold: 0.7,\n+\t\t\t},\n+\t\t},\n+\t}, c)\n+}\n+\n+func TestGettingStartedDeterministicMetrics(t *testing.T) {\n+\tt.Setenv(eval.EnvVar, \"1\")\n+\n+\tr := eval.NewRunner(deterministicJudge{})\n+\n+\tr.Run(t, eval.Contains{}, eval.Case{\n+\t\tOutput: \"Paris is the capital of France.\",\n+\t\tExpected: \"Paris\",\n+\t})\n+\tr.Run(t, eval.Regex{Pattern: `(?i)\\bparis\\b`}, eval.Case{\n+\t\tOutput: \"Paris is the capital of France.\",\n+\t})\n+\tr.Run(t, eval.MustJSONPath(\"answer.city\"), eval.Case{\n+\t\tOutput: `{\"answer\":{\"city\":\"Paris\",\"country\":\"France\"}}`,\n+\t\tExpected: \"Paris\",\n+\t})\n+\tr.Run(t, eval.FieldCount{MinFields: 2}, eval.Case{\n+\t\tOutput: `{\"answer\":\"Paris\",\"confidence\":0.98}`,\n+\t})\n+\tr.Run(t, eval.Precheck{\n+\t\tPre: eval.Regex{Pattern: `^\\s*\\{`},\n+\t\tMain: eval.GEval{\n+\t\t\tCriteria: \"The JSON answer should be grounded in the provided context.\",\n+\t\t\tThreshold: 0.8,\n+\t\t},\n+\t}, eval.Case{\n+\t\tOutput: `{\"answer\":\"Paris\"}`,\n+\t\tContext: []string{\"Paris is the capital of France.\"},\n+\t})\n+}\n+\n+func BenchmarkGettingStartedFaithfulness(b *testing.B) {\n+\tr := eval.NewRunner(deterministicJudge{})\n+\tc := eval.Case{\n+\t\tInput: \"What is the capital of France?\",\n+\t\tOutput: \"Paris is the capital of France.\",\n+\t\tContext: []string{\"Paris is the capital of France.\"},\n+\t}\n+\n+\teval.Bench(b, r, eval.Faithfulness{Threshold: 0.8}, c)\n+}", "status": "added"}], "message": "Add getting started guide", "sha": "69aa07c660de9c4a86079d3cef77e427041fb82d"}], "post_review_commits": ["e2bbecfbfdd7bfdd904ad8754a555ec0b71316d0"], "pr_author": "igcodinap", "pr_title": "Add v0.3 Getting Started guide", "repo_name": "igcodinap/go-eval"}, "repo": "igcodinap/go-eval", "snapshot": "snapshots/a33df83486d0a3e38604b5e47c12ca6a1c73bcc5d5dc8526a7fc6139eec46d04.pack", "split": "rl", "task_id": "0d526cf4efb2e56708abc8424ea7051f77950dc84ae6f599dcc781d87624a0ab"} {"base_sha": "f1cb1fdb21be680df68bde086d8abad73cc22651", "cohort": null, "context": {"canonical_pr_url": "https://github.com/kdlbs/kandev/pull/934", "id": "0d839fc31dbba425b5eb74a3a8f7d20d0491cc134b218da00cdf833768971d97", "preparation_mode": "source-only", "snapshot": {"base_ref": "f1cb1fdb21be680df68bde086d8abad73cc22651", "base_sha": "f1cb1fdb21be680df68bde086d8abad73cc22651", "body": "", "head_ref": "73f63ae83783f73ecc24e7523496bac37a811451", "head_sha": "73f63ae83783f73ecc24e7523496bac37a811451", "name": "kandev", "number": 934, "owner": "kdlbs", "pr_url": "https://github.com/kdlbs/kandev/pull/934", "title": ""}}, "head_sha": "73f63ae83783f73ecc24e7523496bac37a811451", "metadata": {"group_id": "7f81bcab28cb456bc9803a88b45617dd0a9d6c9e383b74ba85cec3572a1bb09f", "snapshot": {"base_sha": "f1cb1fdb21be680df68bde086d8abad73cc22651", "external_requirements": [], "head_sha": "73f63ae83783f73ecc24e7523496bac37a811451", "objects": 4257, "objects_sha256": "fd55f9feb2708db4a09f81796e3546cb35e968f57aeeab4b38488c2e192bbec7", "patch_sha256": "cc388563bd7fe957326a76ba11c8834b94cb3f5ef315e321277260f658c622b8"}}, "pr_number": 934, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "31a31edfbe45", "description": "Cmd/Ctrl+Enter in the custom-answer input called the per-question submit handler before final submission, redundantly advancing the carousel on multi-question bundles and potentially triggering a second submission path.", "file_path": "apps/web/components/task/chat/clarification-overlay-parts.tsx"}, {"action_id": "A2", "action_type": "improvement", "category": "performance", "commit_sha": "31a31edfbe45", "description": "The submit callback depended on the entire clarification group object, which was recreated on every render, causing the callback to be recreated on each live-recorded keystroke.", "file_path": "apps/web/components/task/chat/clarification-input-overlay.tsx"}, {"action_id": "A3", "action_type": "improvement", "category": "other", "commit_sha": "31a31edfbe45", "description": "The inflight submission guard lacked a direct concurrency test; the existing 409 round-trip test did not verify that simultaneous submitCollected calls produce only one POST.", "file_path": "apps/web/hooks/domains/session/use-clarification-group.test.ts"}], "commits_under_review": [{"author": "zeval", "date": "2026-05-18T12:51:37Z", "files": [{"additions": 25, "deletions": 0, "filename": "apps/web/hooks/domains/session/use-clarification-group.test.ts", "patch": "@@ -77,6 +77,31 @@ describe(\"useClarificationGroup — derived state\", () => {\n expect(result.current.answeredCount).toBe(1);\n expect(fetchMock).not.toHaveBeenCalled();\n });\n+\n+ it(\"clearAnswer removes the entry and decrements answeredCount\", async () => {\n+ const msgs = [\n+ clarMessage({ id: \"m1\", pendingId: \"p1\", questionId: \"q1\", index: 0, total: 2 }),\n+ clarMessage({ id: \"m2\", pendingId: \"p1\", questionId: \"q2\", index: 1, total: 2 }),\n+ ];\n+ const { result } = renderHook(() => useClarificationGroup(msgs));\n+\n+ await act(async () => {\n+ result.current.recordAnswer(\"q1\", { question_id: \"q1\", custom_text: \"draft\" });\n+ });\n+ expect(result.current.answeredCount).toBe(1);\n+\n+ await act(async () => {\n+ result.current.clearAnswer(\"q1\");\n+ });\n+ expect(result.current.answers[\"q1\"]).toBeUndefined();\n+ expect(result.current.answeredCount).toBe(0);\n+\n+ // Clearing a question that was never recorded is a no-op.\n+ await act(async () => {\n+ result.current.clearAnswer(\"q-missing\");\n+ });\n+ expect(result.current.answeredCount).toBe(0);\n+ });\n });\n \n describe(\"useClarificationGroup — submit + skip\", () => {", "status": "modified"}, {"additions": 24, "deletions": 0, "filename": "apps/web/hooks/domains/session/use-clarification-group.ts", "patch": "@@ -13,6 +13,7 @@ export type ClarificationGroupApi = {\n answers: Record;\n submitState: SubmitState;\n recordAnswer: (questionId: string, answer: ClarificationAnswer) => void;\n+ clearAnswer: (questionId: string) => void;\n // Submits every recorded answer in a single batch. An optional `override`\n // map is merged into the current answers right before the POST so callers\n // can safely auto-submit immediately after recording an answer (the React\n@@ -88,6 +89,11 @@ export function useClarificationGroup(\n answersRef.current = answers;\n }, [answers]);\n const [submitState, setSubmitState] = useState(\"idle\");\n+ // Re-entry guard: multiple submit paths can race (Cmd+Enter inside the\n+ // custom input fires both the input's onSubmit and onRequestFinalSubmit;\n+ // a double-click on the Submit button can also race). The hook owns the\n+ // guarantee that only one POST is in flight at a time.\n+ const inflightRef = useRef(false);\n \n const pendingId = useMemo(() => {\n if (!messages || messages.length === 0) return null;\n@@ -106,12 +112,23 @@ export function useClarificationGroup(\n setAnswers((prev) => ({ ...prev, [questionId]: answer }));\n }, []);\n \n+ const clearAnswer = useCallback((questionId: string) => {\n+ setAnswers((prev) => {\n+ if (!(questionId in prev)) return prev;\n+ const next = { ...prev };\n+ delete next[questionId];\n+ return next;\n+ });\n+ }, []);\n+\n const submitCollected = useCallback(\n async (override?: Record) => {\n if (!pendingId) return;\n+ if (inflightRef.current) return;\n const current = { ...answersRef.current, ...(override ?? {}) };\n const haveAll = questionIds.every((id) => Boolean(current[id]));\n if (!haveAll) return;\n+ inflightRef.current = true;\n setSubmitState(\"submitting\");\n const ordered = questionIds\n .map((id) => current[id])\n@@ -121,6 +138,8 @@ export function useClarificationGroup(\n } catch (err) {\n console.error(\"Clarification submit threw:\", err);\n setSubmitState(\"error\");\n+ } finally {\n+ inflightRef.current = false;\n }\n },\n [pendingId, questionIds],\n@@ -129,12 +148,16 @@ export function useClarificationGroup(\n const skipAll = useCallback(\n async (reason?: string) => {\n if (!pendingId) return;\n+ if (inflightRef.current) return;\n+ inflightRef.current = true;\n setSubmitState(\"submitting\");\n try {\n setSubmitState(await postClarificationSkip(pendingId, reason ?? \"User skipped\"));\n } catch (err) {\n console.error(\"Clarification skip threw:\", err);\n setSubmitState(\"error\");\n+ } finally {\n+ inflightRef.current = false;\n }\n },\n [pendingId],\n@@ -147,6 +170,7 @@ export function useClarificationGroup(\n answers,\n submitState,\n recordAnswer,\n+ clearAnswer,\n submitCollected,\n skipAll,\n };", "status": "modified"}], "message": "feat(web): add clearAnswer + submit re-entry guard to useClarificationGroup\n\nclearAnswer removes a stored answer so emptying a clarification draft can\nrevert the stepper to \"unanswered\". A small inflight ref in submitCollected\n/ skipAll prevents duplicate POSTs when multiple submit paths race (e.g.\nCmd+Enter inside the custom input commits the draft and also asks the\nparent to finalize the batch).", "sha": "162a3141e20fc58bd6853bab24f97cc8167d2a12"}, {"author": "zeval", "date": "2026-05-18T12:51:49Z", "files": [{"additions": 133, "deletions": 39, "filename": "apps/web/components/task/chat/clarification-input-overlay.tsx", "patch": "@@ -59,11 +59,13 @@ type CardProps = {\n selectedOption: string | null;\n customCommittedText: string | null;\n customDraft: string;\n+ customActive: boolean;\n isSubmitting: boolean;\n showAgentDisconnected: boolean;\n onSelectOption: (optionId: string) => void;\n onCustomDraftChange: (text: string) => void;\n onSubmitCustom: (text: string) => void;\n+ onRequestFinalSubmit: () => void;\n };\n \n function ClarificationCard(props: CardProps) {\n@@ -74,11 +76,13 @@ function ClarificationCard(props: CardProps) {\n selectedOption,\n customCommittedText,\n customDraft,\n+ customActive,\n isSubmitting,\n showAgentDisconnected,\n onSelectOption,\n onCustomDraftChange,\n onSubmitCustom,\n+ onRequestFinalSubmit,\n } = props;\n const { question, metadata } = meta;\n return (\n@@ -111,6 +115,7 @@ function ClarificationCard(props: CardProps) {\n options={question.options}\n selectedOption={selectedOption}\n isSubmitting={isSubmitting}\n+ customActive={customActive}\n onSelectOption={onSelectOption}\n />\n {showAgentDisconnected && (\n@@ -126,8 +131,10 @@ function ClarificationCard(props: CardProps) {\n draft={customDraft}\n isSubmitting={isSubmitting}\n committedText={customCommittedText}\n+ active={customActive}\n onChange={onCustomDraftChange}\n onSubmit={onSubmitCustom}\n+ onRequestFinalSubmit={onRequestFinalSubmit}\n />\n \n );\n@@ -172,12 +179,29 @@ function shouldIgnoreShortcut(e: KeyboardEvent): boolean {\n return e.metaKey || e.ctrlKey || e.altKey || e.shiftKey;\n }\n \n+// tryHandleMetaEnter returns true when the event was Cmd/Ctrl+Enter, so the\n+// caller can short-circuit. When focus is inside the custom-text input it\n+// returns true *without* invoking onSubmit — the input's own keydown handler\n+// owns that path and is responsible for committing the draft + final submit.\n+function tryHandleMetaEnter(e: KeyboardEvent, canSubmit: boolean, onSubmit: () => void): boolean {\n+ if (e.key !== \"Enter\" || e.shiftKey || e.altKey) return false;\n+ if (!e.metaKey && !e.ctrlKey) return false;\n+ const inEditable =\n+ e.target instanceof HTMLElement &&\n+ (e.target.tagName === \"INPUT\" || e.target.tagName === \"TEXTAREA\");\n+ if (inEditable) return true;\n+ e.preventDefault();\n+ if (canSubmit) onSubmit();\n+ return true;\n+}\n+\n function CarouselKeyboardShortcuts(args: CarouselShortcutArgs) {\n const optionsCount = args.meta.question.options.length;\n const isLast = args.activeIndex === args.total - 1;\n const { canSubmit, onPick, onPrev, onNext, onSkip, onSubmit } = args;\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n+ if (tryHandleMetaEnter(e, canSubmit, onSubmit)) return;\n if (shouldIgnoreShortcut(e)) return;\n if (e.key === \"Escape\") {\n e.preventDefault();\n@@ -216,6 +240,98 @@ type CarouselBodyProps = {\n setCustomDrafts: React.Dispatch>>;\n };\n \n+type QuestionHandlerCtx = {\n+ meta: SingleQuestionMeta;\n+ group: ReturnType;\n+ isSingleQuestion: boolean;\n+ activeIndex: number;\n+ total: number;\n+ setActiveIndex: (idx: number) => void;\n+ setCustomDrafts: React.Dispatch>>;\n+};\n+\n+type QuestionHandlers = {\n+ onSelectOption: (optionId: string) => void;\n+ onCustomDraftChange: (value: string) => void;\n+ onSubmitCustom: (text: string) => void;\n+};\n+\n+type SelectionState = {\n+ selectedOption: string | null;\n+ customCommittedText: string | null;\n+ draft: string;\n+ customActive: boolean;\n+};\n+\n+function deriveSelectionState(\n+ meta: SingleQuestionMeta,\n+ answers: Record,\n+ customDrafts: Record,\n+): SelectionState {\n+ const stored = answers[meta.questionId];\n+ const selected = stored?.selected_options ?? [];\n+ const selectedOption = selected.length > 0 ? selected[0] : null;\n+ const customCommittedText = stored?.custom_text ?? null;\n+ const draft = customDrafts[meta.questionId] ?? \"\";\n+ const hasCustomText = draft.trim().length > 0 || (customCommittedText?.length ?? 0) > 0;\n+ const customActive = !selectedOption && hasCustomText;\n+ return { selectedOption, customCommittedText, draft, customActive };\n+}\n+\n+function buildQuestionHandlers(ctx: QuestionHandlerCtx): QuestionHandlers {\n+ const { meta, group, isSingleQuestion, activeIndex, total, setActiveIndex, setCustomDrafts } =\n+ ctx;\n+\n+ // Records the answer, then auto-submits (single-question — uses the override\n+ // path because setState is async) or auto-advances to the next step.\n+ const commitAnswer = (answer: ClarificationAnswer) => {\n+ group.recordAnswer(meta.questionId, answer);\n+ if (isSingleQuestion) {\n+ void group.submitCollected({ [meta.questionId]: answer });\n+ return;\n+ }\n+ if (activeIndex < total - 1) setActiveIndex(activeIndex + 1);\n+ };\n+\n+ return {\n+ onSelectOption(optionId) {\n+ // Picking an option wipes any in-flight draft so the answer state and\n+ // the visible input agree (custom_text and selected_options are mutually\n+ // exclusive at commit time).\n+ setCustomDrafts((prev) => {\n+ if (!prev[meta.questionId]) return prev;\n+ return { ...prev, [meta.questionId]: \"\" };\n+ });\n+ commitAnswer({ question_id: meta.questionId, selected_options: [optionId] });\n+ },\n+ // Live-record the draft so the stepper updates and the custom input lights\n+ // up the moment the user types. Emptying the draft clears the answer so\n+ // allAnswered reverts to false. Enter/Cmd+Enter still drives advance/submit.\n+ onCustomDraftChange(value) {\n+ setCustomDrafts((prev) => ({ ...prev, [meta.questionId]: value }));\n+ const trimmed = value.trim();\n+ if (trimmed.length === 0) {\n+ group.clearAnswer(meta.questionId);\n+ return;\n+ }\n+ group.recordAnswer(meta.questionId, {\n+ question_id: meta.questionId,\n+ selected_options: [],\n+ custom_text: trimmed,\n+ });\n+ },\n+ onSubmitCustom(text) {\n+ const trimmed = text.trim();\n+ if (!trimmed) return;\n+ commitAnswer({\n+ question_id: meta.questionId,\n+ selected_options: [],\n+ custom_text: trimmed,\n+ });\n+ },\n+ };\n+}\n+\n function ClarificationCarouselBody({\n sortedMessages,\n group,\n@@ -231,7 +347,6 @@ function ClarificationCarouselBody({\n (m) => (m.metadata as ClarificationRequestMetadata | undefined)?.agent_disconnected === true,\n );\n const isSubmitting = group.submitState === \"submitting\";\n-\n const isSingleQuestion = total === 1;\n \n const allAnswered = sortedMessages.every((m) => {\n@@ -245,42 +360,21 @@ function ClarificationCarouselBody({\n \n if (!meta) return null;\n \n- const stored = group.answers[meta.questionId];\n- const selectedOption =\n- stored?.selected_options && stored.selected_options.length > 0\n- ? stored.selected_options[0]\n- : null;\n- const customCommittedText = stored?.custom_text ?? null;\n- const draft = customDrafts[meta.questionId] ?? \"\";\n-\n- // Records the new answer, then either auto-submits (single-question case\n- // takes the override path so the freshly recorded answer is included even\n- // though setState is async) or auto-advances to the next step.\n- const commitAnswer = (answer: ClarificationAnswer) => {\n- group.recordAnswer(meta.questionId, answer);\n- if (isSingleQuestion) {\n- void group.submitCollected({ [meta.questionId]: answer });\n- return;\n- }\n- if (activeIndex < total - 1) {\n- setActiveIndex(activeIndex + 1);\n- }\n- };\n+ const { selectedOption, customCommittedText, draft, customActive } = deriveSelectionState(\n+ meta,\n+ group.answers,\n+ customDrafts,\n+ );\n \n- const onSelectOption = (optionId: string) => {\n- commitAnswer({\n- question_id: meta.questionId,\n- selected_options: [optionId],\n- });\n- };\n- const onSubmitCustom = (text: string) => {\n- if (!text.trim()) return;\n- commitAnswer({\n- question_id: meta.questionId,\n- selected_options: [],\n- custom_text: text.trim(),\n- });\n- };\n+ const { onSelectOption, onCustomDraftChange, onSubmitCustom } = buildQuestionHandlers({\n+ meta,\n+ group,\n+ isSingleQuestion,\n+ activeIndex,\n+ total,\n+ setActiveIndex,\n+ setCustomDrafts,\n+ });\n \n return (\n <>\n@@ -291,13 +385,13 @@ function ClarificationCarouselBody({\n selectedOption={selectedOption}\n customCommittedText={customCommittedText}\n customDraft={draft}\n+ customActive={customActive}\n isSubmitting={isSubmitting}\n showAgentDisconnected={activeIndex === 0 && showAgentDisconnectedAtTop}\n onSelectOption={onSelectOption}\n- onCustomDraftChange={(value) =>\n- setCustomDrafts((prev) => ({ ...prev, [meta.questionId]: value }))\n- }\n+ onCustomDraftChange={onCustomDraftChange}\n onSubmitCustom={onSubmitCustom}\n+ onRequestFinalSubmit={handleSubmit}\n />\n {!isSingleQuestion && (\n void;\n };\n \n-// The agent receives both the selected option id and the custom text when\n-// both are present, so we never visually grey out one when the other is\n-// active — that previously created an asymmetric dimming bug where typing\n-// a custom answer dimmed the options but selecting an option did not dim\n-// the custom input.\n export function ClarificationOptions({\n options,\n selectedOption,\n isSubmitting,\n+ customActive,\n onSelectOption,\n }: OptionListProps) {\n return (\n
\n {options.map((option, idx) => {\n- const isSelected = selectedOption === option.option_id;\n+ const isSelected = !customActive && selectedOption === option.option_id;\n return (\n void;\n onSubmit: (text: string) => void;\n+ // Called after Cmd/Ctrl+Enter so the parent can attempt a batch submit\n+ // (no-op when not all questions are answered yet).\n+ onRequestFinalSubmit?: () => void;\n };\n \n export function ClarificationCustomInput({\n draft,\n isSubmitting,\n committedText,\n+ active,\n onChange,\n onSubmit,\n+ onRequestFinalSubmit,\n }: CustomInputProps) {\n return (\n-
\n- ↳\n+ \n+ \n+ ↳\n+ \n {\n- if (e.key === \"Enter\" && !e.shiftKey && draft.trim()) {\n+ if (e.key !== \"Enter\" || e.shiftKey || e.altKey) return;\n+ if (e.metaKey || e.ctrlKey) {\n+ e.preventDefault();\n+ if (draft.trim()) onSubmit(draft.trim());\n+ onRequestFinalSubmit?.();\n+ return;\n+ }\n+ if (draft.trim()) {\n e.preventDefault();\n onSubmit(draft.trim());\n }\n@@ -182,6 +212,7 @@ export function ClarificationCustomInput({\n \n Enter\n \n+ {active && }\n
\n );\n }", "status": "modified"}], "message": "feat(web): show selected state and Cmd+Enter submit on clarification custom input\n\nThe \"Or type a custom answer…\" input previously had no selected styling and\nneeded an Enter keypress before the carousel stepper marked the question as\nanswered, which made it easy to lose track of which path was the active\nanswer. Now:\n\n- Typing into the custom input live-records the draft, so the stepper and\n group progress update immediately and the input picks up the same blue\n ring + check icon used by selected options. When custom is active, any\n previously picked option visually deselects (they are mutually exclusive\n at commit time).\n- Picking an option after typing wipes that question's draft so the visible\n input and committed answer stay in sync.\n- Cmd/Ctrl+Enter submits the bundle when every question is answered — from\n inside the custom input (commits the draft then finalises) and from\n anywhere else in the overlay. Inside the input is handled locally so\n submitCollected does not fire twice.", "sha": "62fcfcfb9481c453b862e685841f146681f46d5e"}, {"author": "zeval", "date": "2026-05-18T12:51:58Z", "files": [{"additions": 5, "deletions": 0, "filename": "apps/web/e2e/pages/session-page.ts", "patch": "@@ -329,6 +329,11 @@ export class SessionPage {\n return this.clarificationQuestionCardById(questionId).getByTestId(\"clarification-input\");\n }\n \n+ /** Container around the custom text input — exposes data-active for selection state. */\n+ clarificationCustomInputContainerForQuestion(questionId: string): Locator {\n+ return this.clarificationQuestionCardById(questionId).getByTestId(\"clarification-custom-input\");\n+ }\n+\n /** Option button (by visible label text) inside a specific question card. */\n clarificationOptionForQuestion(questionId: string, text: string): Locator {\n return this.clarificationQuestionCardById(questionId)", "status": "modified"}, {"additions": 123, "deletions": 0, "filename": "apps/web/e2e/tests/chat/clarification.spec.ts", "patch": "@@ -473,4 +473,127 @@ test.describe(\"Multi-question clarification carousel\", () => {\n await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n await expect(session.clarificationPrev()).toBeDisabled();\n });\n+\n+ test(\"typing in the custom input auto-selects it and deselects the picked option\", async ({\n+ testPage,\n+ apiClient,\n+ seedData,\n+ }) => {\n+ const session = await seedClarificationTask(\n+ testPage,\n+ apiClient,\n+ seedData,\n+ \"Multi-q custom auto-selects\",\n+ \"clarification-multi\",\n+ );\n+\n+ await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n+\n+ // Pick an option on Q1 (auto-advances to Q2), then jump back to Q1.\n+ await session.clarificationOption(\"PostgreSQL\").click();\n+ await session.clarificationStep(0).click();\n+ const selectedBefore = session\n+ .clarificationQuestionCardById(\"db\")\n+ .locator('[data-testid=\"clarification-option\"][data-selected=\"true\"]');\n+ await expect(selectedBefore).toContainText(\"PostgreSQL\");\n+\n+ // Type into the custom input — it should light up and the option should\n+ // deselect, while the stepper keeps step 0 marked as answered.\n+ const input = session.clarificationInputForQuestion(\"db\");\n+ await input.click();\n+ await input.fill(\"Bespoke KV store\");\n+\n+ const customContainer = session.clarificationCustomInputContainerForQuestion(\"db\");\n+ await expect(customContainer).toHaveAttribute(\"data-active\", \"true\");\n+ await expect(\n+ session\n+ .clarificationQuestionCardById(\"db\")\n+ .locator('[data-testid=\"clarification-option\"][data-selected=\"true\"]'),\n+ ).toHaveCount(0);\n+ await expect(session.clarificationStep(0)).toHaveAttribute(\"data-answered\", \"true\");\n+ await expect(session.clarificationGroupProgress()).toContainText(\"1 of 3 answered\");\n+ });\n+\n+ test(\"emptying the custom draft clears the answer and reverts the stepper\", async ({\n+ testPage,\n+ apiClient,\n+ seedData,\n+ }) => {\n+ const session = await seedClarificationTask(\n+ testPage,\n+ apiClient,\n+ seedData,\n+ \"Multi-q draft clears answer\",\n+ \"clarification-multi\",\n+ );\n+\n+ await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n+\n+ const input = session.clarificationInputForQuestion(\"db\");\n+ await input.click();\n+ await input.fill(\"Bespoke KV store\");\n+ await expect(session.clarificationStep(0)).toHaveAttribute(\"data-answered\", \"true\");\n+ await expect(session.clarificationGroupProgress()).toContainText(\"1 of 3 answered\");\n+\n+ await input.fill(\"\");\n+ await expect(session.clarificationStep(0)).toHaveAttribute(\"data-answered\", \"false\");\n+ await expect(session.clarificationGroupProgress()).toContainText(\"0 of 3 answered\");\n+ await expect(session.clarificationCustomInputContainerForQuestion(\"db\")).toHaveAttribute(\n+ \"data-active\",\n+ \"false\",\n+ );\n+ });\n+\n+ test(\"Cmd+Enter from the last step's custom input submits the bundle\", async ({\n+ testPage,\n+ apiClient,\n+ seedData,\n+ }) => {\n+ const session = await seedClarificationTask(\n+ testPage,\n+ apiClient,\n+ seedData,\n+ \"Multi-q cmd+enter from input\",\n+ \"clarification-multi\",\n+ );\n+\n+ await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n+\n+ await session.clarificationOption(\"PostgreSQL\").click();\n+ await session.clarificationOption(\"Go\").click();\n+\n+ const deployInput = session.clarificationInputForQuestion(\"deploy\");\n+ await deployInput.click();\n+ await deployInput.fill(\"Nomad cluster\");\n+ await deployInput.press(\"ControlOrMeta+Enter\");\n+\n+ await expect(session.clarificationOverlay()).not.toBeVisible({ timeout: 30_000 });\n+ await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });\n+ await expect(session.chat).toContainText(\"Nomad cluster\");\n+ });\n+\n+ test(\"Cmd+Enter from outside the input submits when all questions are answered\", async ({\n+ testPage,\n+ apiClient,\n+ seedData,\n+ }) => {\n+ const session = await seedClarificationTask(\n+ testPage,\n+ apiClient,\n+ seedData,\n+ \"Multi-q cmd+enter global\",\n+ \"clarification-multi\",\n+ );\n+\n+ await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n+\n+ await session.clarificationOption(\"PostgreSQL\").click();\n+ await session.clarificationOption(\"Go\").click();\n+ await session.clarificationOption(\"Docker\").click();\n+\n+ // Focus is on the last option button, not the input.\n+ await testPage.keyboard.press(\"ControlOrMeta+Enter\");\n+ await expect(session.clarificationOverlay()).not.toBeVisible({ timeout: 30_000 });\n+ await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });\n+ });\n });", "status": "modified"}], "message": "test(web): cover live-record + Cmd+Enter clarification UX\n\nAdds four cases over the existing clarification-multi mock scenario:\ntyping auto-selects custom and deselects the option, emptying the draft\nreverts the stepper, Cmd+Enter from the last-step custom input submits\nthe bundle, and Cmd+Enter from outside the input submits when all answered.\nAdds a session-page locator for the new custom-input container so the\ndata-active attribute can be asserted.", "sha": "73f63ae83783f73ecc24e7523496bac37a811451"}], "post_review_commits": ["31a31edfbe4595d2709c89d3694d7f50fed04bb7"], "pr_author": "zeval", "pr_title": "feat(web): clearer custom-answer state and Cmd+Enter submit on clarifications", "repo_name": "kdlbs/kandev"}, "repo": "kdlbs/kandev", "snapshot": "snapshots/7f81bcab28cb456bc9803a88b45617dd0a9d6c9e383b74ba85cec3572a1bb09f.pack", "split": "rl", "task_id": "0d839fc31dbba425b5eb74a3a8f7d20d0491cc134b218da00cdf833768971d97"} {"base_sha": "3c0e7fb001becdb3761bcbfcab9b0cc3116b99fc", "cohort": null, "context": {"canonical_pr_url": "https://github.com/tirthpatell/threads-go/pull/29", "id": "0d8617912d4a6d9d252c6967648878d3f6d84ec3cd4ea9c01d457825dfd16755", "preparation_mode": "source-only", "snapshot": {"base_ref": "3c0e7fb001becdb3761bcbfcab9b0cc3116b99fc", "base_sha": "3c0e7fb001becdb3761bcbfcab9b0cc3116b99fc", "body": "", "head_ref": "05c791936f7f7c6b7608ba5c294606cd34491e75", "head_sha": "05c791936f7f7c6b7608ba5c294606cd34491e75", "name": "threads-go", "number": 29, "owner": "tirthpatell", "pr_url": "https://github.com/tirthpatell/threads-go/pull/29", "title": ""}}, "head_sha": "05c791936f7f7c6b7608ba5c294606cd34491e75", "metadata": {"group_id": "5925f55ef03b28eb806212d6fb4a9ad4a8657c3a40e78f14cee4cc0a3ff9277d", "snapshot": {"base_sha": "3c0e7fb001becdb3761bcbfcab9b0cc3116b99fc", "external_requirements": [], "head_sha": "05c791936f7f7c6b7608ba5c294606cd34491e75", "objects": 85, "objects_sha256": "8adbc49b60442e17a2bdd8dd580de2e84084d02bba9d92613bb295ccd986a054", "patch_sha256": "d625bcdbc501a7ef7cf4cc067f2746f3e708b31b8c75e28bdf3b4c30485db9ba"}}, "pr_number": 29, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "70ea89fffc51", "description": "Authentication errors carrying an HTTP 5xx status were treated as retryable, even though retrying an invalid token cannot resolve the error.", "file_path": "http_client.go"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "70ea89fffc51", "description": "When the /me fallback returned malformed JSON, token validation wrapped the earlier debug_token error instead of the JSON parsing error, hiding the actual failure.", "file_path": "client.go"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "70ea89fffc51", "description": "When both debug_token and /me failed, token validation reported only the debug_token error, concealing the /me failure and making infrastructure failures harder to distinguish from authentication failures.", "file_path": "client.go"}, {"action_id": "A4", "action_type": "cleanup", "category": "refactor", "commit_sha": "70ea89fffc51", "description": "Production token validation used TestAPICall for the /me fallback, despite that method being designated as test-only infrastructure.", "file_path": "client.go"}], "commits_under_review": [{"author": "tirthpatell", "date": "2026-05-20T15:11:07Z", "files": [{"additions": 32, "deletions": 5, "filename": "client.go", "patch": "@@ -526,14 +526,41 @@ func NewClientWithToken(accessToken string, config *Config) (*Client, error) {\n \t\treturn nil, fmt.Errorf(\"failed to set temporary token: %w\", err)\n \t}\n \n-\t// Validate and get accurate token information\n-\tdebugResp, err := client.DebugToken(context.Background(), accessToken)\n+\t// Validate and get accurate token information via debug_token. If that\n+\t// endpoint fails (graph.threads.net returns HTTP 500 for valid tokens on\n+\t// dev-mode apps), fall back to a /me call which reliably validates the\n+\t// token and returns the user ID needed to bootstrap TokenInfo.\n+\tdebugResp, debugErr := client.DebugToken(context.Background(), accessToken)\n+\tif debugErr == nil {\n+\t\tif err := client.SetTokenFromDebugInfo(accessToken, debugResp); err != nil {\n+\t\t\treturn nil, fmt.Errorf(\"failed to set token info: %w\", err)\n+\t\t}\n+\t\treturn client, nil\n+\t}\n+\n+\t// debug_token failed — verify with /me as fallback\n+\tmeResp, err := client.TestAPICall(\"GET\", \"/v1.0/me\", map[string]string{\"fields\": \"id\"})\n \tif err != nil {\n-\t\treturn nil, fmt.Errorf(\"failed to validate token: %w\", err)\n+\t\t// Both validation paths failed; surface the original debug_token error\n+\t\treturn nil, fmt.Errorf(\"failed to validate token: %w\", debugErr)\n \t}\n \n-\t// Set accurate token information from debug response\n-\tif err := client.SetTokenFromDebugInfo(accessToken, debugResp); err != nil {\n+\tvar me struct {\n+\t\tID string `json:\"id\"`\n+\t}\n+\tif jsonErr := json.Unmarshal(meResp.Body, &me); jsonErr != nil || me.ID == \"\" {\n+\t\treturn nil, fmt.Errorf(\"failed to validate token: %w\", debugErr)\n+\t}\n+\n+\t// /me succeeded — token is valid. Set token info with the user ID and a\n+\t// 60-day expiry (standard Threads long-lived token lifetime).\n+\tif err := client.SetTokenInfo(&TokenInfo{\n+\t\tAccessToken: accessToken,\n+\t\tTokenType: \"Bearer\",\n+\t\tExpiresAt: time.Now().Add(60 * 24 * time.Hour),\n+\t\tUserID: me.ID,\n+\t\tCreatedAt: time.Now(),\n+\t}); err != nil {\n \t\treturn nil, fmt.Errorf(\"failed to set token info: %w\", err)\n \t}\n ", "status": "modified"}, {"additions": 35, "deletions": 0, "filename": "client_test.go", "patch": "@@ -1235,6 +1235,41 @@ func TestNewClientWithToken(t *testing.T) {\n \t\t}\n \t})\n \n+\tt.Run(\"debug_token 500 falls back to /me\", func(t *testing.T) {\n+\t\t// graph.threads.net returns HTTP 500 for valid tokens on dev-mode apps;\n+\t\t// NewClientWithToken must fall back to /me and succeed.\n+\t\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n+\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n+\t\t\tif r.URL.Path == \"/debug_token\" {\n+\t\t\t\tw.WriteHeader(500)\n+\t\t\t\tw.Write([]byte(`{\"error\":{\"message\":\"Invalid OAuth 2.0 Access Token\",\"code\":190,\"type\":\"THApiException\",\"error_data\":[]}}`))\n+\t\t\t\treturn\n+\t\t\t}\n+\t\t\t// /v1.0/me fallback\n+\t\t\tw.WriteHeader(200)\n+\t\t\tw.Write([]byte(`{\"id\":\"27258452443753298\",\"username\":\"fiadocs\"}`))\n+\t\t}))\n+\t\tdefer ts.Close()\n+\n+\t\tconfig := &Config{\n+\t\t\tClientID: \"test-id\",\n+\t\t\tClientSecret: \"test-secret\",\n+\t\t\tRedirectURI: \"https://example.com/callback\",\n+\t\t\tBaseURL: ts.URL,\n+\t\t}\n+\n+\t\tclient, err := NewClientWithToken(\"valid-token\", config)\n+\t\tif err != nil {\n+\t\t\tt.Fatalf(\"expected no error when /me succeeds, got: %v\", err)\n+\t\t}\n+\t\tif !client.IsAuthenticated() {\n+\t\t\tt.Error(\"expected client to be authenticated\")\n+\t\t}\n+\t\tif client.GetTokenInfo().UserID != \"27258452443753298\" {\n+\t\t\tt.Errorf(\"expected UserID 27258452443753298, got %s\", client.GetTokenInfo().UserID)\n+\t\t}\n+\t})\n+\n \tt.Run(\"valid token with mock server\", func(t *testing.T) {\n \t\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n \t\t\tw.Header().Set(\"Content-Type\", \"application/json\")", "status": "modified"}], "message": "fix(auth): fall back to /me when debug_token fails in NewClientWithToken\n\ngraph.threads.net returns HTTP 500 for the /debug_token endpoint even\nfor fully valid tokens on Development-mode apps, making NewClientWithToken\nfail at startup despite the token working correctly for all real API calls.\n\nAdd a /me fallback: if DebugToken fails, call /v1.0/me?fields=id to\nverify the token works. On success, bootstrap TokenInfo with the user ID\nand a 60-day expiry (standard Threads long-lived token lifetime). Only\nsurface the original debug_token error if /me also fails, indicating the\ntoken is genuinely invalid.\n\nNote: the retry delay (~7s from 3 retries on 5xx) before the /me fallback\nis a separate issue — debug_token 5xx should not be retried as they are\nnon-transient auth failures.", "sha": "02194b0c5a702e737a088e64a7f415e62be5a6e3"}, {"author": "tirthpatell", "date": "2026-05-20T15:20:35Z", "files": [{"additions": 5, "deletions": 1, "filename": "auth.go", "patch": "@@ -489,7 +489,11 @@ func (c *Client) DebugToken(ctx context.Context, inputToken string) (*DebugToken\n \n \tresp, err := c.httpClient.GET(\"/debug_token\", params, callerToken)\n \tif err != nil {\n-\t\treturn nil, NewNetworkError(0, \"Failed to debug token\", err.Error(), true)\n+\t\t// Propagate the typed error (e.g. AuthenticationError for code 190)\n+\t\t// so callers can inspect it correctly. Wrapping in a NetworkError with\n+\t\t// temporary=true was wrong: it hid the real type and made auth errors\n+\t\t// appear retryable.\n+\t\treturn nil, fmt.Errorf(\"Failed to debug token - %w\", err)\n \t}\n \n \tif resp.StatusCode != http.StatusOK {", "status": "modified"}, {"additions": 22, "deletions": 1, "filename": "http_client.go", "patch": "@@ -315,8 +315,15 @@ func (h *HTTPClient) createErrorFromResponse(resp *Response) error {\n \t\tdetails = details[:500] + \"...\"\n \t}\n \n-\t// Create specific error types based on status code\n+\t// API-level auth codes take priority over HTTP status. Meta returns 5xx\n+\t// for token failures on some endpoints (e.g. /debug_token returns HTTP 500\n+\t// for error 190), which would otherwise be misclassified as retryable 5xx.\n \tvar resultErr error\n+\tif isAuthErrorCode(errorCode) {\n+\t\tauthErr := NewAuthenticationError(errorCode, message, details)\n+\t\tsetErrorMetadata(authErr, false, resp.StatusCode, apiErr.Error.ErrorSubcode)\n+\t\treturn authErr\n+\t}\n \tswitch resp.StatusCode {\n \tcase 401, 403:\n \t\tresultErr = NewAuthenticationError(errorCode, message, details)\n@@ -353,6 +360,20 @@ func (h *HTTPClient) createErrorFromResponse(resp *Response) error {\n \treturn resultErr\n }\n \n+// isAuthErrorCode reports whether code is a well-known Meta/Threads top-level\n+// auth error that should always map to AuthenticationError, regardless of HTTP\n+// status. Meta returns 5xx for these on some endpoints (e.g. /debug_token).\n+// Subcodes (463 = token expired, 467 = missing permissions) nest under 190\n+// and are handled by the caller via setErrorMetadata.\n+func isAuthErrorCode(code int) bool {\n+\tswitch code {\n+\tcase 190, // Invalid/revoked/expired access token (subcodes 463, 467)\n+\t\t102: // Session invalidated / login required\n+\t\treturn true\n+\t}\n+\treturn false\n+}\n+\n // wrapNetworkError wraps network errors with appropriate error types.\n // The original error is preserved as the Cause, so errors.Is/errors.As\n // can inspect it (e.g., to detect context.Canceled).", "status": "modified"}], "message": "fix(http): classify auth error codes as non-retryable; fix DebugToken wrapping\n\nTwo issues caused unnecessary retries and confusing error messages when\ngraph.threads.net returns HTTP 500 for auth failures like error 190:\n\n1. createErrorFromResponse switched on HTTP status only, so a 5xx response\n carrying error code 190 hit the default case (NewAPIError), which\n isRetryableError treated as retryable (HTTPStatusCode >= 500). Add\n isAuthErrorCode to classify known top-level auth codes (190, 102) as\n AuthenticationError regardless of HTTP status — these are never transient.\n\n2. DebugToken wrapped all errors in NewNetworkError(code=0, temporary=true),\n hiding the real error type and marking non-transient auth errors as\n retryable to any caller. Use fmt.Errorf wrapping instead to preserve the\n typed error for callers (including the /me fallback in NewClientWithToken).\n\nTogether these eliminate the ~7s startup delay (3 retries × backoff) that\noccurred when debug_token returned HTTP 500 for a valid token on a dev-mode app.", "sha": "05c791936f7f7c6b7608ba5c294606cd34491e75"}], "post_review_commits": ["70ea89fffc518d83d405057d5d3300c183755b49"], "pr_author": "tirthpatell", "pr_title": "fix: NewClientWithToken /me fallback + non-retryable auth errors", "repo_name": "tirthpatell/threads-go"}, "repo": "tirthpatell/threads-go", "snapshot": "snapshots/5925f55ef03b28eb806212d6fb4a9ad4a8657c3a40e78f14cee4cc0a3ff9277d.pack", "split": "rl", "task_id": "0d8617912d4a6d9d252c6967648878d3f6d84ec3cd4ea9c01d457825dfd16755"} {"base_sha": "f1cb1fdb21be680df68bde086d8abad73cc22651", "cohort": null, "context": {"canonical_pr_url": "https://github.com/kdlbs/kandev/pull/934", "id": "108294290859338d3c3c4da78a7537d8d039966b4c0dd370f7e4e179466ae8f7", "preparation_mode": "source-only", "snapshot": {"base_ref": "f1cb1fdb21be680df68bde086d8abad73cc22651", "base_sha": "f1cb1fdb21be680df68bde086d8abad73cc22651", "body": "", "head_ref": "73f63ae83783f73ecc24e7523496bac37a811451", "head_sha": "73f63ae83783f73ecc24e7523496bac37a811451", "name": "kandev", "number": 934, "owner": "kdlbs", "pr_url": "https://github.com/kdlbs/kandev/pull/934", "title": ""}}, "head_sha": "73f63ae83783f73ecc24e7523496bac37a811451", "metadata": {"group_id": "7f81bcab28cb456bc9803a88b45617dd0a9d6c9e383b74ba85cec3572a1bb09f", "snapshot": {"base_sha": "f1cb1fdb21be680df68bde086d8abad73cc22651", "external_requirements": [], "head_sha": "73f63ae83783f73ecc24e7523496bac37a811451", "objects": 4257, "objects_sha256": "fd55f9feb2708db4a09f81796e3546cb35e968f57aeeab4b38488c2e192bbec7", "patch_sha256": "cc388563bd7fe957326a76ba11c8834b94cb3f5ef315e321277260f658c622b8"}}, "pr_number": 934, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "31a31edfbe45", "description": "Cmd/Ctrl+Enter in the custom-answer input called both the per-question commit and final submission. Because the draft was already recorded on change, the commit could unnecessarily advance the carousel on a non-final step and race with bundle submission.", "file_path": "apps/web/components/task/chat/clarification-overlay-parts.tsx"}, {"action_id": "A2", "action_type": "improvement", "category": "performance", "commit_sha": "31a31edfbe45", "description": "The submit callback depended on the entire clarification group object, which was recreated on each render; live-recording a keystroke therefore recreated the callback unnecessarily.", "file_path": "apps/web/components/task/chat/clarification-input-overlay.tsx"}, {"action_id": "A3", "action_type": "improvement", "category": "other", "commit_sha": "31a31edfbe45", "description": "The concurrent-submission guard lacked a direct test: the existing 409 round-trip test did not verify that two simultaneous submitCollected calls produce only one POST.", "file_path": "apps/web/hooks/domains/session/use-clarification-group.test.ts"}], "commits_under_review": [{"author": "zeval", "date": "2026-05-18T12:51:37Z", "files": [{"additions": 25, "deletions": 0, "filename": "apps/web/hooks/domains/session/use-clarification-group.test.ts", "patch": "@@ -77,6 +77,31 @@ describe(\"useClarificationGroup — derived state\", () => {\n expect(result.current.answeredCount).toBe(1);\n expect(fetchMock).not.toHaveBeenCalled();\n });\n+\n+ it(\"clearAnswer removes the entry and decrements answeredCount\", async () => {\n+ const msgs = [\n+ clarMessage({ id: \"m1\", pendingId: \"p1\", questionId: \"q1\", index: 0, total: 2 }),\n+ clarMessage({ id: \"m2\", pendingId: \"p1\", questionId: \"q2\", index: 1, total: 2 }),\n+ ];\n+ const { result } = renderHook(() => useClarificationGroup(msgs));\n+\n+ await act(async () => {\n+ result.current.recordAnswer(\"q1\", { question_id: \"q1\", custom_text: \"draft\" });\n+ });\n+ expect(result.current.answeredCount).toBe(1);\n+\n+ await act(async () => {\n+ result.current.clearAnswer(\"q1\");\n+ });\n+ expect(result.current.answers[\"q1\"]).toBeUndefined();\n+ expect(result.current.answeredCount).toBe(0);\n+\n+ // Clearing a question that was never recorded is a no-op.\n+ await act(async () => {\n+ result.current.clearAnswer(\"q-missing\");\n+ });\n+ expect(result.current.answeredCount).toBe(0);\n+ });\n });\n \n describe(\"useClarificationGroup — submit + skip\", () => {", "status": "modified"}, {"additions": 24, "deletions": 0, "filename": "apps/web/hooks/domains/session/use-clarification-group.ts", "patch": "@@ -13,6 +13,7 @@ export type ClarificationGroupApi = {\n answers: Record;\n submitState: SubmitState;\n recordAnswer: (questionId: string, answer: ClarificationAnswer) => void;\n+ clearAnswer: (questionId: string) => void;\n // Submits every recorded answer in a single batch. An optional `override`\n // map is merged into the current answers right before the POST so callers\n // can safely auto-submit immediately after recording an answer (the React\n@@ -88,6 +89,11 @@ export function useClarificationGroup(\n answersRef.current = answers;\n }, [answers]);\n const [submitState, setSubmitState] = useState(\"idle\");\n+ // Re-entry guard: multiple submit paths can race (Cmd+Enter inside the\n+ // custom input fires both the input's onSubmit and onRequestFinalSubmit;\n+ // a double-click on the Submit button can also race). The hook owns the\n+ // guarantee that only one POST is in flight at a time.\n+ const inflightRef = useRef(false);\n \n const pendingId = useMemo(() => {\n if (!messages || messages.length === 0) return null;\n@@ -106,12 +112,23 @@ export function useClarificationGroup(\n setAnswers((prev) => ({ ...prev, [questionId]: answer }));\n }, []);\n \n+ const clearAnswer = useCallback((questionId: string) => {\n+ setAnswers((prev) => {\n+ if (!(questionId in prev)) return prev;\n+ const next = { ...prev };\n+ delete next[questionId];\n+ return next;\n+ });\n+ }, []);\n+\n const submitCollected = useCallback(\n async (override?: Record) => {\n if (!pendingId) return;\n+ if (inflightRef.current) return;\n const current = { ...answersRef.current, ...(override ?? {}) };\n const haveAll = questionIds.every((id) => Boolean(current[id]));\n if (!haveAll) return;\n+ inflightRef.current = true;\n setSubmitState(\"submitting\");\n const ordered = questionIds\n .map((id) => current[id])\n@@ -121,6 +138,8 @@ export function useClarificationGroup(\n } catch (err) {\n console.error(\"Clarification submit threw:\", err);\n setSubmitState(\"error\");\n+ } finally {\n+ inflightRef.current = false;\n }\n },\n [pendingId, questionIds],\n@@ -129,12 +148,16 @@ export function useClarificationGroup(\n const skipAll = useCallback(\n async (reason?: string) => {\n if (!pendingId) return;\n+ if (inflightRef.current) return;\n+ inflightRef.current = true;\n setSubmitState(\"submitting\");\n try {\n setSubmitState(await postClarificationSkip(pendingId, reason ?? \"User skipped\"));\n } catch (err) {\n console.error(\"Clarification skip threw:\", err);\n setSubmitState(\"error\");\n+ } finally {\n+ inflightRef.current = false;\n }\n },\n [pendingId],\n@@ -147,6 +170,7 @@ export function useClarificationGroup(\n answers,\n submitState,\n recordAnswer,\n+ clearAnswer,\n submitCollected,\n skipAll,\n };", "status": "modified"}], "message": "feat(web): add clearAnswer + submit re-entry guard to useClarificationGroup\n\nclearAnswer removes a stored answer so emptying a clarification draft can\nrevert the stepper to \"unanswered\". A small inflight ref in submitCollected\n/ skipAll prevents duplicate POSTs when multiple submit paths race (e.g.\nCmd+Enter inside the custom input commits the draft and also asks the\nparent to finalize the batch).", "sha": "162a3141e20fc58bd6853bab24f97cc8167d2a12"}, {"author": "zeval", "date": "2026-05-18T12:51:49Z", "files": [{"additions": 133, "deletions": 39, "filename": "apps/web/components/task/chat/clarification-input-overlay.tsx", "patch": "@@ -59,11 +59,13 @@ type CardProps = {\n selectedOption: string | null;\n customCommittedText: string | null;\n customDraft: string;\n+ customActive: boolean;\n isSubmitting: boolean;\n showAgentDisconnected: boolean;\n onSelectOption: (optionId: string) => void;\n onCustomDraftChange: (text: string) => void;\n onSubmitCustom: (text: string) => void;\n+ onRequestFinalSubmit: () => void;\n };\n \n function ClarificationCard(props: CardProps) {\n@@ -74,11 +76,13 @@ function ClarificationCard(props: CardProps) {\n selectedOption,\n customCommittedText,\n customDraft,\n+ customActive,\n isSubmitting,\n showAgentDisconnected,\n onSelectOption,\n onCustomDraftChange,\n onSubmitCustom,\n+ onRequestFinalSubmit,\n } = props;\n const { question, metadata } = meta;\n return (\n@@ -111,6 +115,7 @@ function ClarificationCard(props: CardProps) {\n options={question.options}\n selectedOption={selectedOption}\n isSubmitting={isSubmitting}\n+ customActive={customActive}\n onSelectOption={onSelectOption}\n />\n {showAgentDisconnected && (\n@@ -126,8 +131,10 @@ function ClarificationCard(props: CardProps) {\n draft={customDraft}\n isSubmitting={isSubmitting}\n committedText={customCommittedText}\n+ active={customActive}\n onChange={onCustomDraftChange}\n onSubmit={onSubmitCustom}\n+ onRequestFinalSubmit={onRequestFinalSubmit}\n />\n
\n );\n@@ -172,12 +179,29 @@ function shouldIgnoreShortcut(e: KeyboardEvent): boolean {\n return e.metaKey || e.ctrlKey || e.altKey || e.shiftKey;\n }\n \n+// tryHandleMetaEnter returns true when the event was Cmd/Ctrl+Enter, so the\n+// caller can short-circuit. When focus is inside the custom-text input it\n+// returns true *without* invoking onSubmit — the input's own keydown handler\n+// owns that path and is responsible for committing the draft + final submit.\n+function tryHandleMetaEnter(e: KeyboardEvent, canSubmit: boolean, onSubmit: () => void): boolean {\n+ if (e.key !== \"Enter\" || e.shiftKey || e.altKey) return false;\n+ if (!e.metaKey && !e.ctrlKey) return false;\n+ const inEditable =\n+ e.target instanceof HTMLElement &&\n+ (e.target.tagName === \"INPUT\" || e.target.tagName === \"TEXTAREA\");\n+ if (inEditable) return true;\n+ e.preventDefault();\n+ if (canSubmit) onSubmit();\n+ return true;\n+}\n+\n function CarouselKeyboardShortcuts(args: CarouselShortcutArgs) {\n const optionsCount = args.meta.question.options.length;\n const isLast = args.activeIndex === args.total - 1;\n const { canSubmit, onPick, onPrev, onNext, onSkip, onSubmit } = args;\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n+ if (tryHandleMetaEnter(e, canSubmit, onSubmit)) return;\n if (shouldIgnoreShortcut(e)) return;\n if (e.key === \"Escape\") {\n e.preventDefault();\n@@ -216,6 +240,98 @@ type CarouselBodyProps = {\n setCustomDrafts: React.Dispatch>>;\n };\n \n+type QuestionHandlerCtx = {\n+ meta: SingleQuestionMeta;\n+ group: ReturnType;\n+ isSingleQuestion: boolean;\n+ activeIndex: number;\n+ total: number;\n+ setActiveIndex: (idx: number) => void;\n+ setCustomDrafts: React.Dispatch>>;\n+};\n+\n+type QuestionHandlers = {\n+ onSelectOption: (optionId: string) => void;\n+ onCustomDraftChange: (value: string) => void;\n+ onSubmitCustom: (text: string) => void;\n+};\n+\n+type SelectionState = {\n+ selectedOption: string | null;\n+ customCommittedText: string | null;\n+ draft: string;\n+ customActive: boolean;\n+};\n+\n+function deriveSelectionState(\n+ meta: SingleQuestionMeta,\n+ answers: Record,\n+ customDrafts: Record,\n+): SelectionState {\n+ const stored = answers[meta.questionId];\n+ const selected = stored?.selected_options ?? [];\n+ const selectedOption = selected.length > 0 ? selected[0] : null;\n+ const customCommittedText = stored?.custom_text ?? null;\n+ const draft = customDrafts[meta.questionId] ?? \"\";\n+ const hasCustomText = draft.trim().length > 0 || (customCommittedText?.length ?? 0) > 0;\n+ const customActive = !selectedOption && hasCustomText;\n+ return { selectedOption, customCommittedText, draft, customActive };\n+}\n+\n+function buildQuestionHandlers(ctx: QuestionHandlerCtx): QuestionHandlers {\n+ const { meta, group, isSingleQuestion, activeIndex, total, setActiveIndex, setCustomDrafts } =\n+ ctx;\n+\n+ // Records the answer, then auto-submits (single-question — uses the override\n+ // path because setState is async) or auto-advances to the next step.\n+ const commitAnswer = (answer: ClarificationAnswer) => {\n+ group.recordAnswer(meta.questionId, answer);\n+ if (isSingleQuestion) {\n+ void group.submitCollected({ [meta.questionId]: answer });\n+ return;\n+ }\n+ if (activeIndex < total - 1) setActiveIndex(activeIndex + 1);\n+ };\n+\n+ return {\n+ onSelectOption(optionId) {\n+ // Picking an option wipes any in-flight draft so the answer state and\n+ // the visible input agree (custom_text and selected_options are mutually\n+ // exclusive at commit time).\n+ setCustomDrafts((prev) => {\n+ if (!prev[meta.questionId]) return prev;\n+ return { ...prev, [meta.questionId]: \"\" };\n+ });\n+ commitAnswer({ question_id: meta.questionId, selected_options: [optionId] });\n+ },\n+ // Live-record the draft so the stepper updates and the custom input lights\n+ // up the moment the user types. Emptying the draft clears the answer so\n+ // allAnswered reverts to false. Enter/Cmd+Enter still drives advance/submit.\n+ onCustomDraftChange(value) {\n+ setCustomDrafts((prev) => ({ ...prev, [meta.questionId]: value }));\n+ const trimmed = value.trim();\n+ if (trimmed.length === 0) {\n+ group.clearAnswer(meta.questionId);\n+ return;\n+ }\n+ group.recordAnswer(meta.questionId, {\n+ question_id: meta.questionId,\n+ selected_options: [],\n+ custom_text: trimmed,\n+ });\n+ },\n+ onSubmitCustom(text) {\n+ const trimmed = text.trim();\n+ if (!trimmed) return;\n+ commitAnswer({\n+ question_id: meta.questionId,\n+ selected_options: [],\n+ custom_text: trimmed,\n+ });\n+ },\n+ };\n+}\n+\n function ClarificationCarouselBody({\n sortedMessages,\n group,\n@@ -231,7 +347,6 @@ function ClarificationCarouselBody({\n (m) => (m.metadata as ClarificationRequestMetadata | undefined)?.agent_disconnected === true,\n );\n const isSubmitting = group.submitState === \"submitting\";\n-\n const isSingleQuestion = total === 1;\n \n const allAnswered = sortedMessages.every((m) => {\n@@ -245,42 +360,21 @@ function ClarificationCarouselBody({\n \n if (!meta) return null;\n \n- const stored = group.answers[meta.questionId];\n- const selectedOption =\n- stored?.selected_options && stored.selected_options.length > 0\n- ? stored.selected_options[0]\n- : null;\n- const customCommittedText = stored?.custom_text ?? null;\n- const draft = customDrafts[meta.questionId] ?? \"\";\n-\n- // Records the new answer, then either auto-submits (single-question case\n- // takes the override path so the freshly recorded answer is included even\n- // though setState is async) or auto-advances to the next step.\n- const commitAnswer = (answer: ClarificationAnswer) => {\n- group.recordAnswer(meta.questionId, answer);\n- if (isSingleQuestion) {\n- void group.submitCollected({ [meta.questionId]: answer });\n- return;\n- }\n- if (activeIndex < total - 1) {\n- setActiveIndex(activeIndex + 1);\n- }\n- };\n+ const { selectedOption, customCommittedText, draft, customActive } = deriveSelectionState(\n+ meta,\n+ group.answers,\n+ customDrafts,\n+ );\n \n- const onSelectOption = (optionId: string) => {\n- commitAnswer({\n- question_id: meta.questionId,\n- selected_options: [optionId],\n- });\n- };\n- const onSubmitCustom = (text: string) => {\n- if (!text.trim()) return;\n- commitAnswer({\n- question_id: meta.questionId,\n- selected_options: [],\n- custom_text: text.trim(),\n- });\n- };\n+ const { onSelectOption, onCustomDraftChange, onSubmitCustom } = buildQuestionHandlers({\n+ meta,\n+ group,\n+ isSingleQuestion,\n+ activeIndex,\n+ total,\n+ setActiveIndex,\n+ setCustomDrafts,\n+ });\n \n return (\n <>\n@@ -291,13 +385,13 @@ function ClarificationCarouselBody({\n selectedOption={selectedOption}\n customCommittedText={customCommittedText}\n customDraft={draft}\n+ customActive={customActive}\n isSubmitting={isSubmitting}\n showAgentDisconnected={activeIndex === 0 && showAgentDisconnectedAtTop}\n onSelectOption={onSelectOption}\n- onCustomDraftChange={(value) =>\n- setCustomDrafts((prev) => ({ ...prev, [meta.questionId]: value }))\n- }\n+ onCustomDraftChange={onCustomDraftChange}\n onSubmitCustom={onSubmitCustom}\n+ onRequestFinalSubmit={handleSubmit}\n />\n {!isSingleQuestion && (\n void;\n };\n \n-// The agent receives both the selected option id and the custom text when\n-// both are present, so we never visually grey out one when the other is\n-// active — that previously created an asymmetric dimming bug where typing\n-// a custom answer dimmed the options but selecting an option did not dim\n-// the custom input.\n export function ClarificationOptions({\n options,\n selectedOption,\n isSubmitting,\n+ customActive,\n onSelectOption,\n }: OptionListProps) {\n return (\n
\n {options.map((option, idx) => {\n- const isSelected = selectedOption === option.option_id;\n+ const isSelected = !customActive && selectedOption === option.option_id;\n return (\n void;\n onSubmit: (text: string) => void;\n+ // Called after Cmd/Ctrl+Enter so the parent can attempt a batch submit\n+ // (no-op when not all questions are answered yet).\n+ onRequestFinalSubmit?: () => void;\n };\n \n export function ClarificationCustomInput({\n draft,\n isSubmitting,\n committedText,\n+ active,\n onChange,\n onSubmit,\n+ onRequestFinalSubmit,\n }: CustomInputProps) {\n return (\n-
\n- ↳\n+ \n+ \n+ ↳\n+ \n {\n- if (e.key === \"Enter\" && !e.shiftKey && draft.trim()) {\n+ if (e.key !== \"Enter\" || e.shiftKey || e.altKey) return;\n+ if (e.metaKey || e.ctrlKey) {\n+ e.preventDefault();\n+ if (draft.trim()) onSubmit(draft.trim());\n+ onRequestFinalSubmit?.();\n+ return;\n+ }\n+ if (draft.trim()) {\n e.preventDefault();\n onSubmit(draft.trim());\n }\n@@ -182,6 +212,7 @@ export function ClarificationCustomInput({\n \n Enter\n \n+ {active && }\n
\n );\n }", "status": "modified"}], "message": "feat(web): show selected state and Cmd+Enter submit on clarification custom input\n\nThe \"Or type a custom answer…\" input previously had no selected styling and\nneeded an Enter keypress before the carousel stepper marked the question as\nanswered, which made it easy to lose track of which path was the active\nanswer. Now:\n\n- Typing into the custom input live-records the draft, so the stepper and\n group progress update immediately and the input picks up the same blue\n ring + check icon used by selected options. When custom is active, any\n previously picked option visually deselects (they are mutually exclusive\n at commit time).\n- Picking an option after typing wipes that question's draft so the visible\n input and committed answer stay in sync.\n- Cmd/Ctrl+Enter submits the bundle when every question is answered — from\n inside the custom input (commits the draft then finalises) and from\n anywhere else in the overlay. Inside the input is handled locally so\n submitCollected does not fire twice.", "sha": "62fcfcfb9481c453b862e685841f146681f46d5e"}, {"author": "zeval", "date": "2026-05-18T12:51:58Z", "files": [{"additions": 5, "deletions": 0, "filename": "apps/web/e2e/pages/session-page.ts", "patch": "@@ -329,6 +329,11 @@ export class SessionPage {\n return this.clarificationQuestionCardById(questionId).getByTestId(\"clarification-input\");\n }\n \n+ /** Container around the custom text input — exposes data-active for selection state. */\n+ clarificationCustomInputContainerForQuestion(questionId: string): Locator {\n+ return this.clarificationQuestionCardById(questionId).getByTestId(\"clarification-custom-input\");\n+ }\n+\n /** Option button (by visible label text) inside a specific question card. */\n clarificationOptionForQuestion(questionId: string, text: string): Locator {\n return this.clarificationQuestionCardById(questionId)", "status": "modified"}, {"additions": 123, "deletions": 0, "filename": "apps/web/e2e/tests/chat/clarification.spec.ts", "patch": "@@ -473,4 +473,127 @@ test.describe(\"Multi-question clarification carousel\", () => {\n await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n await expect(session.clarificationPrev()).toBeDisabled();\n });\n+\n+ test(\"typing in the custom input auto-selects it and deselects the picked option\", async ({\n+ testPage,\n+ apiClient,\n+ seedData,\n+ }) => {\n+ const session = await seedClarificationTask(\n+ testPage,\n+ apiClient,\n+ seedData,\n+ \"Multi-q custom auto-selects\",\n+ \"clarification-multi\",\n+ );\n+\n+ await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n+\n+ // Pick an option on Q1 (auto-advances to Q2), then jump back to Q1.\n+ await session.clarificationOption(\"PostgreSQL\").click();\n+ await session.clarificationStep(0).click();\n+ const selectedBefore = session\n+ .clarificationQuestionCardById(\"db\")\n+ .locator('[data-testid=\"clarification-option\"][data-selected=\"true\"]');\n+ await expect(selectedBefore).toContainText(\"PostgreSQL\");\n+\n+ // Type into the custom input — it should light up and the option should\n+ // deselect, while the stepper keeps step 0 marked as answered.\n+ const input = session.clarificationInputForQuestion(\"db\");\n+ await input.click();\n+ await input.fill(\"Bespoke KV store\");\n+\n+ const customContainer = session.clarificationCustomInputContainerForQuestion(\"db\");\n+ await expect(customContainer).toHaveAttribute(\"data-active\", \"true\");\n+ await expect(\n+ session\n+ .clarificationQuestionCardById(\"db\")\n+ .locator('[data-testid=\"clarification-option\"][data-selected=\"true\"]'),\n+ ).toHaveCount(0);\n+ await expect(session.clarificationStep(0)).toHaveAttribute(\"data-answered\", \"true\");\n+ await expect(session.clarificationGroupProgress()).toContainText(\"1 of 3 answered\");\n+ });\n+\n+ test(\"emptying the custom draft clears the answer and reverts the stepper\", async ({\n+ testPage,\n+ apiClient,\n+ seedData,\n+ }) => {\n+ const session = await seedClarificationTask(\n+ testPage,\n+ apiClient,\n+ seedData,\n+ \"Multi-q draft clears answer\",\n+ \"clarification-multi\",\n+ );\n+\n+ await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n+\n+ const input = session.clarificationInputForQuestion(\"db\");\n+ await input.click();\n+ await input.fill(\"Bespoke KV store\");\n+ await expect(session.clarificationStep(0)).toHaveAttribute(\"data-answered\", \"true\");\n+ await expect(session.clarificationGroupProgress()).toContainText(\"1 of 3 answered\");\n+\n+ await input.fill(\"\");\n+ await expect(session.clarificationStep(0)).toHaveAttribute(\"data-answered\", \"false\");\n+ await expect(session.clarificationGroupProgress()).toContainText(\"0 of 3 answered\");\n+ await expect(session.clarificationCustomInputContainerForQuestion(\"db\")).toHaveAttribute(\n+ \"data-active\",\n+ \"false\",\n+ );\n+ });\n+\n+ test(\"Cmd+Enter from the last step's custom input submits the bundle\", async ({\n+ testPage,\n+ apiClient,\n+ seedData,\n+ }) => {\n+ const session = await seedClarificationTask(\n+ testPage,\n+ apiClient,\n+ seedData,\n+ \"Multi-q cmd+enter from input\",\n+ \"clarification-multi\",\n+ );\n+\n+ await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n+\n+ await session.clarificationOption(\"PostgreSQL\").click();\n+ await session.clarificationOption(\"Go\").click();\n+\n+ const deployInput = session.clarificationInputForQuestion(\"deploy\");\n+ await deployInput.click();\n+ await deployInput.fill(\"Nomad cluster\");\n+ await deployInput.press(\"ControlOrMeta+Enter\");\n+\n+ await expect(session.clarificationOverlay()).not.toBeVisible({ timeout: 30_000 });\n+ await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });\n+ await expect(session.chat).toContainText(\"Nomad cluster\");\n+ });\n+\n+ test(\"Cmd+Enter from outside the input submits when all questions are answered\", async ({\n+ testPage,\n+ apiClient,\n+ seedData,\n+ }) => {\n+ const session = await seedClarificationTask(\n+ testPage,\n+ apiClient,\n+ seedData,\n+ \"Multi-q cmd+enter global\",\n+ \"clarification-multi\",\n+ );\n+\n+ await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });\n+\n+ await session.clarificationOption(\"PostgreSQL\").click();\n+ await session.clarificationOption(\"Go\").click();\n+ await session.clarificationOption(\"Docker\").click();\n+\n+ // Focus is on the last option button, not the input.\n+ await testPage.keyboard.press(\"ControlOrMeta+Enter\");\n+ await expect(session.clarificationOverlay()).not.toBeVisible({ timeout: 30_000 });\n+ await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });\n+ });\n });", "status": "modified"}], "message": "test(web): cover live-record + Cmd+Enter clarification UX\n\nAdds four cases over the existing clarification-multi mock scenario:\ntyping auto-selects custom and deselects the option, emptying the draft\nreverts the stepper, Cmd+Enter from the last-step custom input submits\nthe bundle, and Cmd+Enter from outside the input submits when all answered.\nAdds a session-page locator for the new custom-input container so the\ndata-active attribute can be asserted.", "sha": "73f63ae83783f73ecc24e7523496bac37a811451"}], "post_review_commits": ["31a31edfbe4595d2709c89d3694d7f50fed04bb7"], "pr_author": "zeval", "pr_title": "feat(web): clearer custom-answer state and Cmd+Enter submit on clarifications", "repo_name": "kdlbs/kandev"}, "repo": "kdlbs/kandev", "snapshot": "snapshots/7f81bcab28cb456bc9803a88b45617dd0a9d6c9e383b74ba85cec3572a1bb09f.pack", "split": "rl", "task_id": "108294290859338d3c3c4da78a7537d8d039966b4c0dd370f7e4e179466ae8f7"} {"base_sha": "6f3dfab455aada9744fd2e849ee950069de3eacb", "cohort": null, "context": {"canonical_pr_url": "https://github.com/MetrolistGroup/Metrolist/pull/3695", "id": "1397a9524c0aecafff99affccf7ea62804093c7928f29af46254c51e422ed175", "preparation_mode": "source-only", "snapshot": {"base_ref": "6f3dfab455aada9744fd2e849ee950069de3eacb", "base_sha": "6f3dfab455aada9744fd2e849ee950069de3eacb", "body": "", "head_ref": "f0839633d9ab20ad846af4d8aa671302d0ac7d33", "head_sha": "f0839633d9ab20ad846af4d8aa671302d0ac7d33", "name": "Metrolist", "number": 3695, "owner": "MetrolistGroup", "pr_url": "https://github.com/MetrolistGroup/Metrolist/pull/3695", "title": ""}}, "head_sha": "f0839633d9ab20ad846af4d8aa671302d0ac7d33", "metadata": {"group_id": "328359f16e38a563598ccf5deb6e209ae24dde0164f52ad1292798abfbbeed7f", "snapshot": {"base_sha": "6f3dfab455aada9744fd2e849ee950069de3eacb", "external_requirements": [{"commit": "a48dda85eccd4afc366ad2f09f1ae56d526f44d2", "path": "metroproto", "snapshot": "6f3dfab455aada9744fd2e849ee950069de3eacb", "type": "submodule"}, {"commit": "a48dda85eccd4afc366ad2f09f1ae56d526f44d2", "path": "metroproto", "snapshot": "f0839633d9ab20ad846af4d8aa671302d0ac7d33", "type": "submodule"}], "head_sha": "f0839633d9ab20ad846af4d8aa671302d0ac7d33", "objects": 1379, "objects_sha256": "ccad5b0e05dd00a37554ebc8d43287f44860848de7fa74996349c46e6f471254", "patch_sha256": "4c1ffb0b74b66f228272e5d7c68f384597b93e6b7400ee38907cd916e1f94bac"}}, "pr_number": 3695, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "d26ce3a46056", "description": "Artist conjunction parsing was not initialized from the app's string resources, so localized conjunctions in YouTube Music responses could remain embedded in a single artist name.", "file_path": "app/src/main/kotlin/com/metrolist/music/App.kt"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "d26ce3a46056", "description": "An empty conjunction list produced a regex with an empty alternative, causing artist runs to split incorrectly instead of splitting only on supported separators.", "file_path": "innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "d26ce3a46056", "description": "Artists and authors without browse IDs remained unlinked because there was no search-based ID resolution for songs, albums, playlists, episodes, or podcasts.", "file_path": "innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "d26ce3a46056", "description": "Initial artist-item pages and their continuations displayed items before resolving missing artist IDs.", "file_path": "app/src/main/kotlin/com/metrolist/music/viewmodels/ArtistItemsViewModel.kt"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "d26ce3a46056", "description": "Artist-page sections displayed items before resolving missing artist IDs.", "file_path": "app/src/main/kotlin/com/metrolist/music/viewmodels/ArtistViewModel.kt"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "d26ce3a46056", "description": "Search summaries, filtered results, and continuation results displayed items before resolving missing artist IDs.", "file_path": "app/src/main/kotlin/com/metrolist/music/viewmodels/OnlineSearchViewModel.kt"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "9952f9ff2fa3", "description": "The conjunction list included words from multiple languages regardless of the active locale, risking splits of artist names on words that were not conjunctions in that locale.", "file_path": "app/src/main/kotlin/com/metrolist/music/App.kt"}, {"action_id": "A8", "action_type": "fix", "category": "bug", "commit_sha": "9952f9ff2fa3", "description": "Missing artist IDs were assigned from the first artist search result even when its name did not match, potentially linking an item to the wrong artist.", "file_path": "innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt"}, {"action_id": "A9", "action_type": "fix", "category": "bug", "commit_sha": "9952f9ff2fa3", "description": "Splitting artist runs on commas could incorrectly break comma-containing artist names into separate artists.", "file_path": "innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt"}, {"action_id": "A10", "action_type": "fix", "category": "bug", "commit_sha": "9952f9ff2fa3", "description": "Only the first part of a split run retained its navigation endpoint, leaving subsequent parsed artists without the available browse ID.", "file_path": "innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt"}, {"action_id": "A11", "action_type": "fix", "category": "bug", "commit_sha": "9952f9ff2fa3", "description": "The metadata-group cleanup decision inspected only the first run and treated any comma as an artist signal, so it could retain non-artist metadata or discard a group with artist signals in later runs.", "file_path": "innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt"}, {"action_id": "A12", "action_type": "fix", "category": "bug", "commit_sha": "9952f9ff2fa3", "description": "When video artist runs had no browse endpoints, the artist-items parser kept only the first artist and discarded the other parsed names.", "file_path": "innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistItemsPage.kt"}, {"action_id": "A13", "action_type": "fix", "category": "bug", "commit_sha": "9952f9ff2fa3", "description": "When video artist runs had no browse endpoints, the artist-page parser kept only the first artist and discarded the other parsed names.", "file_path": "innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistPage.kt"}], "commits_under_review": [{"author": "kairosci", "date": "2026-05-03T11:46:35Z", "files": [{"additions": 24, "deletions": 0, "filename": "innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt", "patch": "@@ -28,6 +28,30 @@ fun List.splitBySeparator(): List> {\n return res\n }\n \n+/**\n+ * Splits artist runs by conjunction separators (&, ,) to properly handle\n+ * cases where multiple artists are displayed as \"Artist1 & Artist2\" or \"Artist1, Artist2\"\n+ */\n+fun List.splitArtistsByConjunction(): List {\n+ val result = mutableListOf()\n+ forEach { run ->\n+ val text = run.text\n+ // Check if this run contains conjunction patterns\n+ if (text.contains(\" & \") || text.contains(\", \")) {\n+ // Split by both patterns and preserve navigationEndpoint if present\n+ val parts = text.split(Regex(\" & |, \"))\n+ parts.forEachIndexed { index, part ->\n+ if (part.isNotBlank()) {\n+ result.add(Run(part.trim(), if (index == 0) run.navigationEndpoint else null))\n+ }\n+ }\n+ } else {\n+ result.add(run)\n+ }\n+ }\n+ return result\n+}\n+\n fun List>.clean(): List> =\n if (getOrNull(0)?.getOrNull(0)?.navigationEndpoint != null ||\n (getOrNull(0)?.getOrNull(0)?.text?.contains(regex = Regex(\"[&,]\"))) != false", "status": "modified"}, {"additions": 43, "deletions": 25, "filename": "innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistItemsPage.kt", "patch": "@@ -9,6 +9,7 @@ import com.metrolist.innertube.models.PlaylistItem\n import com.metrolist.innertube.models.SongItem\n import com.metrolist.innertube.models.YTItem\n import com.metrolist.innertube.models.oddElements\n+import com.metrolist.innertube.models.splitArtistsByConjunction\n import com.metrolist.innertube.models.splitBySeparator\n import com.metrolist.innertube.utils.parseTime\n \n@@ -20,20 +21,21 @@ data class ArtistItemsPage(\n companion object {\n fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): SongItem? {\n // Split the secondary line by bullet separator to separate artists from other metadata (like views)\n- val secondaryLineRuns = renderer.flexColumns\n+ val artistRuns = renderer.flexColumns\n .getOrNull(1)\n ?.musicResponsiveListItemFlexColumnRenderer\n ?.text\n ?.runs\n ?.splitBySeparator()\n-\n- // Extract artists from the first segment after splitting\n- val artists = secondaryLineRuns?.firstOrNull()?.oddElements()?.map {\n- Artist(\n- name = it.text,\n- id = it.navigationEndpoint?.browseEndpoint?.browseId\n- )\n- }\n+ ?.getOrNull(0)\n+ ?.splitArtistsByConjunction()\n+ ?.filter { it.text.isNotBlank() && it.text != \"&\" && it.text != \",\" }\n+ ?.map { run ->\n+ Artist(\n+ name = run.text.trim(),\n+ id = run.navigationEndpoint?.browseEndpoint?.browseId\n+ )\n+ }\n \n // Extract album from last flexColumn (like SimpMusic does)\n val album = renderer.flexColumns.lastOrNull()\n@@ -55,7 +57,7 @@ data class ArtistItemsPage(\n title = renderer.flexColumns.firstOrNull()\n ?.musicResponsiveListItemFlexColumnRenderer?.text\n ?.runs?.firstOrNull()?.text ?: return null,\n- artists = artists ?: return null,\n+ artists = artistRuns ?: return null,\n album = album,\n duration = renderer.fixedColumns?.firstOrNull()\n ?.musicResponsiveListItemFlexColumnRenderer?.text\n@@ -89,21 +91,37 @@ data class ArtistItemsPage(\n } != null\n )\n // Video\n- renderer.isSong -> SongItem(\n- id = renderer.navigationEndpoint.watchEndpoint?.videoId ?: return null,\n- title = renderer.title.runs?.firstOrNull()?.text ?: return null,\n- artists = renderer.subtitle?.runs?.splitBySeparator()?.firstOrNull()?.oddElements()?.map {\n- Artist(\n- name = it.text,\n- id = it.navigationEndpoint?.browseEndpoint?.browseId\n- )\n- } ?: return null,\n- album = null,\n- duration = null,\n- musicVideoType = renderer.musicVideoType,\n- thumbnail = renderer.thumbnailRenderer.musicThumbnailRenderer?.getThumbnailUrl() ?: return null,\n- endpoint = renderer.navigationEndpoint.watchEndpoint\n- )\n+ renderer.isSong -> {\n+ val subtitleRuns = renderer.subtitle?.runs ?: return null\n+ // Split any runs that contain conjunctions (&, ,) to properly extract individual artists\n+ val expandedRuns = subtitleRuns.splitArtistsByConjunction()\n+ // Filter out separator runs (like \"&\", \",\") to get only artist runs\n+ val artistRuns = expandedRuns.filter { \n+ it.text.isNotBlank() && it.text != \"&\" && it.text != \",\" \n+ }\n+ SongItem(\n+ id = renderer.navigationEndpoint.watchEndpoint?.videoId ?: return null,\n+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,\n+ artists = artistRuns.filter { \n+ it.navigationEndpoint?.browseEndpoint?.browseId?.startsWith(\"UC\") == true ||\n+ it.navigationEndpoint?.browseEndpoint != null\n+ }.map {\n+ Artist(\n+ name = it.text.trim(),\n+ id = it.navigationEndpoint?.browseEndpoint?.browseId\n+ )\n+ }.ifEmpty {\n+ artistRuns.firstOrNull()?.let { \n+ listOf(Artist(name = it.text.trim(), id = null)) \n+ } ?: emptyList()\n+ },\n+ album = null,\n+ duration = null,\n+ musicVideoType = renderer.musicVideoType,\n+ thumbnail = renderer.thumbnailRenderer.musicThumbnailRenderer?.getThumbnailUrl() ?: return null,\n+ endpoint = renderer.navigationEndpoint.watchEndpoint\n+ )\n+ }\n renderer.isPlaylist -> PlaylistItem(\n id = renderer.navigationEndpoint.browseEndpoint?.browseId?.removePrefix(\"VL\") ?: return null,\n title = renderer.title.runs?.firstOrNull()?.text ?: return null,", "status": "modified"}, {"additions": 23, "deletions": 15, "filename": "innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistPage.kt", "patch": "@@ -20,6 +20,7 @@ import com.metrolist.innertube.models.YTItem\n import com.metrolist.innertube.models.filterExplicit\n import com.metrolist.innertube.models.getItems\n import com.metrolist.innertube.models.oddElements\n+import com.metrolist.innertube.models.splitArtistsByConjunction\n import com.metrolist.innertube.models.splitBySeparator\n \n data class ArtistSection(\n@@ -72,20 +73,21 @@ data class ArtistPage(\n \n private fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): SongItem? {\n // Split the secondary line by bullet separator to separate artists from other metadata (like views)\n- val secondaryLineRuns = renderer.flexColumns\n+ val artistRuns = renderer.flexColumns\n .getOrNull(1)\n ?.musicResponsiveListItemFlexColumnRenderer\n ?.text\n ?.runs\n ?.splitBySeparator()\n-\n- // Extract artists from the first segment after splitting\n- val artists = secondaryLineRuns?.firstOrNull()?.oddElements()?.map {\n- Artist(\n- name = it.text,\n- id = it.navigationEndpoint?.browseEndpoint?.browseId\n- )\n- }\n+ ?.getOrNull(0)\n+ ?.splitArtistsByConjunction()\n+ ?.filter { it.text.isNotBlank() && it.text != \"&\" && it.text != \",\" }\n+ ?.map { run ->\n+ Artist(\n+ name = run.text.trim(),\n+ id = run.navigationEndpoint?.browseEndpoint?.browseId\n+ )\n+ }\n \n // Extract album from last flexColumn (like SimpMusic)\n val album = renderer.flexColumns.lastOrNull()\n@@ -107,7 +109,7 @@ data class ArtistPage(\n title = renderer.flexColumns.firstOrNull()\n ?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()\n ?.text ?: return null,\n- artists = artists ?: return null,\n+ artists = artistRuns ?: return null,\n album = album,\n duration = null,\n musicVideoType = renderer.musicVideoType,\n@@ -125,21 +127,27 @@ data class ArtistPage(\n private fun fromMusicTwoRowItemRenderer(renderer: MusicTwoRowItemRenderer): YTItem? {\n return when {\n renderer.isSong -> {\n- val subtitleRuns = renderer.subtitle?.runs?.oddElements() ?: return null\n+ val subtitleRuns = renderer.subtitle?.runs ?: return null\n+ // Split any runs that contain conjunctions (&, ,) to properly extract individual artists\n+ val expandedRuns = subtitleRuns.splitArtistsByConjunction()\n+ // Filter out separator runs (like \"&\", \",\") to get only artist runs\n+ val artistRuns = expandedRuns.filter { \n+ it.text.isNotBlank() && it.text != \"&\" && it.text != \",\" \n+ }\n SongItem(\n id = renderer.navigationEndpoint.watchEndpoint?.videoId ?: return null,\n title = renderer.title.runs?.firstOrNull()?.text ?: return null,\n- artists = subtitleRuns.filter { \n+ artists = artistRuns.filter { \n it.navigationEndpoint?.browseEndpoint?.browseId?.startsWith(\"UC\") == true ||\n it.navigationEndpoint?.browseEndpoint != null\n }.map {\n Artist(\n- name = it.text,\n+ name = it.text.trim(),\n id = it.navigationEndpoint?.browseEndpoint?.browseId\n )\n }.ifEmpty {\n- subtitleRuns.firstOrNull()?.let { \n- listOf(Artist(name = it.text, id = null)) \n+ artistRuns.firstOrNull()?.let { \n+ listOf(Artist(name = it.text.trim(), id = null)) \n } ?: emptyList()\n },\n album = null,", "status": "modified"}, {"additions": 12, "deletions": 9, "filename": "innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchSuggestionPage.kt", "patch": "@@ -12,6 +12,7 @@ import com.metrolist.innertube.models.SongItem\n import com.metrolist.innertube.models.YTItem\n import com.metrolist.innertube.models.clean\n import com.metrolist.innertube.models.oddElements\n+import com.metrolist.innertube.models.splitArtistsByConjunction\n import com.metrolist.innertube.models.splitBySeparator\n import com.metrolist.innertube.utils.parseTime\n \n@@ -159,6 +160,11 @@ object SearchSuggestionPage {\n ?.runs\n ?.splitBySeparator()\n ?.clean()\n+ // Split artist runs by conjunction to handle \"Artist1 & Artist2\" cases\n+ val artistRuns = secondaryLine\n+ ?.firstOrNull()\n+ ?.splitArtistsByConjunction()\n+ ?.filter { it.text.isNotBlank() && it.text != \"&\" && it.text != \",\" }\n SongItem(\n id = renderer.playlistItemData?.videoId ?: return null,\n title =\n@@ -170,15 +176,12 @@ object SearchSuggestionPage {\n ?.firstOrNull()\n ?.text ?: return null,\n artists =\n- secondaryLine\n- ?.firstOrNull()\n- ?.oddElements()\n- ?.map {\n- Artist(\n- name = it.text,\n- id = it.navigationEndpoint?.browseEndpoint?.browseId,\n- )\n- } ?: return null,\n+ artistRuns?.map { run ->\n+ Artist(\n+ name = run.text.trim(),\n+ id = run.navigationEndpoint?.browseEndpoint?.browseId,\n+ )\n+ } ?: return null,\n album =\n renderer.flexColumns\n .getOrNull(", "status": "modified"}, {"additions": 8, "deletions": 3, "filename": "innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchSummaryPage.kt", "patch": "@@ -19,6 +19,7 @@ import com.metrolist.innertube.models.filterExplicit\n import com.metrolist.innertube.models.filterVideoSongs\n import com.metrolist.innertube.models.filterYoutubeShorts\n import com.metrolist.innertube.models.oddElements\n+import com.metrolist.innertube.models.splitArtistsByConjunction\n import com.metrolist.innertube.models.splitBySeparator\n import com.metrolist.innertube.utils.parseTime\n \n@@ -324,6 +325,10 @@ data class SearchSummaryPage(\n ?: emptyList()\n val listRun = (secondaryLine + thirdLine).clean()\n \n+ // Split artist runs by conjunction to handle \"Artist1 & Artist2\" cases\n+ val artistRuns = listRun.getOrNull(0)?.splitArtistsByConjunction()\n+ ?.filter { it.text.isNotBlank() && it.text != \"&\" && it.text != \",\" }\n+\n SongItem(\n id = renderer.playlistItemData?.videoId ?: return null,\n title =\n@@ -334,10 +339,10 @@ data class SearchSummaryPage(\n ?.runs\n ?.firstOrNull()\n ?.text ?: return null,\n- artists = listRun.getOrNull(0)?.oddElements()?.map {\n+ artists = artistRuns?.map { run ->\n Artist(\n- name = it.text,\n- id = it.navigationEndpoint?.browseEndpoint?.browseId\n+ name = run.text.trim(),\n+ id = run.navigationEndpoint?.browseEndpoint?.browseId\n )\n } ?: return null,\n album = listRun.getOrNull(1)?.firstOrNull()?.takeIf { it.navigationEndpoint?.browseEndpoint != null }?.let {", "status": "modified"}], "message": "fix(artists): properly handle artist conjunctions in YouTube Music API responses\n\n- Add splitArtistsByConjunction() function to Runs.kt to handle & and , separators in artist names\n- Fix ArtistPage.kt to properly parse artists from MusicResponsiveListItemRenderer and MusicTwoRowItemRenderer\n- Fix ArtistItemsPage.kt to properly parse artists from both renderer types\n- Fix SearchSummaryPage.kt and SearchSuggestionPage.kt to handle artist conjunctions\n- This resolves issues where songs appeared under wrong artists, artists had conjunction symbols in their names, and single-song artist pages were created incorrectly\n\nThe changes ensure that when YouTube Music returns \"Artist1 & Artist2\" or \"Artist1, Artist2\", each artist is properly extracted and associated with the song.", "sha": "82187a8a4bde235fa9f525f0be0c00a19747982d"}, {"author": "kairosci", "date": "2026-05-03T11:52:32Z", "files": [{"additions": 3, "deletions": 8, "filename": "innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt", "patch": "@@ -28,18 +28,13 @@ fun List.splitBySeparator(): List> {\n return res\n }\n \n-/**\n- * Splits artist runs by conjunction separators (&, ,) to properly handle\n- * cases where multiple artists are displayed as \"Artist1 & Artist2\" or \"Artist1, Artist2\"\n- */\n fun List.splitArtistsByConjunction(): List {\n val result = mutableListOf()\n forEach { run ->\n val text = run.text\n- // Check if this run contains conjunction patterns\n- if (text.contains(\" & \") || text.contains(\", \")) {\n- // Split by both patterns and preserve navigationEndpoint if present\n- val parts = text.split(Regex(\" & |, \"))\n+ val conjunctionPattern = Regex(\" & |, | \\\\band\\\\b| \\\\be\\\\b| \\\\by\\\\b| \\\\bet\\\\b| \\\\und\\\\b| \\\\bи\\\\b| \\\\bと\\\\b| \\\\b와\\\\b\")\n+ if (text.contains(conjunctionPattern)) {\n+ val parts = text.split(conjunctionPattern)\n parts.forEachIndexed { index, part ->\n if (part.isNotBlank()) {\n result.add(Run(part.trim(), if (index == 0) run.navigationEndpoint else null))", "status": "modified"}, {"additions": 0, "deletions": 3, "filename": "innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistPage.kt", "patch": "@@ -72,7 +72,6 @@ data class ArtistPage(\n }\n \n private fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): SongItem? {\n- // Split the secondary line by bullet separator to separate artists from other metadata (like views)\n val artistRuns = renderer.flexColumns\n .getOrNull(1)\n ?.musicResponsiveListItemFlexColumnRenderer\n@@ -89,7 +88,6 @@ data class ArtistPage(\n )\n }\n \n- // Extract album from last flexColumn (like SimpMusic)\n val album = renderer.flexColumns.lastOrNull()\n ?.musicResponsiveListItemFlexColumnRenderer?.text?.runs\n ?.firstOrNull()?.let {\n@@ -101,7 +99,6 @@ data class ArtistPage(\n } else null\n }\n \n- // Extract library tokens using the new method that properly handles multiple toggle items\n val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)\n \n return SongItem(", "status": "modified"}], "message": "refactor: remove unnecessary comments from artist parsing code", "sha": "4598adc20d77cf96ae5eea175dd03ebd890162ec"}, {"author": "kairosci", "date": "2026-05-03T11:56:13Z", "files": [{"additions": 3, "deletions": 0, "filename": "app/src/main/res/values/metrolist_strings.xml", "patch": "@@ -27,6 +27,9 @@\n Sync playlist\n Sync disabled\n NOTE: This option enables syncing with YouTube Music and CANNOT be changed later\n+\n+ \n+ and\n Generating image…\n Please wait\n Cancel", "status": "modified"}], "message": "feat(strings): add conjunction_and string for artist parsing\n\nAdd localized string for 'and' conjunction to support internationalized artist name parsing.", "sha": "bdc8f9732180c1d65793f2f02f7317304876fe7e"}, {"author": "kairosci", "date": "2026-05-03T11:58:05Z", "files": [{"additions": 1, "deletions": 1, "filename": "innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt", "patch": "@@ -32,7 +32,7 @@ fun List.splitArtistsByConjunction(): List {\n val result = mutableListOf()\n forEach { run ->\n val text = run.text\n- val conjunctionPattern = Regex(\" & |, | \\\\band\\\\b| \\\\be\\\\b| \\\\by\\\\b| \\\\bet\\\\b| \\\\und\\\\b| \\\\bи\\\\b| \\\\bと\\\\b| \\\\b와\\\\b\")\n+ val conjunctionPattern = Regex(\" & |, | \\\\band\\\\b\")\n if (text.contains(conjunctionPattern)) {\n val parts = text.split(conjunctionPattern)\n parts.forEachIndexed { index, part ->", "status": "modified"}], "message": "fix(artists): use only 'and' conjunction for now\n\nRevert to using only 'and' (via \\band\\b regex) for artist name\nparsing. The localized conjunction strings in metrolist_strings.xml\nwill be used later for full internationalization.", "sha": "2e91b6a572cd0fb4a9a3263f4af8f4c5daf7e233"}, {"author": "kairosci", "date": "2026-05-03T12:00:29Z", "files": [{"additions": 6, "deletions": 1, "filename": "innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt", "patch": "@@ -30,9 +30,10 @@ fun List.splitBySeparator(): List> {\n \n fun List.splitArtistsByConjunction(): List {\n val result = mutableListOf()\n+ val pattern = ArtistConjunctions.conjunctions.joinToString(\"|\") { Regex.escape(it) }\n+ val conjunctionPattern = Regex(\" $pattern |, | & \")\n forEach { run ->\n val text = run.text\n- val conjunctionPattern = Regex(\" & |, | \\\\band\\\\b\")\n if (text.contains(conjunctionPattern)) {\n val parts = text.split(conjunctionPattern)\n parts.forEachIndexed { index, part ->\n@@ -47,6 +48,10 @@ fun List.splitArtistsByConjunction(): List {\n return result\n }\n \n+object ArtistConjunctions {\n+ var conjunctions: List = listOf(\"and\")\n+}\n+\n fun List>.clean(): List> =\n if (getOrNull(0)?.getOrNull(0)?.navigationEndpoint != null ||\n (getOrNull(0)?.getOrNull(0)?.text?.contains(regex = Regex(\"[&,]\"))) != false", "status": "modified"}], "message": "feat(artists): make conjunction patterns configurable via ArtistConjunctions\n\n- ArtistConjunctions object holds the list of conjunction words\n- splitArtistsByConjunction() now uses ArtistConjunctions.conjunctions\n- App module can now set ArtistConjunctions.conjunctions with\n localized strings from metrolist_strings.xml at startup", "sha": "f0839633d9ab20ad846af4d8aa671302d0ac7d33"}], "post_review_commits": ["d26ce3a460567ad023c1ea1f45caf0a08e2c75cc", "9952f9ff2fa3fb3b3fe358461e367b748643ed14"], "pr_author": "kairosci", "pr_title": "fix(artists): properly handle artist conjunctions in YouTube Music API responses", "repo_name": "MetrolistGroup/Metrolist"}, "repo": "MetrolistGroup/Metrolist", "snapshot": "snapshots/328359f16e38a563598ccf5deb6e209ae24dde0164f52ad1292798abfbbeed7f.pack", "split": "rl", "task_id": "1397a9524c0aecafff99affccf7ea62804093c7928f29af46254c51e422ed175"} {"base_sha": "5dd0364f0b329c71319fda4f07f54fb9b010dbab", "cohort": null, "context": {"canonical_pr_url": "https://github.com/EtanHey/cmuxlayer/pull/724", "id": "1a235cbe31d5d0b88cc220ea824873e24e956bf774172f75392e9f3ab25571ed", "preparation_mode": "source-only", "snapshot": {"base_ref": "5dd0364f0b329c71319fda4f07f54fb9b010dbab", "base_sha": "5dd0364f0b329c71319fda4f07f54fb9b010dbab", "body": "", "head_ref": "52b98a60e30361379bb3562f899bf48ad36d1acf", "head_sha": "52b98a60e30361379bb3562f899bf48ad36d1acf", "name": "cmuxlayer", "number": 724, "owner": "EtanHey", "pr_url": "https://github.com/EtanHey/cmuxlayer/pull/724", "title": ""}}, "head_sha": "52b98a60e30361379bb3562f899bf48ad36d1acf", "metadata": {"group_id": "3f4aa481c92338c1e6f0cf3e3778651152d3421722af72b05f363debbb37bb68", "snapshot": {"base_sha": "5dd0364f0b329c71319fda4f07f54fb9b010dbab", "external_requirements": [], "head_sha": "52b98a60e30361379bb3562f899bf48ad36d1acf", "objects": 588, "objects_sha256": "87265d71e562271d09a97645744b35253e19116a48d5afefd4817f8f63182e23", "patch_sha256": "9352508ea22a9a781027147229fcebee556164e435fc791c3afe5c1d76d06411"}}, "pr_number": 724, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "d9c9aae62651", "description": "Claude pane model parsing discarded explicit context tiers such as “(1M context)” and “(200K context)”, preventing the reported tier from reaching model-mismatch detection.", "file_path": "src/screen-parser.ts"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "d9c9aae62651", "description": "Claude model comparison treated a requested context tier as a match when the pane reported no tier, instead of returning an unknown mismatch result.", "file_path": "src/agent-engine.ts"}], "commits_under_review": [{"author": "EtanHey", "date": "2026-09-23T06:16:09Z", "files": [{"additions": 37, "deletions": 1, "filename": "src/agent-engine.ts", "patch": "@@ -958,9 +958,29 @@ function toParsedScreenStatus(\n }\n }\n \n+/** Compare Claude's launcher ID and pane label using their shared model parts. */\n+function parseClaudeModelIdentity(model: string): {\n+ family: string;\n+ major: string | null;\n+ minor: string | null;\n+ context: string | null;\n+} | null {\n+ const match = model.match(\n+ /^(?:claude[-\\s]+)?(opus|sonnet|haiku)(?:[-\\s]+(\\d+)(?:[-.\\s]+(\\d+))?)?\\s*(?:\\[(\\d+(?:\\.\\d+)?[km])\\]|\\((\\d+(?:\\.\\d+)?[km])\\s+context\\))?$/i,\n+ );\n+ if (!match) return null;\n+ return {\n+ family: match[1].toLowerCase(),\n+ major: match[2] ?? null,\n+ minor: match[3] ?? null,\n+ context: (match[4] ?? match[5] ?? null)?.toLowerCase() ?? null,\n+ };\n+}\n+\n /**\n * Loosely compare the requested model with the model reported by the live CLI.\n- * A missing side is unknown rather than a match.\n+ * A missing side is unknown rather than a match. The pane can omit the context\n+ * tier, so only an explicit disagreement on both sides proves tier drift.\n */\n export function computeModelMismatch(\n requestedModel: string,\n@@ -969,6 +989,22 @@ export function computeModelMismatch(\n const requested = requestedModel.toLowerCase().trim();\n const parsed = parsedModel?.toLowerCase().trim();\n if (!requested || !parsed) return null;\n+ const requestedClaude = parseClaudeModelIdentity(requested);\n+ const parsedClaude = parseClaudeModelIdentity(parsed);\n+ if (requestedClaude && parsedClaude) {\n+ return (\n+ requestedClaude.family !== parsedClaude.family ||\n+ (requestedClaude.major !== null &&\n+ parsedClaude.major !== null &&\n+ requestedClaude.major !== parsedClaude.major) ||\n+ (requestedClaude.minor !== null &&\n+ parsedClaude.minor !== null &&\n+ requestedClaude.minor !== parsedClaude.minor) ||\n+ (requestedClaude.context !== null &&\n+ parsedClaude.context !== null &&\n+ requestedClaude.context !== parsedClaude.context)\n+ );\n+ }\n return !parsed.includes(requested) && !requested.includes(parsed);\n }\n ", "status": "modified"}, {"additions": 52, "deletions": 0, "filename": "tests/agent-engine.test.ts", "patch": "@@ -8708,6 +8708,58 @@ Session ID: ${sessionId}`,\n });\n });\n \n+ it(\"settles the live Claude Opus 5.5 1M banner as the requested registry model\", async () => {\n+ stateMgr.writeState(\n+ makeRecord({\n+ agent_id: \"agent-opus-1m\",\n+ state: \"booting\",\n+ surface_id: \"surface:opus-1m\",\n+ cli: \"claude\",\n+ model: \"claude-opus-5-5[1m]\",\n+ }),\n+ );\n+ liveSurfaces = [makeSurface(\"surface:opus-1m\")];\n+ (mockClient.readScreen as ReturnType).mockResolvedValue({\n+ surface: \"surface:opus-1m\",\n+ text: [\n+ \"Claude Code\",\n+ \"🤖 Opus 5.5 (1M context)\",\n+ \"❯\",\n+ \"⏵⏵ bypass permissions on\",\n+ ].join(\"\\n\"),\n+ lines: 80,\n+ scrollback_used: false,\n+ });\n+ await engine.getRegistry().reconstitute();\n+\n+ await engine.runSweep();\n+\n+ expect(engine.getAgentState(\"agent-opus-1m\")).toMatchObject({\n+ state: \"ready\",\n+ model: \"claude-opus-5-5[1m]\",\n+ parsed_model: \"Opus 5.5\",\n+ model_mismatch: false,\n+ });\n+ });\n+\n+ it(\"compares Claude ID and display aliases without hiding a real model drift\", () => {\n+ expect(\n+ computeModelMismatch(\n+ \"claude-opus-5-5[1m]\",\n+ \"Opus 5.5 (1M context)\",\n+ ),\n+ ).toBe(false);\n+ expect(\n+ computeModelMismatch(\"claude-opus-5-5[1m]\", \"Sonnet 5.5 (1M context)\"),\n+ ).toBe(true);\n+ expect(\n+ computeModelMismatch(\"claude-opus-5-5[1m]\", \"Opus 5.4 (1M context)\"),\n+ ).toBe(true);\n+ expect(\n+ computeModelMismatch(\"claude-opus-5-5[1m]\", \"Opus 5.5 (200K context)\"),\n+ ).toBe(true);\n+ });\n+\n it(\"leaves a fresh noninteractive boot record inside its boot window\", async () => {\n stateMgr.writeState(\n makeRecord({", "status": "modified"}], "message": "fix: normalize Claude model IDs against pane labels\n\nCo-Authored-By: cmuxlayerCodex-c37b0ffb running gpt-6-sol ", "sha": "52b98a60e30361379bb3562f899bf48ad36d1acf"}], "post_review_commits": ["d9c9aae62651ca0c5dc63028a10f7ae382053d01", "fc998640d240909d9bd97c5cde73371a3edad1ed"], "pr_author": "EtanHey", "pr_title": "fix: recognize Claude model ID and pane aliases", "repo_name": "EtanHey/cmuxlayer"}, "repo": "EtanHey/cmuxlayer", "snapshot": "snapshots/3f4aa481c92338c1e6f0cf3e3778651152d3421722af72b05f363debbb37bb68.pack", "split": "rl", "task_id": "1a235cbe31d5d0b88cc220ea824873e24e956bf774172f75392e9f3ab25571ed"} {"base_sha": "f9cc8c0098c5b94041a1567b26276c2f02221122", "cohort": null, "context": {"canonical_pr_url": "https://github.com/wave-av/wave-desktop/pull/5", "id": "1b090cc5a19905e619fd8fefc65cb295557aa82d130e91254c802c7143fe1e68", "preparation_mode": "source-only", "snapshot": {"base_ref": "f9cc8c0098c5b94041a1567b26276c2f02221122", "base_sha": "f9cc8c0098c5b94041a1567b26276c2f02221122", "body": "", "head_ref": "84786dc9cfd298458f06b74437e7f596f6c5d69d", "head_sha": "84786dc9cfd298458f06b74437e7f596f6c5d69d", "name": "wave-desktop", "number": 5, "owner": "wave-av", "pr_url": "https://github.com/wave-av/wave-desktop/pull/5", "title": ""}}, "head_sha": "84786dc9cfd298458f06b74437e7f596f6c5d69d", "metadata": {"group_id": "aca09a9cd9725bc2c2bf9fe6085a8a02b3ac668aac76ebf602b6efe666409d32", "snapshot": {"base_sha": "f9cc8c0098c5b94041a1567b26276c2f02221122", "external_requirements": [], "head_sha": "84786dc9cfd298458f06b74437e7f596f6c5d69d", "objects": 9, "objects_sha256": "7bcbd8f990dfd64cf0a536f6d3d224c49f61980db1433fad26b778329eeaa290", "patch_sha256": "19d9f9ac19b6230c7e22a0640bf95a8ecdf81348ea1cb2305d3ba6c20c985dcd"}}, "pr_number": 5, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "a35102b9bda5", "description": "The capability registry exposed Electron renderer-to-main IPC channels as HTTP APIs, even though they are intra-app implementation details rather than inter-product platform contracts.", "file_path": "capabilities.json"}], "commits_under_review": [{"author": "yakimoto", "date": "2026-06-01T19:47:13Z", "files": [{"additions": 33, "deletions": 0, "filename": "capabilities.json", "patch": "@@ -0,0 +1,33 @@\n+{\n+ \"schemaVersion\": \"1\",\n+ \"repo\": \"wave-av/wave-desktop\",\n+ \"version\": \"0.2.0\",\n+ \"lifecycle\": \"alpha\",\n+ \"planeLayer\": 0,\n+ \"foundationPin\": \"v1\",\n+ \"maintainers\": [{ \"team\": \"operator\" }],\n+ \"exposes\": {\n+ \"renderSurfaces\": [{ \"kind\": \"electron-app\", \"id\": \"online.wave.desktop\" }],\n+ \"apis\": [\n+ { \"protocol\": \"http\", \"endpoint\": \"ipc://wave:auth:state\", \"auth\": \"none\" },\n+ { \"protocol\": \"http\", \"endpoint\": \"ipc://wave:encoder:start\", \"auth\": \"bearer-jwt\" }\n+ ]\n+ },\n+ \"consumes\": {\n+ \"waveProducts\": [\n+ { \"repo\": \"wave-av/wave-gateway\", \"endpoint\": \"/oauth/device/code\" },\n+ { \"repo\": \"wave-av/wave-gateway\", \"endpoint\": \"/oauth/token\" }\n+ ],\n+ \"thirdParty\": [\n+ { \"service\": \"electron-safe-storage\", \"licenseGated\": false }\n+ ],\n+ \"foundationFrameworks\": [\"frameworks/protocol-plane\", \"frameworks/platform-registry\", \"frameworks/copywriting\"]\n+ },\n+ \"events\": {\n+ \"publishes\": [\n+ { \"topic\": \"auth.signed-in\", \"transport\": \"sentry\" },\n+ { \"topic\": \"auth.sign-in.failed\", \"transport\": \"sentry\" }\n+ ]\n+ },\n+ \"tags\": [\"operator\", \"public\", \"electron\", \"on-prem\", \"build-on-wave\", \"oauth-device-code\"]\n+}", "status": "added"}], "message": "feat: add capabilities.json (platform-registry Phase D)\n\nPublishes this repo to wave-foundation/frameworks/platform-registry.\n\nCo-Authored-By: Claude Opus 4.7 (1M context) ", "sha": "84786dc9cfd298458f06b74437e7f596f6c5d69d"}], "post_review_commits": ["a35102b9bda518b5459d31103a1ba1692c9fc37a"], "pr_author": "yakimoto", "pr_title": "feat: add capabilities.json (platform-registry Phase D)", "repo_name": "wave-av/wave-desktop"}, "repo": "wave-av/wave-desktop", "snapshot": "snapshots/aca09a9cd9725bc2c2bf9fe6085a8a02b3ac668aac76ebf602b6efe666409d32.pack", "split": "rl", "task_id": "1b090cc5a19905e619fd8fefc65cb295557aa82d130e91254c802c7143fe1e68"} {"base_sha": "a81181ada05d6dbb2982f28b540b15f26339dcee", "cohort": null, "context": {"canonical_pr_url": "https://github.com/schubydoo/clauster/pull/398", "id": "1c0154b254545e5cad57512431409dd7ba013bad08c30193624e25c36dc5e43c", "preparation_mode": "source-only", "snapshot": {"base_ref": "a81181ada05d6dbb2982f28b540b15f26339dcee", "base_sha": "a81181ada05d6dbb2982f28b540b15f26339dcee", "body": "", "head_ref": "fae5dad9c287bfd4b55a5eafb4937bdb417dfe36", "head_sha": "fae5dad9c287bfd4b55a5eafb4937bdb417dfe36", "name": "clauster", "number": 398, "owner": "schubydoo", "pr_url": "https://github.com/schubydoo/clauster/pull/398", "title": ""}}, "head_sha": "fae5dad9c287bfd4b55a5eafb4937bdb417dfe36", "metadata": {"group_id": "9e2a85a63cc679aea6bf71b59c2c255fb1d585ad5db7b5535ecb3b0d107c8b61", "snapshot": {"base_sha": "a81181ada05d6dbb2982f28b540b15f26339dcee", "external_requirements": [], "head_sha": "fae5dad9c287bfd4b55a5eafb4937bdb417dfe36", "objects": 305, "objects_sha256": "c46819a225aa139ed96a96f4f1cb8ab3320eafde0536af2f7f517f0d7decbf49", "patch_sha256": "423c0efc21417d1bcb7dde8094cd060464ee2b6c3446ac2d4395ed0c8ee2b4aa"}}, "pr_number": 398, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "535b487e4878", "description": "The resume API did not check whether a background job's worker was still alive. A direct POST could bypass the UI gate and start a second worker over the same transcript.", "file_path": "src/clauster/supervisor.py"}], "commits_under_review": [{"author": "schubydoo", "date": "2026-06-18T07:13:08Z", "files": [{"additions": 27, "deletions": 0, "filename": "src/clauster/app.py", "patch": "@@ -1119,6 +1119,33 @@ async def api_stop_agent(job_id: str) -> dict:\n except supervisor.StopError as exc:\n raise HTTPException(status_code=409, detail=str(exc)) from exc\n \n+ @app.post(\"/api/agents/{job_id}/resume\", status_code=201)\n+ async def api_resume_agent(job_id: str) -> dict:\n+ \"\"\"Resume an ended `claude --bg` session into a new bg job inheriting its transcript.\n+\n+ The path `{job_id}` is the 8-hex short id (validated like the stop path); the\n+ `--resume` argument is the job's full session UUID, validated separately\n+ (`valid_session_id`) — the 8-hex guard would reject a UUID. Resume mints a NEW\n+ job id (and session UUID) that inherits the prior transcript, so `{id}` returned\n+ here differs from the path id; the panel surfaces it as a new row.\n+ \"\"\"\n+ if not supervisor.valid_job_id(job_id):\n+ raise HTTPException(status_code=422, detail=\"invalid job id\")\n+ try:\n+ new_id = await asyncio.to_thread(\n+ supervisor.resume_background_job,\n+ job_id,\n+ binary=config.claude.binary,\n+ claude_json=runner.claude_json,\n+ )\n+ except claude_cli.ClaudeNotFound as exc:\n+ raise HTTPException(status_code=503, detail=str(exc)) from exc\n+ except supervisor.ResumeError as exc:\n+ raise HTTPException(status_code=409, detail=str(exc)) from exc\n+ except supervisor.DispatchError as exc:\n+ raise HTTPException(status_code=502, detail=str(exc)) from exc\n+ return {\"id\": new_id}\n+\n def _enforce_bypass_ceiling(project: str, permission_mode: str | None) -> None:\n \"\"\"Reject ``bypassPermissions`` when a project's config ceiling forbids it.\n ", "status": "modified"}, {"additions": 70, "deletions": 1, "filename": "src/clauster/supervisor.py", "patch": "@@ -244,14 +244,19 @@ def build_dispatch_argv(\n model: str | None = None,\n permission_mode: str | None = None,\n prompt: str | None = None,\n+ resume: str | None = None,\n ) -> list[str]:\n \"\"\"Build the ``claude --bg [...]`` argv. Pure (no side effects) — unit-testable.\n \n ``rc_name`` opens the cloud door (``--rc`` → a cloud-visible Remote Control\n session); omit it for a purely local background job. ``prompt`` is the\n trailing positional (the session's initial instruction) and may be omitted.\n+ ``resume`` is a prior session's full UUID — ``--bg --resume `` continues\n+ that conversation in a new bg job inheriting its transcript (#336).\n \"\"\"\n argv = [binary, \"--bg\"]\n+ if resume:\n+ argv += [\"--resume\", resume]\n if rc_name:\n argv += [\"--rc\", rc_name]\n if model:\n@@ -276,6 +281,7 @@ def dispatch_background_job(\n binary: str = \"claude\",\n claude_json: Path | None = None,\n timeout: float = _DISPATCH_TIMEOUT,\n+ resume: str | None = None,\n ) -> str:\n \"\"\"Dispatch a ``claude --bg`` background session in ``cwd``; return its job id.\n \n@@ -308,13 +314,22 @@ def dispatch_background_job(\n for label, value in flag_values:\n if value is not None and not _flag_value_ok(value):\n raise DispatchError(f\"invalid {label}: {value!r}\")\n+ # The resume arg is a session UUID, not a flag value: validate it to the RFC-4122\n+ # shape (the 8-hex job-id guard would reject it) so it can't smuggle an argv flag.\n+ if resume is not None and not valid_session_id(resume):\n+ raise DispatchError(f\"invalid resume session id: {resume!r}\")\n resolved = resolve_binary(binary) # absolute path, or ClaudeNotFound\n if claude_json is None:\n trust_directory(cwd)\n else:\n trust_directory(cwd, claude_json)\n argv = build_dispatch_argv(\n- resolved, rc_name=rc_name, model=model, permission_mode=permission_mode, prompt=prompt\n+ resolved,\n+ rc_name=rc_name,\n+ model=model,\n+ permission_mode=permission_mode,\n+ prompt=prompt,\n+ resume=resume,\n )\n try:\n proc = subprocess.run(\n@@ -344,6 +359,12 @@ def dispatch_background_job(\n # it also guards the `claude rm ` argv against injection.\n _JOB_ID_RE = re.compile(r\"[0-9a-f]{8}\")\n \n+# Session UUID shape (RFC-4122, 8-4-4-4-12 hex) — guards the `--resume ` argv\n+# against injection. Distinct from the 8-hex job id (#336).\n+_SESSION_ID_RE = re.compile(\n+ r\"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\"\n+)\n+\n # How long to wait for the SIGINT'd session to actually exit (orderly settle).\n _SETTLE_TIMEOUT = 20.0\n _SETTLE_POLL = 0.5\n@@ -365,6 +386,54 @@ def valid_job_id(job_id: object) -> bool:\n return isinstance(job_id, str) and _JOB_ID_RE.fullmatch(job_id) is not None\n \n \n+def valid_session_id(session_id: object) -> bool:\n+ \"\"\"Whether ``session_id`` matches the RFC-4122 UUID shape (resume argv guard, #336).\n+\n+ The ``--resume`` argument is the full session UUID, NOT the 8-hex job id, so the\n+ job-id guard would wrongly reject it; this validates the UUID's own shape.\n+ \"\"\"\n+ return isinstance(session_id, str) and _SESSION_ID_RE.fullmatch(session_id) is not None\n+\n+\n+class ResumeError(RuntimeError):\n+ \"\"\"An ended `claude --bg` session could not be resumed (raised fail-closed, #336).\"\"\"\n+\n+\n+def resume_background_job(\n+ job_id: str,\n+ *,\n+ binary: str = \"claude\",\n+ claude_json: Path | None = None,\n+ jobs_dir: Path | None = None,\n+ roster_json: Path | None = None,\n+ timeout: float = _DISPATCH_TIMEOUT,\n+) -> str:\n+ \"\"\"Resume an ended `claude --bg` session into a NEW bg job that inherits it (#336).\n+\n+ Looks the job up by its 8-hex id, reads its full session UUID + cwd, then\n+ dispatches ``claude --bg --resume `` in that cwd. Returns the **new** job\n+ id — a resume mints a fresh 8-hex id (and a new session UUID) that inherits the\n+ prior transcript, so the resumed agent surfaces as a new panel row.\n+\n+ Fail-closed: a job that no longer exists, has no recorded session UUID, or has\n+ no cwd raises :class:`ResumeError` rather than dispatching a malformed resume.\n+ \"\"\"\n+ job = next((j for j in list_background_jobs(jobs_dir, roster_json) if j.id == job_id), None)\n+ if job is None:\n+ raise ResumeError(f\"no background job {job_id!r}\")\n+ if not valid_session_id(job.session_id):\n+ raise ResumeError(f\"job {job_id!r} has no resumable session id\")\n+ if job.cwd is None:\n+ raise ResumeError(f\"job {job_id!r} has no recorded working directory\")\n+ return dispatch_background_job(\n+ job.cwd,\n+ resume=job.session_id,\n+ binary=binary,\n+ claude_json=claude_json,\n+ timeout=timeout,\n+ )\n+\n+\n def _live_session_pid(job_id: str, workers: dict[str, dict]) -> int | None:\n \"\"\"Return the roster pid for ``job_id`` only if it passes the liveness guard.\n ", "status": "modified"}, {"additions": 18, "deletions": 0, "filename": "src/clauster/templates/_dashboard_script.html", "patch": "@@ -82,6 +82,7 @@\n agentDispatchOpen: false,\n agentForm: { project: \"\", prompt: \"\", cloud: false, busy: false },\n agentStopping: {}, // job id -> true while a stop request is in flight\n+ agentResuming: {}, // job id -> true while a resume request is in flight (#336)\n forgetting: {}, // bridge/hosted id -> true while a forget request is in flight\n launching: {}, // project name -> true while a launch is in flight (double-submit guard)\n // --- hosted live-view sessions (claustrum stream-json channel, CL-4c) ---\n@@ -592,6 +593,23 @@\n this.agentStopping[j.id] = false;\n await this.refresh();\n },\n+ // Resume an ended bg agent: `--bg --resume ` continues the prior\n+ // conversation in a NEW job (new id), so we refresh to surface the new row (#336).\n+ async resumeAgent(j) {\n+ const label = j.name || j.id;\n+ this.agentResuming[j.id] = true;\n+ try {\n+ const res = await fetch(ROOT + \"/api/agents/\" + encodeURIComponent(j.id) + \"/resume\", { method: \"POST\" });\n+ if (res.status === 401) { window.location.assign(ROOT + \"/login\"); return; }\n+ const b = await res.json().catch(() => ({}));\n+ if (res.ok && b.id) this.toast(label + \": resumed as \" + b.id, \"success\");\n+ else this.toast(label + \": resume failed — \" + (b.detail || res.status), \"error\");\n+ } catch (e) { this.toast(label + \": resume failed\", \"error\"); }\n+ // finally: reset on EVERY path (incl. the 401 early-return) so the button can't\n+ // wedge on \"Resuming…\" if the login redirect is slow/blocked.\n+ finally { this.agentResuming[j.id] = false; }\n+ await this.refresh();\n+ },\n // Forget = drop a stopped/ended session's record so it leaves Recent/resumable.\n // Fail-closed on the server (a live session is refused 409); never stops a process.\n // `forget(name)` is a bridge (keyed by project), `forgetHosted(h)` a hosted session.", "status": "modified"}, {"additions": 9, "deletions": 0, "filename": "src/clauster/templates/dashboard.html", "patch": "@@ -265,6 +265,15 @@\n for an ended claude.ai session the title flags the possible cloud orphan.\n `!!` coercion: see the hosted-row note above — without it the button is\n stuck DISABLED on first paint (Alpine 3.15.x x-for missing-key `:disabled`). #}\n+ {# Resume an ENDED agent with a session UUID: `--bg --resume` continues the\n+ prior conversation in a new job (#336). `!!` coercion on :disabled — same\n+ Alpine 3.15.x x-for missing-key guard as the sibling buttons. #}\n+ \n \n+ \n+
\n+ `;\n+ overlay.appendChild(modal);\n+ document.body.appendChild(overlay);\n+\n+ const nameInput = modal.querySelector('[data-field=\"name\"]')!;\n+ const typeSelect = modal.querySelector('[data-field=\"type\"]')!;\n+ const ok = modal.querySelector(\".base-modal-ok\")!;\n+ const cancel = modal.querySelector(\".base-modal-cancel\")!;\n+\n+ const close = (val: { name: string; type: string } | null) => {\n+ overlay.remove();\n+ resolve(val);\n+ };\n+\n+ ok.addEventListener(\"click\", () => {\n+ const name = nameInput.value.trim();\n+ if (!name) return;\n+ close({ name, type: typeSelect.value });\n+ });\n+ cancel.addEventListener(\"click\", () => close(null));\n+ overlay.addEventListener(\"click\", (e) => { if (e.target === overlay) close(null); });\n+ nameInput.addEventListener(\"keydown\", (e) => {\n+ if (e.key === \"Enter\") { e.preventDefault(); ok.click(); }\n+ else if (e.key === \"Escape\") { e.preventDefault(); close(null); }\n+ });\n+ setTimeout(() => { nameInput.focus(); nameInput.select(); }, 0);\n+ });\n+}\n+\n function pickColumnName(suggestions: string[]): Promise {\n return new Promise((resolve) => {\n const overlay = document.createElement(\"div\");\n@@ -648,48 +746,6 @@ function startCellEdit(\n });\n }\n \n-function getCellValue(note: IndexedNote, column: string): unknown {\n- if (column.startsWith(\"formula:\")) {\n- const key = column.slice(\"formula:\".length);\n- return note.formulaValues?.[key];\n- }\n-\n- switch (column) {\n- case \"file.name\":\n- return note.name;\n- case \"file.path\":\n- return note.path;\n- case \"file.folder\":\n- return note.folder;\n- case \"file.ext\":\n- return note.ext;\n- case \"file.mtime\":\n- return note.mtime;\n- case \"file.ctime\":\n- return note.ctime;\n- case \"file.tags\":\n- case \"tags\":\n- return note.tags.join(\", \");\n- default:\n- return note.frontmatter[column];\n- }\n-}\n-\n-function formatValue(value: unknown): string {\n- if (value === undefined || value === null) return \"\";\n- if (Array.isArray(value)) return value.join(\", \");\n- if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n- if (value instanceof Date) return value.toLocaleDateString();\n- if (typeof value === \"number\" && value > 1e12) return new Date(value).toLocaleString();\n- return String(value);\n-}\n-\n-function formatColumnName(col: string): string {\n- if (col.startsWith(\"formula:\")) return col.slice(\"formula:\".length);\n- if (col.startsWith(\"file.\")) return col.slice(\"file.\".length);\n- return col.charAt(0).toUpperCase() + col.slice(1).replace(/[-_]/g, \" \");\n-}\n-\n function parseInputValue(str: string): unknown {\n const trimmed = str.trim();\n if (trimmed === \"\") return null;\n@@ -704,18 +760,4 @@ function parseInputValue(str: string): unknown {\n return trimmed;\n }\n \n-function compareValues(a: unknown, b: unknown): number {\n- if (a === b) return 0;\n- if (a === null || a === undefined) return -1;\n- if (b === null || b === undefined) return 1;\n- if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n- return String(a).localeCompare(String(b));\n-}\n \n-function escapeHtml(str: string): string {\n- return str\n- .replace(/&/g, \"&\")\n- .replace(//g, \">\")\n- .replace(/\"/g, \""\");\n-}", "status": "modified"}, {"additions": 68, "deletions": 0, "filename": "web/input.css", "patch": "@@ -525,6 +525,74 @@\n font-size: 13px;\n }\n \n+ /* ── Bases card / list view ──────────────────────────────────────────── */\n+\n+ .base-card-list {\n+ display: grid;\n+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));\n+ gap: 12px;\n+ }\n+ .base-card-gallery {\n+ display: grid;\n+ grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));\n+ gap: 12px;\n+ }\n+ .base-card {\n+ @apply bg-ob-bg2 border border-ob-border rounded-md p-3 transition-colors duration-100;\n+ display: flex;\n+ flex-direction: column;\n+ gap: 6px;\n+ min-height: 96px;\n+ }\n+ .base-card:hover { @apply border-ob-accent; }\n+ .base-card-title {\n+ @apply text-ob-accent no-underline;\n+ font-weight: 600;\n+ font-size: 14px;\n+ word-break: break-word;\n+ }\n+ .base-card-title:hover { @apply underline; }\n+ .base-card-folder {\n+ @apply text-ob-muted;\n+ font-size: 11px;\n+ }\n+ .base-card-meta {\n+ display: grid;\n+ grid-template-columns: max-content 1fr;\n+ column-gap: 8px;\n+ row-gap: 2px;\n+ margin: 4px 0 0 0;\n+ }\n+ .base-card-meta-label {\n+ @apply text-ob-muted;\n+ font-size: 11px;\n+ text-transform: uppercase;\n+ letter-spacing: 0.04em;\n+ }\n+ .base-card-meta-value {\n+ @apply text-ob-text;\n+ font-size: 12px;\n+ word-break: break-word;\n+ margin: 0;\n+ }\n+ .base-card-tags {\n+ display: flex;\n+ flex-wrap: wrap;\n+ gap: 4px;\n+ margin-top: auto;\n+ }\n+ .base-card-tag {\n+ @apply bg-ob-surface text-ob-muted rounded;\n+ padding: 2px 6px;\n+ font-size: 11px;\n+ }\n+ .base-card-empty {\n+ @apply text-ob-muted text-center;\n+ grid-column: 1 / -1;\n+ padding: 24px;\n+ font-size: 13px;\n+ }\n+\n /* Unsupported view placeholder */\n .base-unsupported-view {\n @apply flex flex-col items-center justify-center p-12 text-center text-ob-muted;", "status": "modified"}, {"additions": 15, "deletions": 1, "filename": "web/main.ts", "patch": "@@ -465,6 +465,10 @@ function showApp(): void {\n let previewDebounce: ReturnType | null = null;\n function updatePreview(doc: string): void {\n if (previewDebounce) clearTimeout(previewDebounce);\n+ previewDebounce = null;\n+ // .base files render the structured view in the preview pane; never let\n+ // the markdown preview overwrite it.\n+ if (currentPath?.endsWith(\".base\")) return;\n previewDebounce = setTimeout(() => {\n const { html, isRtl } = renderMarkdown(doc);\n previewEl.innerHTML = html;\n@@ -585,7 +589,17 @@ function showApp(): void {\n const trimmed = rawInput.trim();\n if (!trimmed) return;\n const fullPath = ensureBaseExt(trimmed);\n- const template = `properties:\\n - name: title\\n type: string\\n\\nviews:\\n - name: Default View\\n type: table\\n columns: [title]\\n`;\n+ // Default template: works out-of-the-box because columns reference\n+ // built-in file.* fields. Includes both a Table and a Cards view so\n+ // users can see card-list rendering immediately.\n+ const template =\n+ \"views:\\n\" +\n+ \" - name: Table\\n\" +\n+ \" type: table\\n\" +\n+ \" columns: [file.name, file.folder, file.mtime]\\n\" +\n+ \" - name: Cards\\n\" +\n+ \" type: list\\n\" +\n+ \" columns: [file.name, file.folder]\\n\";\n try {\n const created = await createFile(fullPath, template);\n renderTree(treeEl, openFile, activePathRef);", "status": "modified"}], "message": "feat(bases): fix new-base view, add Card/Gallery views, source toggle", "sha": "8b9e93102c90fccaf69c4b4e8af43d7bd921ee60"}], "post_review_commits": ["c05763379d265de3d877a4204a9a227bb090b801"], "pr_author": "devin-ai-integration[bot]", "pr_title": "feat(bases): fix new-base view, add Card list / Gallery views, keep source toggle", "repo_name": "abdelmomen1985/obsidian-direct"}, "repo": "abdelmomen1985/obsidian-direct", "snapshot": "snapshots/7c7e90eac29d4c6db3a49a8058f24a14d5c148ab97e395db34d132fae9a470c9.pack", "split": "rl", "task_id": "1d788d960cf677f0d560c7a99d523b60e352a781ef69f9db5f81a4e5343c2f23"} {"base_sha": "61a7fa7ffc55c00fdf9624a73c145ba74f1a80ff", "cohort": null, "context": {"canonical_pr_url": "https://github.com/hashgraph-online/hol-guard/pull/474", "id": "1ef63098d7d2dbc3f65fe68f7d2f31ac279415c3bbe5039b155115a105d72928", "preparation_mode": "source-only", "snapshot": {"base_ref": "61a7fa7ffc55c00fdf9624a73c145ba74f1a80ff", "base_sha": "61a7fa7ffc55c00fdf9624a73c145ba74f1a80ff", "body": "", "head_ref": "bca7201adbf8cc0493979e2d09d09737f2ec5539", "head_sha": "bca7201adbf8cc0493979e2d09d09737f2ec5539", "name": "hol-guard", "number": 474, "owner": "hashgraph-online", "pr_url": "https://github.com/hashgraph-online/hol-guard/pull/474", "title": ""}}, "head_sha": "bca7201adbf8cc0493979e2d09d09737f2ec5539", "metadata": {"group_id": "7cae3970d86e9f83fcb507e046fa2d6a78ce6b001c4da5ef43aa6175e810169f", "snapshot": {"base_sha": "61a7fa7ffc55c00fdf9624a73c145ba74f1a80ff", "external_requirements": [], "head_sha": "bca7201adbf8cc0493979e2d09d09737f2ec5539", "objects": 759, "objects_sha256": "8579b506925055c1b0ea2ac608440b03fb8484223c452a9d9786130e5f9e28db", "patch_sha256": "fadb83f5f290c3ff7d61b5ca97b59cd922a3982813ee159b8e4187b9b9fd0ec1"}}, "pr_number": 474, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "security", "commit_sha": "46fb6869d609", "description": "Trusted-publisher detection treated any URL containing `github.com` as GitHub Actions, allowing an attacker-controlled host with that string in its path to be misidentified as GitHub.", "file_path": "src/codex_plugin_scanner/guard/provenance.py"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "46fb6869d609", "description": "Git source immutability accepted hexadecimal fragments longer than a full 40-character commit SHA as immutable pins.", "file_path": "src/codex_plugin_scanner/guard/provenance.py"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "46fb6869d609", "description": "Provenance never affected risk decisions because the override function always returned false, even for verified or attested provenance on non-hard-risk, non-blocked decisions.", "file_path": "src/codex_plugin_scanner/guard/provenance.py"}], "commits_under_review": [{"author": "kantorcodes", "date": "2026-05-25T21:32:15Z", "files": [{"additions": 378, "deletions": 0, "filename": "src/codex_plugin_scanner/guard/provenance.py", "patch": "@@ -0,0 +1,378 @@\n+\"\"\"Supply chain provenance, attestation, SLSA, registry identity, and source policy.\n+\n+Implements SCRG146-158: npm provenance fetcher, PyPI attestation, Sigstore bundle\n+verification, SLSA provenance fields, repository binding policy, registry identity\n+pinning, dist integrity checks, HTTP source policy, and git source immutability.\n+\"\"\"\n+\n+from __future__ import annotations\n+\n+import hashlib\n+import json\n+import re\n+import urllib.error\n+import urllib.request\n+from typing import Any\n+\n+_HARD_RISK_CODES = frozenset(\n+ {\n+ \"known_malware\",\n+ \"kev_exploited\",\n+ \"malware_confirmed\",\n+ \"security_hold\",\n+ \"osv_critical_active\",\n+ \"license_violation_hard\",\n+ }\n+)\n+\n+_OFFICIAL_REGISTRIES: dict[str, set[str]] = {\n+ \"npm\": {\"https://registry.npmjs.org\", \"https://registry.yarnpkg.com\"},\n+ \"pypi\": {\"https://pypi.org\", \"https://files.pythonhosted.org\"},\n+ \"cargo\": {\"https://crates.io\", \"https://static.crates.io\"},\n+ \"rubygems\": {\"https://rubygems.org\"},\n+ \"maven\": {\"https://repo1.maven.org\", \"https://repo.maven.apache.org\"},\n+ \"go\": {\"https://proxy.golang.org\", \"https://goproxy.io\"},\n+}\n+\n+REGISTRY_IDENTITY_POLICY_ADR = \"\"\"\n+ADR-SCRG152: Registry Identity and Pinning Policy\n+\n+Status: Accepted\n+\n+Context:\n+Package managers can be configured to pull from arbitrary registries. A compromised\n+or malicious registry can serve tampered packages even with matching names and versions.\n+\n+Decision:\n+1. Each ecosystem has a set of official/trusted registries (see _OFFICIAL_REGISTRIES).\n+2. Any registry not in the trusted set produces an 'allowed: False' result with a\n+ non-empty reason and a recommendation to pin or explicitly allow-list the registry.\n+3. Workspace policy may extend the trusted set via allowed_registries config.\n+4. A registry fingerprint (SHA-256 of the registry base URL) is stored alongside\n+ package install receipts to enable drift detection.\n+5. Registry pinning is enforced at the point of source URL resolution, before download.\n+\n+Consequences:\n+- Packages resolved from unofficial registries will produce warnings or blocks\n+ depending on workspace risk tolerance settings.\n+- Private registries must be explicitly listed in workspace config to avoid false\n+ positives in enterprise environments.\n+\"\"\"\n+\n+\n+def _fetch_npm_attestations(package: str, version: str) -> dict[str, Any]:\n+ \"\"\"Fetch npm attestation data from the official npm registry API.\"\"\"\n+ encoded = urllib.request.quote(f\"{package}/-/{package}-{version}.tgz\", safe=\"@/\")\n+ url = f\"https://registry.npmjs.org/-/npm/v1/attestations/{encoded}\"\n+ req = urllib.request.Request(url, headers={\"Accept\": \"application/json\"})\n+ with urllib.request.urlopen(req, timeout=10) as resp:\n+ return json.loads(resp.read())\n+\n+\n+def _fetch_pypi_attestations(package: str, version: str) -> dict[str, Any]:\n+ \"\"\"Fetch PyPI attestation data from the PyPI API.\"\"\"\n+ url = f\"https://pypi.org/integrity/{package}/{version}/attestations.json\"\n+ req = urllib.request.Request(url, headers={\"Accept\": \"application/json\"})\n+ with urllib.request.urlopen(req, timeout=10) as resp:\n+ return json.loads(resp.read())\n+\n+\n+def fetch_npm_provenance(package: str, version: str) -> dict[str, Any]:\n+ \"\"\"Fetch and summarise npm provenance attestation for *package* at *version*.\n+\n+ Returns a dict with at least:\n+ - ``status``: 'attested' | 'verified' | 'unverified' | 'missing' | 'error'\n+ - ``attestations``: list of raw attestation dicts (empty when missing/error)\n+ - ``error``: error string when status='error'\n+ \"\"\"\n+ try:\n+ data = _fetch_npm_attestations(package, version)\n+ except Exception as exc:\n+ return {\"status\": \"error\", \"attestations\": [], \"error\": str(exc)}\n+\n+ attestations = data.get(\"attestations\", [])\n+ if not attestations:\n+ return {\"status\": \"missing\", \"attestations\": []}\n+\n+ return {\"status\": \"attested\", \"attestations\": attestations, \"package\": package, \"version\": version}\n+\n+\n+def extract_npm_trusted_publisher(attestation: dict[str, Any]) -> dict[str, Any]:\n+ \"\"\"Extract OIDC trusted publisher information from a single npm attestation dict.\n+\n+ Returns a dict with:\n+ - ``provider``: 'github_actions' | 'unknown'\n+ - ``source_repository``: URL or None\n+ - ``ref``: branch/tag ref or None\n+ - ``run_uri``: CI run URI or None\n+ \"\"\"\n+ predicate = attestation.get(\"predicate\", {})\n+ run_uri = predicate.get(\"runInvocationUri\") or predicate.get(\"runUri\")\n+ source_repo = predicate.get(\"sourceRepositoryUri\")\n+ ref = predicate.get(\"sourceRepositoryRef\")\n+\n+ if not source_repo and not run_uri:\n+ return {\"provider\": \"unknown\", \"source_repository\": None, \"ref\": None, \"run_uri\": None}\n+\n+ provider = \"unknown\"\n+ if (run_uri and \"github.com\" in run_uri) or (source_repo and \"github.com\" in source_repo):\n+ provider = \"github_actions\"\n+\n+ return {\n+ \"provider\": provider,\n+ \"source_repository\": source_repo,\n+ \"ref\": ref,\n+ \"run_uri\": run_uri,\n+ }\n+\n+\n+def fetch_pypi_attestation(package: str, version: str) -> dict[str, Any]:\n+ \"\"\"Fetch and summarise PyPI attestation for *package* at *version*.\n+\n+ Returns a dict with:\n+ - ``status``: 'attested' | 'missing' | 'error'\n+ - ``attestations``: list of attestation dicts\n+ \"\"\"\n+ try:\n+ data = _fetch_pypi_attestations(package, version)\n+ except Exception as exc:\n+ return {\"status\": \"error\", \"attestations\": [], \"error\": str(exc)}\n+\n+ attestations = data.get(\"attestations\", [])\n+ if not attestations:\n+ return {\"status\": \"missing\", \"attestations\": []}\n+\n+ return {\"status\": \"attested\", \"attestations\": attestations, \"package\": package, \"version\": version}\n+\n+\n+def verify_sigstore_bundle(bundle: dict[str, Any], *, expected_package_digest: str | None) -> dict[str, Any]:\n+ \"\"\"Verify a Sigstore bundle structure without trusted root.\n+\n+ Performs structural validation only (no network/crypto library calls):\n+ - Checks bundle mediaType\n+ - Checks verification material presence\n+ - Checks message digest matches expected_package_digest when provided\n+\n+ Returns dict with:\n+ - ``valid``: bool\n+ - ``reason``: explanation string\n+ \"\"\"\n+ if not bundle:\n+ return {\"valid\": False, \"reason\": \"empty bundle\"}\n+\n+ media_type = bundle.get(\"mediaType\", \"\")\n+ if \"sigstore\" not in media_type and \"bundle\" not in media_type:\n+ return {\"valid\": False, \"reason\": \"unrecognised bundle mediaType\"}\n+\n+ verification_material = bundle.get(\"verificationMaterial\")\n+ if not verification_material:\n+ return {\"valid\": False, \"reason\": \"missing verificationMaterial\"}\n+\n+ if expected_package_digest is not None:\n+ msg_sig = bundle.get(\"messageSignature\", {})\n+ actual_digest = msg_sig.get(\"messageDigest\", {}).get(\"digest\")\n+ if actual_digest and actual_digest != expected_package_digest:\n+ return {\"valid\": False, \"reason\": f\"digest mismatch: {actual_digest} != {expected_package_digest}\"}\n+\n+ return {\"valid\": True, \"reason\": \"structural validation passed\"}\n+\n+\n+def build_slsa_provenance_record(ecosystem: str, attestation: dict[str, Any]) -> dict[str, Any]:\n+ \"\"\"Build a SLSA provenance record from an attestation dict.\n+\n+ Fields:\n+ - ``builder_id``: CI builder URI or None\n+ - ``source_repository``: source repo URI or None\n+ - ``source_ref``: branch/tag ref or None\n+ - ``source_commit``: commit SHA or None\n+ - ``build_type``: build type URI or None\n+ - ``slsa_level``: int 1-3 or None\n+ - ``ecosystem``: the package ecosystem\n+ \"\"\"\n+ predicate = attestation.get(\"predicate\", {})\n+ run_uri = predicate.get(\"runInvocationUri\") or predicate.get(\"runUri\")\n+ source_repo = predicate.get(\"sourceRepositoryUri\")\n+ source_ref = predicate.get(\"sourceRepositoryRef\")\n+ source_commit = predicate.get(\"sourceRepositoryCommit\") or predicate.get(\"sourceCommit\")\n+ build_type = predicate.get(\"buildType\")\n+ builder_id = predicate.get(\"builderId\") or predicate.get(\"builderUri\") or run_uri\n+\n+ slsa_level: int | None = None\n+ if source_repo and run_uri:\n+ slsa_level = 2 if source_commit and len(source_commit) >= 40 else 1\n+\n+ return {\n+ \"builder_id\": builder_id,\n+ \"source_repository\": source_repo,\n+ \"source_ref\": source_ref,\n+ \"source_commit\": source_commit,\n+ \"build_type\": build_type,\n+ \"slsa_level\": slsa_level,\n+ \"ecosystem\": ecosystem,\n+ }\n+\n+\n+def check_repository_binding(\n+ *,\n+ actual_source: str | None,\n+ required_org: str | None,\n+ required_repo: str | None = None,\n+) -> dict[str, Any]:\n+ \"\"\"Check whether a package's source repository matches workspace binding policy.\n+\n+ Returns:\n+ - ``bound``: True if policy is satisfied\n+ - ``violation``: human-readable reason when bound=False, else None\n+ \"\"\"\n+ if required_org is None and required_repo is None:\n+ return {\"bound\": True, \"violation\": None}\n+\n+ if not actual_source:\n+ return {\"bound\": False, \"violation\": \"no source repository in provenance\"}\n+\n+ if required_repo is not None and required_repo.lower() not in actual_source.lower():\n+ return {\n+ \"bound\": False,\n+ \"violation\": f\"source {actual_source!r} does not match required repo {required_repo!r}\",\n+ }\n+\n+ if required_org is not None:\n+ org_pattern = f\"/{required_org}/\"\n+ alt_pattern = f\":{required_org}/\"\n+ if org_pattern.lower() not in actual_source.lower() and alt_pattern.lower() not in actual_source.lower():\n+ return {\n+ \"bound\": False,\n+ \"violation\": f\"source {actual_source!r} does not match required org {required_org!r}\",\n+ }\n+\n+ return {\"bound\": True, \"violation\": None}\n+\n+\n+def check_registry_identity(ecosystem: str, registry_url: str) -> dict[str, Any]:\n+ \"\"\"Check whether *registry_url* is an officially trusted registry for *ecosystem*.\n+\n+ Returns:\n+ - ``allowed``: bool\n+ - ``reason``: explanation when not allowed\n+ - ``fingerprint``: SHA-256 hex of registry_url\n+ \"\"\"\n+ canonical = registry_url.rstrip(\"/\").lower()\n+ trusted = _OFFICIAL_REGISTRIES.get(ecosystem, set())\n+ trusted_lower = {u.rstrip(\"/\").lower() for u in trusted}\n+ fingerprint = hashlib.sha256(registry_url.encode()).hexdigest()\n+\n+ if canonical in trusted_lower:\n+ return {\"allowed\": True, \"reason\": None, \"fingerprint\": fingerprint}\n+\n+ return {\n+ \"allowed\": False,\n+ \"reason\": (\n+ f\"registry {registry_url!r} is not in the trusted set for ecosystem {ecosystem!r}. \"\n+ \"Add it to workspace.allowed_registries to allow installs from this registry.\"\n+ ),\n+ \"fingerprint\": fingerprint,\n+ }\n+\n+\n+def check_dist_integrity(\n+ *,\n+ lockfile_integrity: str | None,\n+ registry_integrity: str | None,\n+) -> dict[str, Any]:\n+ \"\"\"Compare lockfile integrity hash against registry-provided integrity.\n+\n+ Returns:\n+ - ``match``: True if hashes agree\n+ - ``status``: 'verified' | 'mismatch' | 'unverifiable'\n+ \"\"\"\n+ if registry_integrity is None:\n+ return {\"match\": False, \"status\": \"unverifiable\", \"lockfile_integrity\": lockfile_integrity}\n+\n+ if lockfile_integrity is None:\n+ return {\"match\": False, \"status\": \"unverifiable\", \"registry_integrity\": registry_integrity}\n+\n+ match = lockfile_integrity == registry_integrity\n+ return {\n+ \"match\": match,\n+ \"status\": \"verified\" if match else \"mismatch\",\n+ \"lockfile_integrity\": lockfile_integrity,\n+ \"registry_integrity\": registry_integrity,\n+ }\n+\n+\n+def check_source_url_security(source_url: str | None) -> dict[str, Any]:\n+ \"\"\"Return whether *source_url* uses a secure scheme.\n+\n+ Returns:\n+ - ``secure``: bool\n+ - ``reason``: 'insecure_http' when scheme is http, None otherwise\n+ \"\"\"\n+ if source_url is None:\n+ return {\"secure\": True, \"reason\": None, \"url\": None}\n+\n+ url_lower = source_url.strip().lower()\n+ if url_lower.startswith(\"http://\"):\n+ return {\"secure\": False, \"reason\": \"insecure_http\", \"url\": source_url}\n+\n+ return {\"secure\": True, \"reason\": None, \"url\": source_url}\n+\n+\n+_SHA_RE = re.compile(r\"^[0-9a-f]{40,}$\", re.IGNORECASE)\n+_SEMVER_RE = re.compile(r\"^v?\\d+\\.\\d+\")\n+\n+\n+def check_git_source_immutability(source_url: str) -> dict[str, Any]:\n+ \"\"\"Determine whether a git source URL pins to an immutable commit SHA.\n+\n+ Returns:\n+ - ``immutable``: True only when the fragment is a full 40+ hex commit SHA\n+ - ``reason``: 'mutable_branch' | 'mutable_tag' | 'no_pin' | None\n+ - ``fragment``: the fragment portion of the URL\n+ \"\"\"\n+ if \"#\" not in source_url:\n+ return {\"immutable\": False, \"reason\": \"no_pin\", \"fragment\": None}\n+\n+ fragment = source_url.split(\"#\", 1)[1]\n+ if not fragment:\n+ return {\"immutable\": False, \"reason\": \"no_pin\", \"fragment\": fragment}\n+\n+ if _SHA_RE.match(fragment):\n+ return {\"immutable\": True, \"reason\": None, \"fragment\": fragment}\n+\n+ if _SEMVER_RE.match(fragment):\n+ return {\"immutable\": False, \"reason\": \"mutable_tag\", \"fragment\": fragment}\n+\n+ return {\"immutable\": False, \"reason\": \"mutable_branch\", \"fragment\": fragment}\n+\n+\n+_PROVENANCE_COPY: dict[str, str] = {\n+ \"verified\": \"Provenance verified: package build is attested to a trusted CI publisher.\",\n+ \"attested\": \"Provenance attested: package includes a build attestation.\",\n+ \"missing\": \"No provenance available for this package. Cannot verify build origin.\",\n+ \"mismatch\": \"Provenance mismatch: attestation data does not agree with package metadata.\",\n+ \"unknown\": \"Provenance status unknown: unable to retrieve attestation data.\",\n+ \"error\": \"Provenance check failed: could not contact the attestation registry.\",\n+ \"unverified\": \"Provenance unverified: attestation structure present but not fully validated.\",\n+}\n+\n+\n+def build_provenance_copy(*, status: str, ecosystem: str, package: str) -> str:\n+ \"\"\"Return a human-readable string describing the provenance status.\"\"\"\n+ base = _PROVENANCE_COPY.get(status, f\"Provenance status: {status}.\")\n+ return f\"{base} ({ecosystem}/{package})\"\n+\n+\n+def provenance_overrides_hard_risk(\n+ *,\n+ decision: str,\n+ block_reason_code: str,\n+ provenance_status: str,\n+) -> bool:\n+ \"\"\"Return whether valid provenance can override the given decision/risk code.\n+\n+ Hard-risk decisions (known_malware, KEV, etc.) are never overridable by provenance.\n+ Returns False for any hard-risk code regardless of provenance status.\n+ \"\"\"\n+ if block_reason_code in _HARD_RISK_CODES:\n+ return False\n+ return False", "status": "added"}, {"additions": 405, "deletions": 0, "filename": "tests/test_guard_provenance.py", "patch": "@@ -0,0 +1,405 @@\n+\"\"\"SCRG146-158: provenance, attestation, SLSA, registry identity, dist integrity, source policy.\"\"\"\n+from __future__ import annotations\n+\n+import json\n+from pathlib import Path\n+from unittest.mock import MagicMock, patch\n+\n+import pytest\n+\n+\n+class TestScrg146NpmProvenanceFetcher:\n+ \"\"\"SCRG146: npm provenance fetcher reads attestation metadata.\"\"\"\n+\n+ def test_npm_provenance_returns_dataclass_for_attested_package(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import fetch_npm_provenance\n+\n+ fixture = {\n+ \"attestations\": [\n+ {\n+ \"url\": \"https://registry.npmjs.org/-/npm/v1/attestations/foo/-/foo-1.0.0.tgz\",\n+ \"type\": \"https://github.com/npm/attestation/tree/main/specs/publish/v0.1\",\n+ \"predicateType\": \"https://github.com/npm/attestation/tree/main/specs/publish/v0.1\",\n+ }\n+ ]\n+ }\n+ with patch(\n+ \"codex_plugin_scanner.guard.provenance._fetch_npm_attestations\",\n+ return_value=fixture,\n+ ):\n+ result = fetch_npm_provenance(\"foo\", \"1.0.0\")\n+ assert result is not None\n+ assert result[\"status\"] in (\"attested\", \"verified\", \"unverified\")\n+ assert \"attestations\" in result\n+\n+ def test_npm_provenance_returns_missing_for_non_attested_package(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import fetch_npm_provenance\n+\n+ with patch(\n+ \"codex_plugin_scanner.guard.provenance._fetch_npm_attestations\",\n+ return_value={\"attestations\": []},\n+ ):\n+ result = fetch_npm_provenance(\"foo\", \"1.0.0\")\n+ assert result[\"status\"] == \"missing\"\n+\n+ def test_npm_provenance_returns_error_on_fetch_failure(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import fetch_npm_provenance\n+\n+ with patch(\n+ \"codex_plugin_scanner.guard.provenance._fetch_npm_attestations\",\n+ side_effect=OSError(\"network error\"),\n+ ):\n+ result = fetch_npm_provenance(\"foo\", \"1.0.0\")\n+ assert result[\"status\"] == \"error\"\n+\n+\n+class TestScrg147NpmTrustedPublisher:\n+ \"\"\"SCRG147: npm trusted publisher OIDC state stored.\"\"\"\n+\n+ def test_extract_trusted_publisher_from_attestation(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import extract_npm_trusted_publisher\n+\n+ attestation = {\n+ \"predicateType\": \"https://github.com/npm/attestation/tree/main/specs/publish/v0.1\",\n+ \"predicate\": {\n+ \"buildTrigger\": \"push\",\n+ \"runInvocationUri\": \"https://github.com/owner/repo/actions/runs/123\",\n+ \"sourceRepositoryUri\": \"https://github.com/owner/repo\",\n+ \"sourceRepositoryRef\": \"refs/heads/main\",\n+ },\n+ }\n+ result = extract_npm_trusted_publisher(attestation)\n+ assert result[\"source_repository\"] == \"https://github.com/owner/repo\"\n+ assert result[\"ref\"] == \"refs/heads/main\"\n+ assert result[\"provider\"] == \"github_actions\"\n+\n+ def test_extract_trusted_publisher_returns_unknown_when_missing(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import extract_npm_trusted_publisher\n+\n+ result = extract_npm_trusted_publisher({})\n+ assert result[\"provider\"] == \"unknown\"\n+ assert result[\"source_repository\"] is None\n+\n+\n+class TestScrg148PypiAttestationVerifier:\n+ \"\"\"SCRG148: PyPI attestation verifier.\"\"\"\n+\n+ def test_pypi_attestation_returns_attested_for_valid_response(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import fetch_pypi_attestation\n+\n+ fixture = {\n+ \"attestations\": [\n+ {\n+ \"statement\": {\"_type\": \"https://in-toto.io/Statement/v0.1\"},\n+ \"verification_material\": {},\n+ }\n+ ]\n+ }\n+ with patch(\n+ \"codex_plugin_scanner.guard.provenance._fetch_pypi_attestations\",\n+ return_value=fixture,\n+ ):\n+ result = fetch_pypi_attestation(\"requests\", \"2.31.0\")\n+ assert result[\"status\"] in (\"attested\", \"verified\", \"unverified\")\n+\n+ def test_pypi_attestation_returns_missing_for_empty(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import fetch_pypi_attestation\n+\n+ with patch(\n+ \"codex_plugin_scanner.guard.provenance._fetch_pypi_attestations\",\n+ return_value={\"attestations\": []},\n+ ):\n+ result = fetch_pypi_attestation(\"requests\", \"2.31.0\")\n+ assert result[\"status\"] == \"missing\"\n+\n+ def test_pypi_attestation_returns_error_on_network_failure(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import fetch_pypi_attestation\n+\n+ with patch(\n+ \"codex_plugin_scanner.guard.provenance._fetch_pypi_attestations\",\n+ side_effect=OSError(\"timeout\"),\n+ ):\n+ result = fetch_pypi_attestation(\"requests\", \"2.31.0\")\n+ assert result[\"status\"] == \"error\"\n+\n+\n+class TestScrg149SigstoreVerification:\n+ \"\"\"SCRG149: Sigstore verification utility - keyless identity check.\"\"\"\n+\n+ def test_verify_sigstore_bundle_structure_valid(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import verify_sigstore_bundle\n+\n+ bundle = {\n+ \"mediaType\": \"application/vnd.dev.sigstore.bundle.v0.3+json\",\n+ \"verificationMaterial\": {\n+ \"certificate\": {\"rawBytes\": \"dGVzdA==\"},\n+ \"tlogEntries\": [{\"inclusionPromise\": {\"signedEntryTimestamp\": \"abc\"}}],\n+ },\n+ \"messageSignature\": {\"messageDigest\": {\"algorithm\": \"SHA2_256\", \"digest\": \"deadbeef\"}, \"signature\": \"sig\"},\n+ }\n+ result = verify_sigstore_bundle(bundle, expected_package_digest=\"deadbeef\")\n+ assert result[\"valid\"] in (True, False)\n+ assert \"reason\" in result\n+\n+ def test_verify_sigstore_rejects_missing_verification_material(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import verify_sigstore_bundle\n+\n+ result = verify_sigstore_bundle({}, expected_package_digest=None)\n+ assert result[\"valid\"] is False\n+ assert \"reason\" in result\n+\n+ def test_verify_sigstore_rejects_digest_mismatch(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import verify_sigstore_bundle\n+\n+ bundle = {\n+ \"mediaType\": \"application/vnd.dev.sigstore.bundle.v0.3+json\",\n+ \"verificationMaterial\": {\"certificate\": {\"rawBytes\": \"x\"}},\n+ \"messageSignature\": {\"messageDigest\": {\"algorithm\": \"SHA2_256\", \"digest\": \"aabbcc\"}, \"signature\": \"sig\"},\n+ }\n+ result = verify_sigstore_bundle(bundle, expected_package_digest=\"deadbeef\")\n+ assert result[\"valid\"] is False\n+ assert \"digest\" in result[\"reason\"].lower() or \"mismatch\" in result[\"reason\"].lower()\n+\n+\n+class TestScrg150SlsaProvenanceFields:\n+ \"\"\"SCRG150: SLSA provenance fields stored correctly.\"\"\"\n+\n+ def test_build_slsa_provenance_record_from_npm_attestation(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import build_slsa_provenance_record\n+\n+ attestation = {\n+ \"predicate\": {\n+ \"buildTrigger\": \"push\",\n+ \"buildType\": \"https://github.com/npm/cli\",\n+ \"runInvocationUri\": \"https://github.com/owner/repo/actions/runs/123\",\n+ \"sourceRepositoryUri\": \"https://github.com/owner/repo\",\n+ \"sourceRepositoryRef\": \"refs/heads/main\",\n+ \"sourceRepositoryCommit\": \"abc123\",\n+ }\n+ }\n+ record = build_slsa_provenance_record(\"npm\", attestation)\n+ assert record[\"builder_id\"] is not None\n+ assert record[\"source_repository\"] == \"https://github.com/owner/repo\"\n+ assert record[\"source_ref\"] == \"refs/heads/main\"\n+ assert record[\"source_commit\"] == \"abc123\"\n+ assert \"slsa_level\" in record\n+\n+ def test_slsa_level_none_when_no_provenance(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import build_slsa_provenance_record\n+\n+ record = build_slsa_provenance_record(\"npm\", {})\n+ assert record[\"slsa_level\"] is None\n+\n+ def test_slsa_level_1_when_build_metadata_present(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import build_slsa_provenance_record\n+\n+ attestation = {\n+ \"predicate\": {\n+ \"runInvocationUri\": \"https://github.com/owner/repo/actions/runs/123\",\n+ \"sourceRepositoryUri\": \"https://github.com/owner/repo\",\n+ }\n+ }\n+ record = build_slsa_provenance_record(\"npm\", attestation)\n+ assert record[\"slsa_level\"] in (1, 2, 3)\n+\n+\n+class TestScrg151RepositoryBindingPolicy:\n+ \"\"\"SCRG151: workspace repository binding policy.\"\"\"\n+\n+ def test_binding_passes_when_source_repo_matches_required(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_repository_binding\n+\n+ result = check_repository_binding(\n+ actual_source=\"https://github.com/owner/repo\",\n+ required_org=\"owner\",\n+ )\n+ assert result[\"bound\"] is True\n+ assert result[\"violation\"] is None\n+\n+ def test_binding_fails_when_source_repo_wrong_org(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_repository_binding\n+\n+ result = check_repository_binding(\n+ actual_source=\"https://github.com/evil/repo\",\n+ required_org=\"trusted-org\",\n+ )\n+ assert result[\"bound\"] is False\n+ assert result[\"violation\"] is not None\n+\n+ def test_binding_passes_with_no_policy(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_repository_binding\n+\n+ result = check_repository_binding(actual_source=None, required_org=None)\n+ assert result[\"bound\"] is True\n+ assert result[\"violation\"] is None\n+\n+\n+class TestScrg152RegistryIdentityPinning:\n+ \"\"\"SCRG152: registry identity/pinning ADR and policy.\"\"\"\n+\n+ def test_registry_identity_policy_adr_exists(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import REGISTRY_IDENTITY_POLICY_ADR\n+\n+ assert isinstance(REGISTRY_IDENTITY_POLICY_ADR, str)\n+ assert len(REGISTRY_IDENTITY_POLICY_ADR) > 50\n+\n+ def test_allowed_registry_check_passes_for_official_npm(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_registry_identity\n+\n+ result = check_registry_identity(\"npm\", \"https://registry.npmjs.org\")\n+ assert result[\"allowed\"] is True\n+\n+ def test_allowed_registry_check_warns_for_unknown_registry(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_registry_identity\n+\n+ result = check_registry_identity(\"npm\", \"https://evil.registry.example.com\")\n+ assert result[\"allowed\"] is False\n+ assert result[\"reason\"] is not None\n+\n+\n+class TestScrg153DistIntegrityCheck:\n+ \"\"\"SCRG153: dist integrity vs lockfile metadata.\"\"\"\n+\n+ def test_integrity_matches_when_hash_agrees(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_dist_integrity\n+\n+ result = check_dist_integrity(\n+ lockfile_integrity=\"sha512-abc123\",\n+ registry_integrity=\"sha512-abc123\",\n+ )\n+ assert result[\"match\"] is True\n+ assert result[\"status\"] == \"verified\"\n+\n+ def test_integrity_mismatch_detected(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_dist_integrity\n+\n+ result = check_dist_integrity(\n+ lockfile_integrity=\"sha512-abc123\",\n+ registry_integrity=\"sha512-DIFFERENT\",\n+ )\n+ assert result[\"match\"] is False\n+ assert result[\"status\"] == \"mismatch\"\n+\n+ def test_integrity_unknown_when_registry_data_missing(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_dist_integrity\n+\n+ result = check_dist_integrity(lockfile_integrity=\"sha512-abc123\", registry_integrity=None)\n+ assert result[\"status\"] == \"unverifiable\"\n+\n+\n+class TestScrg154HttpSourcePolicy:\n+ \"\"\"SCRG154: HTTP (insecure) source URL blocked by default.\"\"\"\n+\n+ def test_http_tarball_url_is_insecure(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_source_url_security\n+\n+ result = check_source_url_security(\"http://example.com/pkg.tgz\")\n+ assert result[\"secure\"] is False\n+ assert result[\"reason\"] == \"insecure_http\"\n+\n+ def test_https_url_is_secure(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_source_url_security\n+\n+ result = check_source_url_security(\"https://registry.npmjs.org/pkg.tgz\")\n+ assert result[\"secure\"] is True\n+\n+ def test_none_url_is_not_flagged(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_source_url_security\n+\n+ result = check_source_url_security(None)\n+ assert result[\"secure\"] is True\n+ assert result[\"reason\"] is None\n+\n+\n+class TestScrg155GitSourceImmutability:\n+ \"\"\"SCRG155: git source immutability - mutable refs warned/blocked.\"\"\"\n+\n+ def test_commit_sha_pin_is_immutable(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_git_source_immutability\n+\n+ result = check_git_source_immutability(\"https://github.com/owner/repo#a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2\")\n+ assert result[\"immutable\"] is True\n+ assert result[\"reason\"] is None\n+\n+ def test_branch_ref_is_mutable(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_git_source_immutability\n+\n+ result = check_git_source_immutability(\"https://github.com/owner/repo#main\")\n+ assert result[\"immutable\"] is False\n+ assert result[\"reason\"] == \"mutable_branch\"\n+\n+ def test_tag_ref_is_mutable(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_git_source_immutability\n+\n+ result = check_git_source_immutability(\"https://github.com/owner/repo#v1.0.0\")\n+ assert result[\"immutable\"] is False\n+ assert result[\"reason\"] == \"mutable_tag\"\n+\n+ def test_no_fragment_is_mutable(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import check_git_source_immutability\n+\n+ result = check_git_source_immutability(\"https://github.com/owner/repo\")\n+ assert result[\"immutable\"] is False\n+ assert result[\"reason\"] == \"no_pin\"\n+\n+\n+class TestScrg156ProvenanceCopy:\n+ \"\"\"SCRG156: provenance copy - verified/missing/mismatched/unknown.\"\"\"\n+\n+ def test_copy_for_verified_status(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import build_provenance_copy\n+\n+ copy = build_provenance_copy(status=\"verified\", ecosystem=\"npm\", package=\"foo\")\n+ assert \"verified\" in copy.lower() or \"attested\" in copy.lower()\n+\n+ def test_copy_for_missing_status(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import build_provenance_copy\n+\n+ copy = build_provenance_copy(status=\"missing\", ecosystem=\"npm\", package=\"foo\")\n+ assert \"provenance\" in copy.lower() or \"no\" in copy.lower() or \"missing\" in copy.lower()\n+\n+ def test_copy_for_mismatch_status(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import build_provenance_copy\n+\n+ copy = build_provenance_copy(status=\"mismatch\", ecosystem=\"npm\", package=\"foo\")\n+ assert len(copy) > 10\n+\n+ def test_copy_for_unknown_status(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import build_provenance_copy\n+\n+ copy = build_provenance_copy(status=\"unknown\", ecosystem=\"pypi\", package=\"requests\")\n+ assert len(copy) > 10\n+\n+\n+class TestScrg157ProvenanceCannotBypassHardRisk:\n+ \"\"\"SCRG157: known malware/KEV still blocks even with valid provenance.\"\"\"\n+\n+ def test_malware_blocked_despite_valid_provenance(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import provenance_overrides_hard_risk\n+\n+ result = provenance_overrides_hard_risk(\n+ decision=\"block\",\n+ block_reason_code=\"known_malware\",\n+ provenance_status=\"verified\",\n+ )\n+ assert result is False\n+\n+ def test_provenance_can_affect_non_hard_risk_decisions(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import provenance_overrides_hard_risk\n+\n+ result = provenance_overrides_hard_risk(\n+ decision=\"warn\",\n+ block_reason_code=\"unknown_package\",\n+ provenance_status=\"verified\",\n+ )\n+ assert isinstance(result, bool)\n+\n+ def test_kev_blocked_despite_provenance(self) -> None:\n+ from codex_plugin_scanner.guard.provenance import provenance_overrides_hard_risk\n+\n+ result = provenance_overrides_hard_risk(\n+ decision=\"block\",\n+ block_reason_code=\"kev_exploited\",\n+ provenance_status=\"verified\",\n+ )\n+ assert result is False", "status": "added"}], "message": "feat(provenance): SCRG146-158 npm/PyPI attestation, Sigstore, SLSA, registry identity, dist integrity, source policy\n\nSigned-off-by: Michael Kantor <6068672+kantorcodes@users.noreply.github.com>", "sha": "bca7201adbf8cc0493979e2d09d09737f2ec5539"}], "post_review_commits": ["46fb6869d60928ca37cf20ad72833ecf5bc9c396"], "pr_author": "kantorcodes", "pr_title": "feat(provenance): SCRG146-158 npm/PyPI attestation, Sigstore, SLSA, registry identity, dist integrity, source policy", "repo_name": "hashgraph-online/hol-guard"}, "repo": "hashgraph-online/hol-guard", "snapshot": "snapshots/7cae3970d86e9f83fcb507e046fa2d6a78ce6b001c4da5ef43aa6175e810169f.pack", "split": "rl", "task_id": "1ef63098d7d2dbc3f65fe68f7d2f31ac279415c3bbe5039b155115a105d72928"} {"base_sha": "1dcf585883185a0c4461cffd657654d69b51fdca", "cohort": null, "context": {"canonical_pr_url": "https://github.com/Obsidian-Owl/floe/pull/305", "id": "2085b342475e3697cf9cbc1182a0c99b78f7c8c0f10aa1655095fa85a4c65f59", "preparation_mode": "source-only", "snapshot": {"base_ref": "1dcf585883185a0c4461cffd657654d69b51fdca", "base_sha": "1dcf585883185a0c4461cffd657654d69b51fdca", "body": "", "head_ref": "d744ae43e97289ee164355a8cac69f3fc4870739", "head_sha": "d744ae43e97289ee164355a8cac69f3fc4870739", "name": "floe", "number": 305, "owner": "Obsidian-Owl", "pr_url": "https://github.com/Obsidian-Owl/floe/pull/305", "title": ""}}, "head_sha": "d744ae43e97289ee164355a8cac69f3fc4870739", "metadata": {"group_id": "2a7865d8446cd7861af8f02f8a0a7f166706a18810c6c568c484ecab0fb25337", "snapshot": {"base_sha": "1dcf585883185a0c4461cffd657654d69b51fdca", "external_requirements": [{"path": "floe.png", "pointer": "version https://git-lfs.github.com/spec/v1\noid sha256:63b6f770c4868b31044dd7a1e5d633d5e7cc1649f37e279f2c087d223338c8ad\nsize 5076210\n", "snapshot": "1dcf585883185a0c4461cffd657654d69b51fdca", "type": "lfs"}, {"path": "floe.png", "pointer": "version https://git-lfs.github.com/spec/v1\noid sha256:63b6f770c4868b31044dd7a1e5d633d5e7cc1649f37e279f2c087d223338c8ad\nsize 5076210\n", "snapshot": "d744ae43e97289ee164355a8cac69f3fc4870739", "type": "lfs"}], "head_sha": "d744ae43e97289ee164355a8cac69f3fc4870739", "objects": 2820, "objects_sha256": "5ca402b44b82b3cb5df5b03c76db2426239e3567ea750ce6a8885585148675dc", "patch_sha256": "058bd0d59105aec3eab028d14628564bbdc871096e0fff93311043a39e6856a9"}}, "pr_number": 305, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "da76df9396d4", "description": "The platform service-map check required quoted keys, so unquoted YAML entries such as `polaris: 8181` bypassed duplicate-map detection.", "file_path": "scripts/check-architecture-drift"}, {"action_id": "A2", "action_type": "improvement", "category": "refactor", "commit_sha": "da76df9396d4", "description": "The service-name alternation was embedded in a long grep expression, making the platform-map rule difficult to maintain.", "file_path": "scripts/check-architecture-drift"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "da76df9396d4", "description": "The root-unit-test scratch file used a pytest-collectable name, and interrupted runs could leave scratch files behind that polluted later test runs.", "file_path": "testing/ci/tests/test_architecture_drift_guard.py"}, {"action_id": "A4", "action_type": "improvement", "category": "other", "commit_sha": "da76df9396d4", "description": "Architecture-drift guard tests lacked the `ALPHA-HARDENING` requirement markers needed to associate them with that requirement.", "file_path": "testing/ci/tests/test_architecture_drift_guard.py"}, {"action_id": "A5", "action_type": "improvement", "category": "bug", "commit_sha": "da76df9396d4", "description": "The guard tests did not verify that canonical service maps in the contract-owned directory remain allowed, leaving the allowlist behavior without regression coverage.", "file_path": "testing/ci/tests/test_architecture_drift_guard.py"}, {"action_id": "A6", "action_type": "fix", "category": "security", "commit_sha": "d1e1146c23db", "description": "Path validation resolved only a changed file's parent directory. An in-repository symlink to an external file could therefore pass the project-root check and cause the guard to inspect a file outside the repository.", "file_path": "scripts/check-architecture-drift"}], "commits_under_review": [{"author": "Specwright Tests", "date": "2026-05-03T23:43:55Z", "files": [{"additions": 56, "deletions": 19, "filename": "scripts/check-architecture-drift", "patch": "@@ -44,13 +44,13 @@ check_dbt_ownership() {\n # Check for SQL parsing in Python\n if grep -qE \"(sqlparse|sql.*parse|parse.*sql|ast.*sql)\" \"$file\" 2>/dev/null; then\n log_error \"$file: SQL parsing detected - dbt owns SQL compilation\"\n- ((violations++))\n+ violations=$((violations + 1))\n fi\n \n # Check for SQL validation\n if grep -qE \"(validate.*sql|sql.*valid)\" \"$file\" 2>/dev/null; then\n log_warn \"$file: SQL validation detected - consider delegating to dbt\"\n- ((warnings++))\n+ warnings=$((warnings + 1))\n fi\n }\n \n@@ -64,7 +64,7 @@ check_layer_boundaries() {\n # Check for manifest.yaml modifications\n if grep -qE \"(manifest\\.yaml|write.*manifest|save.*manifest)\" \"$file\" 2>/dev/null; then\n log_error \"$file: Layer 4 (Data) modifying Layer 2 (Configuration) - FORBIDDEN\"\n- ((violations++))\n+ violations=$((violations + 1))\n fi\n fi\n }\n@@ -86,7 +86,7 @@ check_contract_boundaries() {\n return 0\n fi\n log_warn \"$file: Direct FloeSpec usage - use CompiledArtifacts for cross-package contracts\"\n- ((warnings++))\n+ warnings=$((warnings + 1))\n fi\n }\n \n@@ -99,7 +99,7 @@ check_plugin_rules() {\n # Check for hardcoded secrets\n if grep -qE \"(password|secret|api_key|token)\\s*=\\s*['\\\"][^'\\\"]+['\\\"]\" \"$file\" 2>/dev/null; then\n log_error \"$file: Hardcoded secret in plugin - use SecretReference\"\n- ((violations++))\n+ violations=$((violations + 1))\n fi\n \n # Check for missing entry point registration (in setup.py or pyproject.toml)\n@@ -108,7 +108,7 @@ check_plugin_rules() {\n package_dir=$(dirname \"$file\")\n if [[ ! -f \"${package_dir}/pyproject.toml\" ]]; then\n log_warn \"$file: Plugin may be missing entry point registration\"\n- ((warnings++))\n+ warnings=$((warnings + 1))\n fi\n fi\n fi\n@@ -132,30 +132,40 @@ check_test_organization() {\n \n if [[ \"$package_imports\" -lt 2 ]]; then\n log_warn \"$file: Root-level test imports from <2 packages - should be in package tests/\"\n- ((warnings++))\n+ warnings=$((warnings + 1))\n fi\n fi\n \n # Check for time.sleep in tests\n if grep -qE \"time\\.sleep\\(\" \"$file\" 2>/dev/null; then\n log_warn \"$file: time.sleep() in test - use polling utilities instead\"\n- ((warnings++))\n+ warnings=$((warnings + 1))\n fi\n \n # Check for pytest.skip\n if grep -qE \"@pytest\\.mark\\.skip|pytest\\.skip\\(\" \"$file\" 2>/dev/null; then\n log_error \"$file: pytest.skip detected - tests must FAIL not skip\"\n- ((violations++))\n+ violations=$((violations + 1))\n fi\n }\n \n-check_file() {\n+check_platform_contract_literals() {\n local file=\"$1\"\n \n- # Only check Python files\n- if [[ ! \"$file\" == *.py ]]; then\n- return 0\n+ case \"$file\" in\n+ *\"packages/floe-core/src/floe_core/contracts/\"*|*\"charts/floe-platform/templates/tests/_contract-env.generated.tpl\")\n+ return 0\n+ ;;\n+ esac\n+\n+ if grep -qE \"['\\\"](dagster|polaris|polaris-management|minio|minio-console|postgres|postgresql|jaeger-query|otel-collector-grpc|otel-collector-http|marquez|oci-registry|oci-registry-auth)['\\\"][[:space:]]*:[[:space:]]*['\\\"]?[0-9]+['\\\"]?([[:space:]]*[,}]|[[:space:]]*$)\" \"$file\" 2>/dev/null; then\n+ log_error \"$file: duplicated platform service map detected - use floe_core.contracts.topology\"\n+ violations=$((violations + 1))\n fi\n+}\n+\n+check_file() {\n+ local file=\"$1\"\n \n # Skip non-existent files (deleted)\n if [[ ! -f \"$file\" ]]; then\n@@ -164,6 +174,19 @@ check_file() {\n \n log_info \"Checking $file...\"\n \n+ # Platform service literal checks apply to source-controlled text files.\n+ # Other checks below remain Python-only.\n+ case \"$file\" in\n+ *.py|*.sh|*.yaml|*.yml|*.toml|*.tpl|*.md|*/Makefile|Makefile)\n+ check_platform_contract_literals \"$file\"\n+ ;;\n+ esac\n+\n+ # Only check Python files for Python-specific rules.\n+ if [[ ! \"$file\" == *.py ]]; then\n+ return 0\n+ fi\n+\n check_dbt_ownership \"$file\"\n check_layer_boundaries \"$file\"\n check_contract_boundaries \"$file\"\n@@ -174,10 +197,26 @@ check_file() {\n validate_file_path() {\n # Prevent path traversal - ensure file is within PROJECT_ROOT\n local file=\"$1\"\n+ local candidate_path\n+ local candidate_dir\n+ local candidate_name\n+ local resolved_dir\n local resolved_path\n \n # Resolve to absolute path and check it's within project\n- resolved_path=$(realpath -m \"${PROJECT_ROOT}/${file}\" 2>/dev/null) || return 1\n+ case \"$file\" in\n+ /*)\n+ candidate_path=\"$file\"\n+ ;;\n+ *)\n+ candidate_path=\"${PROJECT_ROOT}/${file}\"\n+ ;;\n+ esac\n+\n+ candidate_dir=\"$(dirname \"$candidate_path\")\"\n+ candidate_name=\"$(basename \"$candidate_path\")\"\n+ resolved_dir=\"$(cd \"$candidate_dir\" 2>/dev/null && pwd -P)\" || return 1\n+ resolved_path=\"${resolved_dir}/${candidate_name}\"\n \n # Ensure path starts with PROJECT_ROOT (no traversal)\n if [[ \"$resolved_path\" != \"${PROJECT_ROOT}\"/* ]]; then\n@@ -201,7 +240,7 @@ main() {\n check_file \"$target\"\n else\n # Check all changed files\n- log_info \"Checking all changed Python files...\"\n+ log_info \"Checking all changed files...\"\n \n # Validate git refs exist before using them\n local base_ref=\"main\"\n@@ -217,7 +256,7 @@ main() {\n \n # Get changed files using validated refs with -- separator\n local changed_files\n- changed_files=$(git diff --name-only \"${base_ref}...${head_ref}\" -- \"*.py\" 2>/dev/null || true)\n+ changed_files=$(git diff --name-only \"${base_ref}...${head_ref}\" 2>/dev/null || true)\n \n if [[ -z \"$changed_files\" ]]; then\n log_info \"No changed files to check\"\n@@ -229,9 +268,7 @@ main() {\n local safe_path\n safe_path=$(validate_file_path \"$file\") || continue\n \n- if [[ \"$safe_path\" == *.py ]]; then\n- check_file \"$safe_path\"\n- fi\n+ check_file \"$safe_path\"\n done <<< \"$changed_files\"\n fi\n ", "status": "modified"}, {"additions": 84, "deletions": 0, "filename": "tests/unit/test_architecture_drift_guard.py", "patch": "@@ -0,0 +1,84 @@\n+\"\"\"Regression tests for architecture drift guard scripts.\"\"\"\n+\n+from __future__ import annotations\n+\n+import subprocess\n+from pathlib import Path\n+\n+PROJECT_ROOT = Path(__file__).resolve().parents[2]\n+\n+\n+def run_architecture_drift(target: Path) -> subprocess.CompletedProcess[str]:\n+ \"\"\"Run the architecture drift script against a target file.\"\"\"\n+ return subprocess.run(\n+ [\n+ str(PROJECT_ROOT / \"scripts/check-architecture-drift\"),\n+ str(target),\n+ ],\n+ cwd=PROJECT_ROOT,\n+ text=True,\n+ capture_output=True,\n+ check=False,\n+ )\n+\n+\n+def test_architecture_drift_reaches_summary_under_set_e(tmp_path: Path) -> None:\n+ \"\"\"Counter increments must not exit before the summary under set -e.\"\"\"\n+ parser_module = (\"s\" + \"ql\") + (\"pa\" + \"rse\")\n+ validation_suffix = \"s\" + \"ql\"\n+ drift_file = tmp_path / \"sql_drift.py\"\n+ drift_file.write_text(\n+ f\"import {parser_module}\\n\"\n+ \"\\n\"\n+ f\"def validate_{validation_suffix}(text: str) -> bool:\\n\"\n+ \" return True\\n\"\n+ )\n+\n+ result = run_architecture_drift(drift_file)\n+\n+ assert result.returncode == 2\n+ assert \"ARCHITECTURE DRIFT DETECTED\" in result.stderr\n+ assert \"Violations: 1, Warnings: 1\" in result.stderr\n+\n+\n+def test_architecture_drift_rejects_single_quoted_platform_service_map(\n+ tmp_path: Path,\n+) -> None:\n+ \"\"\"Duplicated platform service maps in Python must be rejected.\"\"\"\n+ component_name = \"pola\" + \"ris\"\n+ duplicated_map = tmp_path / \"duplicated_service_map.py\"\n+ duplicated_map.write_text(f\"SERVICE_DEFAULT_PORTS = {{{component_name!r}: 8181}}\\n\")\n+\n+ result = run_architecture_drift(duplicated_map)\n+\n+ assert result.returncode == 2\n+ assert \"duplicated platform service map detected\" in result.stderr\n+\n+\n+def test_architecture_drift_rejects_non_python_platform_service_map(\n+ tmp_path: Path,\n+) -> None:\n+ \"\"\"Duplicated platform service maps in YAML must be rejected.\"\"\"\n+ component_name = \"pola\" + \"ris\"\n+ duplicated_map = tmp_path / \"duplicated_service_map.yaml\"\n+ duplicated_map.write_text(f'ports:\\n \"{component_name}\": 8181\\n')\n+\n+ result = run_architecture_drift(duplicated_map)\n+\n+ assert result.returncode == 2\n+ assert \"duplicated platform service map detected\" in result.stderr\n+\n+\n+def test_architecture_drift_allows_nested_platform_service_config_map(\n+ tmp_path: Path,\n+) -> None:\n+ \"\"\"Nested service configuration maps are examples, not duplicate port tables.\"\"\"\n+ component_name = \"pola\" + \"ris\"\n+ nested_config = tmp_path / \"nested_service_config.py\"\n+ nested_config.write_text(\n+ f\"generator.add_plugin_values({{{component_name!r}: {{'enabled': True}}}})\\n\"\n+ )\n+\n+ result = run_architecture_drift(nested_config)\n+\n+ assert result.returncode == 0, result.stderr", "status": "added"}], "message": "fix: harden architecture drift guard", "sha": "5b140ef7b56ec43d91608be0b906976e1d3866e0"}, {"author": "Specwright Tests", "date": "2026-05-03T23:45:53Z", "files": [{"additions": 5, "deletions": 1, "filename": "scripts/check-architecture-drift", "patch": "@@ -127,7 +127,11 @@ check_test_organization() {\n if [[ \"$file\" == \"${PROJECT_ROOT}/tests/\"* ]]; then\n # Check if it imports from multiple packages\n local package_imports\n- package_imports=$(grep -E \"from (floe_core|floe_dagster|floe_dbt|floe_polaris)\" \"$file\" 2>/dev/null | wc -l | tr -d ' ')\n+ package_imports=$(\n+ { grep -E \"from (floe_core|floe_dagster|floe_dbt|floe_polaris)\" \"$file\" 2>/dev/null || true; } \\\n+ | wc -l \\\n+ | tr -d ' '\n+ )\n package_imports=${package_imports:-0}\n \n if [[ \"$package_imports\" -lt 2 ]]; then", "status": "modified"}, {"additions": 17, "deletions": 1, "filename": "testing/ci/tests/test_architecture_drift_guard.py", "patch": "@@ -3,9 +3,10 @@\n from __future__ import annotations\n \n import subprocess\n+import uuid\n from pathlib import Path\n \n-PROJECT_ROOT = Path(__file__).resolve().parents[2]\n+PROJECT_ROOT = Path(__file__).resolve().parents[3]\n \n \n def run_architecture_drift(target: Path) -> subprocess.CompletedProcess[str]:\n@@ -41,6 +42,21 @@ def test_architecture_drift_reaches_summary_under_set_e(tmp_path: Path) -> None:\n assert \"Violations: 1, Warnings: 1\" in result.stderr\n \n \n+def test_architecture_drift_import_count_reaches_warning_summary() -> None:\n+ \"\"\"Root test import counting must not exit before the warning summary.\"\"\"\n+ drift_file = PROJECT_ROOT / \"tests\" / \"unit\" / f\"test_arch_drift_{uuid.uuid4().hex}.py\"\n+ drift_file.write_text(\"def test_placeholder() -> None:\\n pass\\n\")\n+ try:\n+ result = run_architecture_drift(drift_file)\n+ finally:\n+ drift_file.unlink(missing_ok=True)\n+\n+ assert result.returncode == 1\n+ assert \"Root-level test imports from <2 packages\" in result.stderr\n+ assert \"ARCHITECTURE DRIFT WARNINGS\" in result.stderr\n+ assert \"Warnings: 1\" in result.stderr\n+\n+\n def test_architecture_drift_rejects_single_quoted_platform_service_map(\n tmp_path: Path,\n ) -> None:", "status": "renamed"}], "message": "test: cover drift guard branch checks", "sha": "d744ae43e97289ee164355a8cac69f3fc4870739"}], "post_review_commits": ["da76df9396d411dfd312dfa706bf9db983285407", "d1e1146c23db7f6680d5c325b9378893d0464f88"], "pr_author": "MacAttak", "pr_title": "Fix architecture drift guard branch checks", "repo_name": "Obsidian-Owl/floe"}, "repo": "Obsidian-Owl/floe", "snapshot": "snapshots/2a7865d8446cd7861af8f02f8a0a7f166706a18810c6c568c484ecab0fb25337.pack", "split": "rl", "task_id": "2085b342475e3697cf9cbc1182a0c99b78f7c8c0f10aa1655095fa85a4c65f59"} {"base_sha": "ed6c117184478d9bd1c781056041eb5f50ac985e", "cohort": null, "context": {"canonical_pr_url": "https://github.com/anomalyco/opencode/pull/36337", "id": "22b751b5647ef87c0377e02cfb0b42f45a6d6c2fc687efa577cae97826f61f3b", "preparation_mode": "source-only", "snapshot": {"base_ref": "ed6c117184478d9bd1c781056041eb5f50ac985e", "base_sha": "ed6c117184478d9bd1c781056041eb5f50ac985e", "body": "", "head_ref": "08ead11bb2066155190129aceb0e747d661bf50f", "head_sha": "08ead11bb2066155190129aceb0e747d661bf50f", "name": "opencode", "number": 36337, "owner": "anomalyco", "pr_url": "https://github.com/anomalyco/opencode/pull/36337", "title": ""}}, "head_sha": "08ead11bb2066155190129aceb0e747d661bf50f", "metadata": {"group_id": "8a8f297df13ac83966e0a0e5de9aeba5e79079aad75e783f9331da37f42b0d6f", "snapshot": {"base_sha": "ed6c117184478d9bd1c781056041eb5f50ac985e", "external_requirements": [], "head_sha": "08ead11bb2066155190129aceb0e747d661bf50f", "objects": 7098, "objects_sha256": "a8925601f1e6557d86b0a15a8e312dacf1c017245bd455ca0b73ffcac0977056", "patch_sha256": "241987f4ddf4ccef8d975599b93729e8963b6222624f3039e8c584264e9d98c0"}}, "pr_number": 36337, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "other", "commit_sha": "9b79d6bf43cd", "description": "The full TUI composer showed its close shortcut in the bottom action row rather than beside the tab heading, making the close action less discoverable; the hint also was not clickable.", "file_path": "packages/tui/src/routes/session/composer/index.tsx"}, {"action_id": "A2", "action_type": "cleanup", "category": "other", "commit_sha": "9b79d6bf43cd", "description": "The mini CLI subagent footer displayed an extra clickable “esc back” hint that was removed from the footer.", "file_path": "packages/cli/src/mini/footer.subagent.tsx"}], "commits_under_review": [{"author": "thdxr", "date": "2026-07-11T01:10:46Z", "files": [{"additions": 3, "deletions": 0, "filename": "packages/cli/src/mini/footer.subagent.tsx", "patch": "@@ -149,6 +149,9 @@ export function RunFooterSubagentBody(props: {\n {\" \" + subtitle()}\n \n \n+ props.onClose()}>\n+ esc back\n+ \n \n {(hint) => (\n ", "status": "modified"}, {"additions": 20, "deletions": 1, "filename": "packages/cli/test/footer-keymap.test.tsx", "patch": "@@ -9,7 +9,7 @@ import { RunFooterView } from \"../src/mini/footer.view\"\n import { RUN_THEME_FALLBACK } from \"../src/mini/theme\"\n import type { FooterState, FooterSubagentState, FooterView } from \"../src/mini/types\"\n \n-test(\"down opens subagents from an empty prompt\", async () => {\n+test(\"subagent inspector is discoverable and closable\", async () => {\n const [state] = createSignal({\n phase: \"idle\",\n status: \"\",\n@@ -97,6 +97,25 @@ test(\"down opens subagents from an empty prompt\", async () => {\n app.mockInput.pressArrow(\"down\")\n await app.renderOnce()\n expect(app.captureCharFrame()).toContain(\"Select subagent\")\n+\n+ app.mockInput.pressEnter()\n+ await app.renderOnce()\n+ expect(app.captureCharFrame()).toContain(\"esc back\")\n+\n+ app.mockInput.pressEscape()\n+ await app.renderOnce()\n+ expect(app.captureCharFrame()).not.toContain(\"esc back\")\n+\n+ app.mockInput.pressArrow(\"down\")\n+ await app.renderOnce()\n+ app.mockInput.pressEnter()\n+ await app.renderOnce()\n+ const lines = app.captureCharFrame().split(\"\\n\")\n+ const y = lines.findIndex((line) => line.includes(\"esc back\"))\n+ const x = lines[y].indexOf(\"esc back\")\n+ await app.mockMouse.click(x, y)\n+ await app.renderOnce()\n+ expect(app.captureCharFrame()).not.toContain(\"esc back\")\n } finally {\n app.renderer.currentFocusedRenderable?.blur()\n app.renderer.currentFocusedEditor?.blur()", "status": "modified"}], "message": "fix(tui): add subagent back affordance", "sha": "08ead11bb2066155190129aceb0e747d661bf50f"}], "post_review_commits": ["9b79d6bf43cd3501b07d0f780c652ebb40558a68"], "pr_author": "thdxr", "pr_title": "fix(tui): make composer close action discoverable", "repo_name": "anomalyco/opencode"}, "repo": "anomalyco/opencode", "snapshot": "snapshots/8a8f297df13ac83966e0a0e5de9aeba5e79079aad75e783f9331da37f42b0d6f.pack", "split": "rl", "task_id": "22b751b5647ef87c0377e02cfb0b42f45a6d6c2fc687efa577cae97826f61f3b"} {"base_sha": "22e5944a675422fc04f7e7ee7a9281bdca9d90cb", "cohort": null, "context": {"canonical_pr_url": "https://github.com/ccusage/ccusage/pull/1237", "id": "294da74def9ed536920784c2fd0bf268558de6b3e32ad38376e645cd812732fa", "preparation_mode": "source-only", "snapshot": {"base_ref": "22e5944a675422fc04f7e7ee7a9281bdca9d90cb", "base_sha": "22e5944a675422fc04f7e7ee7a9281bdca9d90cb", "body": "", "head_ref": "88ee6e1e1dc38b0ef4fb4380e09132c4fc6650b9", "head_sha": "88ee6e1e1dc38b0ef4fb4380e09132c4fc6650b9", "name": "ccusage", "number": 1237, "owner": "ccusage", "pr_url": "https://github.com/ccusage/ccusage/pull/1237", "title": ""}}, "head_sha": "88ee6e1e1dc38b0ef4fb4380e09132c4fc6650b9", "metadata": {"group_id": "23d704357de3e2be44ddca1ae4edd07521a311194ad002002a32361ceddd1811", "snapshot": {"base_sha": "22e5944a675422fc04f7e7ee7a9281bdca9d90cb", "external_requirements": [], "head_sha": "88ee6e1e1dc38b0ef4fb4380e09132c4fc6650b9", "objects": 452, "objects_sha256": "6a2d296e81d5f6078caf8078b73a0c38fe581773269fb095c9a4e0e110d1f501", "patch_sha256": "a2f47f5ea36845c2b4c0545273feb3d92aa15f9c8abdc0d8ed150cda23890b04"}}, "pr_number": 1237, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "other", "commit_sha": "d31939405495", "description": "The copied-rollout deduplication regression test covered only one aggregation mode, leaving the local or parallel path untested.", "file_path": "rust/crates/ccusage/src/adapter/codex/aggregate.rs"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "c7ffd05c10da", "description": "Codex session reports used a cross-session deduplication key before grouping, so identical token-usage rows in different session files could be collapsed, omitting a distinct session group and undercounting its usage.", "file_path": "rust/crates/ccusage/src/adapter/codex/aggregate.rs"}], "commits_under_review": [{"author": "ryoppippi", "date": "2026-06-08T21:57:11Z", "files": [{"additions": 43, "deletions": 14, "filename": "rust/crates/ccusage/src/adapter/codex/aggregate.rs", "patch": "@@ -18,18 +18,7 @@ use crate::{\n \n use super::{parser, paths};\n \n-type CodexEventKey = (\n- u64,\n- usize,\n- crate::TimestampMs,\n- u64,\n- usize,\n- u64,\n- u64,\n- u64,\n- u64,\n- u64,\n-);\n+type CodexEventKey = (crate::TimestampMs, u64, usize, u64, u64, u64, u64, u64);\n type CodexDedupeShards = [Mutex>];\n \n struct CodexAggregation {\n@@ -356,8 +345,6 @@ fn codex_event_key(\n model: &str,\n ) -> CodexEventKey {\n (\n- hash_text(&event.session_id),\n- event.session_id.len(),\n timestamp,\n hash_text(model),\n model.len(),\n@@ -463,6 +450,48 @@ mod tests {\n \n use crate::adapter::codex::paths::CodexUsageSource;\n \n+ #[test]\n+ fn dedupes_copied_token_usage_across_session_files() {\n+ let usage_line = json!({\n+ \"timestamp\": \"2026-05-29T08:01:00.000Z\",\n+ \"type\": \"event_msg\",\n+ \"payload\": {\n+ \"type\": \"token_count\",\n+ \"info\": {\n+ \"model\": \"gpt-5.2\",\n+ \"last_token_usage\": {\n+ \"input_tokens\": 1_000,\n+ \"cached_input_tokens\": 100,\n+ \"output_tokens\": 200,\n+ \"reasoning_output_tokens\": 20,\n+ \"total_tokens\": 1_200,\n+ },\n+ },\n+ },\n+ })\n+ .to_string();\n+ let fixture = fs_fixture!({\n+ \"sessions/root.jsonl\": &usage_line,\n+ \"sessions/goal.jsonl\": &usage_line,\n+ });\n+ let shared = SharedArgs {\n+ timezone: Some(\"UTC\".to_string()),\n+ ..SharedArgs::default()\n+ };\n+\n+ let groups =\n+ load_groups_from_directory(&fixture.path(\"sessions\"), &shared, AgentReportKind::Daily)\n+ .unwrap();\n+\n+ assert_eq!(groups.len(), 1);\n+ let group = groups.get(\"2026-05-29\").unwrap();\n+ assert_eq!(group.input_tokens, 1_000);\n+ assert_eq!(group.cached_input_tokens, 100);\n+ assert_eq!(group.output_tokens, 200);\n+ assert_eq!(group.reasoning_output_tokens, 20);\n+ assert_eq!(group.total_tokens, 1_200);\n+ }\n+\n #[test]\n fn aggregates_active_copy_when_archived_file_has_same_relative_path() {\n let active_usage = [", "status": "modified"}, {"additions": 5, "deletions": 5, "filename": "rust/crates/ccusage/src/adapter/codex/mod.rs", "patch": "@@ -96,7 +96,7 @@ mod tests {\n }\n \n #[test]\n- fn keeps_matching_grouped_codex_usage_events_from_distinct_sessions() {\n+ fn dedupes_matching_grouped_codex_usage_events_from_distinct_sessions() {\n let usage_line = r#\"{\"timestamp\":\"2026-01-02T00:00:00.000Z\",\"type\":\"event_msg\",\"payload\":{\"type\":\"token_count\",\"info\":{\"model\":\"gpt-5\",\"last_token_usage\":{\"input_tokens\":100,\"cached_input_tokens\":10,\"output_tokens\":50,\"reasoning_output_tokens\":0,\"total_tokens\":150}}}}\"#;\n let fixture = fs_fixture!({\n \"sessions/session-a.jsonl\": usage_line,\n@@ -113,10 +113,10 @@ mod tests {\n \n assert_eq!(groups.len(), 1);\n let group = groups.get(\"2026-01-02\").unwrap();\n- assert_eq!(group.input_tokens, 200);\n- assert_eq!(group.cached_input_tokens, 20);\n- assert_eq!(group.output_tokens, 100);\n- assert_eq!(group.total_tokens, 300);\n+ assert_eq!(group.input_tokens, 100);\n+ assert_eq!(group.cached_input_tokens, 10);\n+ assert_eq!(group.output_tokens, 50);\n+ assert_eq!(group.total_tokens, 150);\n }\n \n #[test]", "status": "modified"}], "message": "fix(codex): dedupe copied rollout token events\n\nAlign the streaming Codex group aggregation dedupe key with the event loader so copied token_count rows from goal or rollout session files are counted once instead of once per session file.\n\nThis prevents daily and monthly table reports from double-counting copied Codex history while preserving the same token tuple based duplicate detection already used by JSON/all-agent loading paths.", "sha": "88ee6e1e1dc38b0ef4fb4380e09132c4fc6650b9"}], "post_review_commits": ["d3193940549512dc2e0f339e88d5c6892b48192d", "c7ffd05c10daa51736b99233b36ce072119e4a1f"], "pr_author": "ryoppippi", "pr_title": "fix(codex): dedupe goal rollout token events", "repo_name": "ccusage/ccusage"}, "repo": "ccusage/ccusage", "snapshot": "snapshots/23d704357de3e2be44ddca1ae4edd07521a311194ad002002a32361ceddd1811.pack", "split": "rl", "task_id": "294da74def9ed536920784c2fd0bf268558de6b3e32ad38376e645cd812732fa"} {"base_sha": "f823d33fd4b177713f2b756641fa4f8f1c52c5e8", "cohort": null, "context": {"canonical_pr_url": "https://github.com/oasisbaklawa2006/Oasis-Baklawa-Central/pull/236", "id": "2a1e555d647de6be4a27520878da1e1fa0f50c45a9584922fab98f8694698d84", "preparation_mode": "source-only", "snapshot": {"base_ref": "f823d33fd4b177713f2b756641fa4f8f1c52c5e8", "base_sha": "f823d33fd4b177713f2b756641fa4f8f1c52c5e8", "body": "", "head_ref": "aa2d99f60b58df2cc25ee195fb147d003eaf934a", "head_sha": "aa2d99f60b58df2cc25ee195fb147d003eaf934a", "name": "Oasis-Baklawa-Central", "number": 236, "owner": "oasisbaklawa2006", "pr_url": "https://github.com/oasisbaklawa2006/Oasis-Baklawa-Central/pull/236", "title": ""}}, "head_sha": "aa2d99f60b58df2cc25ee195fb147d003eaf934a", "metadata": {"group_id": "6dde624acef7eabc6250a4403acce721001f69e38e6cf40a6d7321e396420682", "snapshot": {"base_sha": "f823d33fd4b177713f2b756641fa4f8f1c52c5e8", "external_requirements": [], "head_sha": "aa2d99f60b58df2cc25ee195fb147d003eaf934a", "objects": 1755, "objects_sha256": "dcd8e8a71a2ad0e4e198691f1b72fef0fa8d33ae024a6e1e37f3beea93501a16", "patch_sha256": "7088d2a98f12f5746b6fa233559443427b299774c309f6b09f9a6673f604b083"}}, "pr_number": 236, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "c467d7376ef3", "description": "The intake trigger suppressed duplicates only on source_message_id. A duplicate provider_message_id could violate its unique index and roll back the originating WhatsApp message insert, breaking durable capture.", "file_path": "supabase/migrations/20260718190000_wa_zero_loss_inbound_wiring.sql"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "c467d7376ef3", "description": "Inbound intake metadata and its capture audit event recorded only contact_id, leaving the required submitter, original communicator, and commercial customer roles ambiguous. The commercial customer must remain unresolved rather than be inferred from the sender.", "file_path": "supabase/migrations/20260718190000_wa_zero_loss_inbound_wiring.sql"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "101ab948bcdc", "description": "The migration contract test required a source_message_id-specific conflict target, so it did not protect against duplicate provider_message_id failures and would reject the broader idempotency fix.", "file_path": "src/lib/wa-governance/tests/whatsappZeroLossInboundWiringMigration.test.ts"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "101ab948bcdc", "description": "The migration contract tests did not verify that intake records persist the identity triad while leaving the commercial customer unresolved.", "file_path": "src/lib/wa-governance/tests/whatsappZeroLossInboundWiringMigration.test.ts"}], "commits_under_review": [{"author": "oasisbaklawa2006", "date": "2026-07-18T17:51:41Z", "files": [{"additions": 122, "deletions": 0, "filename": "supabase/migrations/20260718190000_wa_zero_loss_inbound_wiring.sql", "patch": "@@ -0,0 +1,122 @@\n+-- WhatsApp B2B zero-loss inbound wiring.\n+-- Canonical authority:\n+-- docs/WHATSAPP_CANONICAL_INTENT_AND_ZERO_LOSS_GOVERNANCE.md\n+-- docs/WHATSAPP_B2B_DOMAIN_BOUNDARY_AND_APP_PLACEMENT.md\n+-- Foundation migration:\n+-- 20260718173000_wa_zero_loss_intake_foundation.sql\n+--\n+-- Scope: every durable inbound WhatsApp message written to whatsapp_messages\n+-- receives exactly one governed intake record. This migration does not write\n+-- orders, order_items, sales_order_drafts, finance, dispatch, or inventory.\n+\n+create unique index whatsapp_business_intakes_source_message_unique\n+ on public.whatsapp_business_intakes(source_message_id)\n+ where source_message_id is not null;\n+\n+create or replace function public.capture_whatsapp_business_intake_from_message()\n+returns trigger\n+language plpgsql\n+security definer\n+set search_path = pg_catalog, public\n+as $$\n+declare\n+ normalized_content text := lower(coalesce(new.content, ''));\n+ inferred_kind text;\n+ inferred_state text;\n+ inferred_next_action text;\n+ created_intake_id uuid;\n+begin\n+ if new.direction is distinct from 'inbound' then\n+ return new;\n+ end if;\n+\n+ -- Noise and unsupported webhook events are filtered before whatsapp_messages.\n+ -- Any message that reaches this durable table must remain visible until classified.\n+ if\n+ normalized_content ~ '(order|need|send|want|box|boxes|carton|cartons|kg|pcs|pieces|rate|price|quote)'\n+ or normalized_content ~ '(sales order|purchase order|repeat order|same as before|previous order)'\n+ then\n+ inferred_kind := 'POTENTIAL_ORDER';\n+ inferred_state := 'RECEIVED';\n+ inferred_next_action := 'Review potential order and confirm customer, product, quantity, delivery, and commercial readiness.';\n+ elsif\n+ new.media_url is not null\n+ or coalesce(new.message_type, '') in ('image', 'document', 'audio', 'video')\n+ then\n+ inferred_kind := 'UNRESOLVED_RISK';\n+ inferred_state := 'AWAITING_CLASSIFICATION';\n+ inferred_next_action := 'Inspect inbound media and classify all business intents; preserve as unresolved risk until reviewed.';\n+ else\n+ inferred_kind := 'NON_ORDER_BUSINESS';\n+ inferred_state := 'AWAITING_CLASSIFICATION';\n+ inferred_next_action := 'Classify inbound WhatsApp message and route every identified business intent.';\n+ end if;\n+\n+ insert into public.whatsapp_business_intakes (\n+ business_domain,\n+ source_message_id,\n+ provider_message_id,\n+ intake_kind,\n+ lifecycle_state,\n+ disposition,\n+ assigned_team,\n+ next_action,\n+ reconciliation_status,\n+ metadata\n+ ) values (\n+ 'B2B',\n+ new.id,\n+ new.provider_message_id,\n+ inferred_kind,\n+ inferred_state,\n+ 'ACTIVE_PENDING',\n+ 'WHATSAPP_INTAKE',\n+ inferred_next_action,\n+ 'ACCOUNTED',\n+ jsonb_build_object(\n+ 'capture_source', 'whatsapp_messages_after_insert_trigger',\n+ 'message_type', new.message_type,\n+ 'contact_id', new.contact_id,\n+ 'captured_at', now()\n+ )\n+ )\n+ on conflict (source_message_id) where source_message_id is not null\n+ do nothing\n+ returning id into created_intake_id;\n+\n+ if created_intake_id is not null then\n+ insert into public.whatsapp_business_intake_audit_log (\n+ intake_id,\n+ event_type,\n+ actor_user_id,\n+ event_data\n+ ) values (\n+ created_intake_id,\n+ 'INBOUND_CAPTURED',\n+ null,\n+ jsonb_build_object(\n+ 'source_message_id', new.id,\n+ 'provider_message_id', new.provider_message_id,\n+ 'intake_kind', inferred_kind,\n+ 'lifecycle_state', inferred_state,\n+ 'assigned_team', 'WHATSAPP_INTAKE'\n+ )\n+ );\n+ end if;\n+\n+ return new;\n+end;\n+$$;\n+\n+revoke all on function public.capture_whatsapp_business_intake_from_message() from public;\n+revoke all on function public.capture_whatsapp_business_intake_from_message() from anon;\n+revoke all on function public.capture_whatsapp_business_intake_from_message() from authenticated;\n+\n+drop trigger if exists trg_capture_whatsapp_business_intake on public.whatsapp_messages;\n+create trigger trg_capture_whatsapp_business_intake\n+after insert on public.whatsapp_messages\n+for each row\n+execute function public.capture_whatsapp_business_intake_from_message();\n+\n+comment on function public.capture_whatsapp_business_intake_from_message() is\n+ 'Captures every durable inbound WhatsApp message into the governed B2B zero-loss intake ledger. Never creates executable orders.';", "status": "added"}], "message": "feat(whatsapp): wire inbound messages to zero-loss intake ledger", "sha": "bfc6421fc537325dd96e325dc9dc444a67b56697"}, {"author": "oasisbaklawa2006", "date": "2026-07-18T17:52:03Z", "files": [{"additions": 84, "deletions": 0, "filename": "src/lib/wa-governance/tests/whatsappZeroLossInboundWiringMigration.test.ts", "patch": "@@ -0,0 +1,84 @@\n+import { readFileSync } from \"node:fs\";\n+import { join } from \"node:path\";\n+import { describe, expect, it } from \"vitest\";\n+\n+const REPO_ROOT = join(import.meta.dirname, \"../../../..\");\n+const MIGRATION_PATH = \"supabase/migrations/20260718190000_wa_zero_loss_inbound_wiring.sql\";\n+\n+function readMigration(): string {\n+ return readFileSync(join(REPO_ROOT, MIGRATION_PATH), \"utf8\");\n+}\n+\n+describe(\"WhatsApp zero-loss inbound wiring migration\", () => {\n+ const sql = readMigration();\n+\n+ it(\"traces to the canonical governance documents and foundation migration\", () => {\n+ expect(sql).toContain(\"docs/WHATSAPP_CANONICAL_INTENT_AND_ZERO_LOSS_GOVERNANCE.md\");\n+ expect(sql).toContain(\"docs/WHATSAPP_B2B_DOMAIN_BOUNDARY_AND_APP_PLACEMENT.md\");\n+ expect(sql).toContain(\"20260718173000_wa_zero_loss_intake_foundation.sql\");\n+ });\n+\n+ it(\"enforces exactly one intake per durable source message\", () => {\n+ expect(sql).toContain(\"whatsapp_business_intakes_source_message_unique\");\n+ expect(sql).toContain(\"on conflict (source_message_id) where source_message_id is not null\");\n+ expect(sql).toContain(\"do nothing\");\n+ });\n+\n+ it(\"captures only inbound whatsapp_messages rows\", () => {\n+ expect(sql).toContain(\"after insert on public.whatsapp_messages\");\n+ expect(sql).toContain(\"new.direction is distinct from 'inbound'\");\n+ });\n+\n+ it(\"keeps every captured message active, owned, and actionable\", () => {\n+ expect(sql).toContain(\"'ACTIVE_PENDING'\");\n+ expect(sql).toContain(\"'WHATSAPP_INTAKE'\");\n+ expect(sql).toContain(\"inferred_next_action\");\n+ expect(sql).toContain(\"'ACCOUNTED'\");\n+ });\n+\n+ it(\"treats order-like text as a potential order\", () => {\n+ expect(sql).toContain(\"inferred_kind := 'POTENTIAL_ORDER'\");\n+ expect(sql).toContain(\"inferred_state := 'RECEIVED'\");\n+ });\n+\n+ it(\"preserves media as unresolved risk until classification\", () => {\n+ expect(sql).toContain(\"inferred_kind := 'UNRESOLVED_RISK'\");\n+ expect(sql).toContain(\"inferred_state := 'AWAITING_CLASSIFICATION'\");\n+ expect(sql).toContain(\"Inspect inbound media and classify all business intents\");\n+ });\n+\n+ it(\"retains non-order business messages for governed classification\", () => {\n+ expect(sql).toContain(\"inferred_kind := 'NON_ORDER_BUSINESS'\");\n+ expect(sql).toContain(\"Classify inbound WhatsApp message and route every identified business intent\");\n+ });\n+\n+ it(\"writes an append-only audit event for each new intake\", () => {\n+ expect(sql).toContain(\"whatsapp_business_intake_audit_log\");\n+ expect(sql).toContain(\"'INBOUND_CAPTURED'\");\n+ });\n+\n+ it(\"does not expose the security-definer trigger function for direct invocation\", () => {\n+ expect(sql).toContain(\"security definer\");\n+ expect(sql).toContain(\"set search_path = pg_catalog, public\");\n+ expect(sql).toContain(\"revoke all on function public.capture_whatsapp_business_intake_from_message() from public\");\n+ expect(sql).toContain(\"revoke all on function public.capture_whatsapp_business_intake_from_message() from anon\");\n+ expect(sql).toContain(\"revoke all on function public.capture_whatsapp_business_intake_from_message() from authenticated\");\n+ });\n+\n+ it(\"never writes executable order, finance, dispatch, or inventory rows\", () => {\n+ for (const table of [\n+ \"orders\",\n+ \"order_items\",\n+ \"sales_order_drafts\",\n+ \"sales_order_draft_lines\",\n+ \"payments\",\n+ \"invoices\",\n+ \"dispatches\",\n+ \"inventory\",\n+ ]) {\n+ expect(sql).not.toMatch(new RegExp(`insert\\\\s+into\\\\s+public\\\\.${table}`, \"i\"));\n+ expect(sql).not.toMatch(new RegExp(`update\\\\s+public\\\\.${table}`, \"i\"));\n+ expect(sql).not.toMatch(new RegExp(`delete\\\\s+from\\\\s+public\\\\.${table}`, \"i\"));\n+ }\n+ });\n+});", "status": "added"}], "message": "test(whatsapp): cover zero-loss inbound wiring contract", "sha": "aa2d99f60b58df2cc25ee195fb147d003eaf934a"}], "post_review_commits": ["c467d7376ef3d0d80ab4afa78a0beeb54b032d0a", "101ab948bcdc262bb56be1b7146a0a89c8acb287"], "pr_author": "oasisbaklawa2006", "pr_title": "feat: wire inbound WhatsApp messages to zero-loss intake", "repo_name": "oasisbaklawa2006/Oasis-Baklawa-Central"}, "repo": "oasisbaklawa2006/Oasis-Baklawa-Central", "snapshot": "snapshots/6dde624acef7eabc6250a4403acce721001f69e38e6cf40a6d7321e396420682.pack", "split": "rl", "task_id": "2a1e555d647de6be4a27520878da1e1fa0f50c45a9584922fab98f8694698d84"} {"base_sha": "d1ac11fa7bac89e470fbe2b5c53f486133b875a9", "cohort": null, "context": {"canonical_pr_url": "https://github.com/netdata/netdata/pull/22027", "id": "2addf12d5c04909bafd9215bf667e3b50d6206b115557e3bd60c52c0eef86dad", "preparation_mode": "source-only", "snapshot": {"base_ref": "d1ac11fa7bac89e470fbe2b5c53f486133b875a9", "base_sha": "d1ac11fa7bac89e470fbe2b5c53f486133b875a9", "body": "", "head_ref": "176564850a23b33e8799b434baa06172fd81133b", "head_sha": "176564850a23b33e8799b434baa06172fd81133b", "name": "netdata", "number": 22027, "owner": "netdata", "pr_url": "https://github.com/netdata/netdata/pull/22027", "title": ""}}, "head_sha": "176564850a23b33e8799b434baa06172fd81133b", "metadata": {"group_id": "192c94dec04b45f4f096864c18f5ad1ed4d870250770925776a2f942f5d85fa6", "snapshot": {"base_sha": "d1ac11fa7bac89e470fbe2b5c53f486133b875a9", "external_requirements": [{"commit": "ec319a14394436f62663548d32eb320eeddd264a", "path": "src/aclk/aclk-schemas", "snapshot": "176564850a23b33e8799b434baa06172fd81133b", "type": "submodule"}, {"commit": "42f240d2a457834bcbdf4dc8b57237f97b5f5854", "path": "src/collectors/debugfs.plugin/libsensors/vendored", "snapshot": "176564850a23b33e8799b434baa06172fd81133b", "type": "submodule"}, {"commit": "ec319a14394436f62663548d32eb320eeddd264a", "path": "src/aclk/aclk-schemas", "snapshot": "d1ac11fa7bac89e470fbe2b5c53f486133b875a9", "type": "submodule"}, {"commit": "42f240d2a457834bcbdf4dc8b57237f97b5f5854", "path": "src/collectors/debugfs.plugin/libsensors/vendored", "snapshot": "d1ac11fa7bac89e470fbe2b5c53f486133b875a9", "type": "submodule"}], "head_sha": "176564850a23b33e8799b434baa06172fd81133b", "objects": 8421, "objects_sha256": "3eb709115904c6232cc50c3a85999bb10c9b45a0783bec327ee37b4bc3d8f1e2", "patch_sha256": "8e10fe75218c8f9e001cd9074a042213c3200f326502cda97b672098d34d1bee"}}, "pr_number": 22027, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "c6fbc753f67e", "description": "The remote-file check used the curl variable without first detecting curl, so it could skip an available curl executable.", "file_path": "packaging/installer/netdata-updater.sh"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "e3f85d4529fb", "description": "The remote-file check skipped wget whenever curl was present, even if the curl HEAD request failed, preventing fallback on network, proxy, or SSL errors.", "file_path": "packaging/installer/netdata-updater.sh"}], "commits_under_review": [{"author": "Ferroin", "date": "2026-03-24T11:10:26Z", "files": [{"additions": 40, "deletions": 1, "filename": "packaging/installer/netdata-updater.sh", "patch": "@@ -655,6 +655,45 @@ download() {\n fi\n }\n \n+check_for_remote_file() {\n+ url=\"${1}\"\n+ succeeded=0\n+ checked=0\n+\n+ if echo \"${url}\" | grep -Eq \"^file:///\"; then\n+ [ -e \"${url#file://}\" ] || return 1\n+ return 0\n+ elif [ -n \"${NETDATA_ASSUME_REMOTE_FILES_ARE_PRESENT}\" ]; then\n+ return 0\n+ fi\n+\n+ if [ -n \"${curl}\" ]; then\n+ checked=1\n+\n+ if \"${curl}\" --output /dev/null --silent --head --fail \"${url}\"; then\n+ succeeded=1\n+ fi\n+ fi\n+\n+ if [ \"${checked}\" -eq 0 ]; then\n+ if command -v wget > /dev/null 2>&1; then\n+ checked=1\n+\n+ if wget -S --spider \"${url}\" 2>&1 | grep -q 'HTTP/1.1 200 OK'; then\n+ succeeded=1\n+ fi\n+ fi\n+ fi\n+\n+ if [ \"${succeeded}\" -eq 1 ]; then\n+ return 0\n+ elif [ \"${checked}\" -eq 1 ]; then\n+ return 1\n+ else\n+ return 255\n+ fi\n+}\n+\n get_netdata_latest_tag() {\n url=\"${1}/latest\"\n \n@@ -1210,7 +1249,7 @@ update_binpkg() {\n info \"Checking if native packages are still being published for this platform.\"\n \n set +e\n- _safe_download \"${check_url}\" /dev/null\n+ check_for_remote_file \"${check_url}\"\n ret=$?\n set -e\n ", "status": "modified"}], "message": "Fix handling of package publishing detection in updater script.", "sha": "176564850a23b33e8799b434baa06172fd81133b"}], "post_review_commits": ["c6fbc753f67ec240c8618cf5da1cb7a2c0384d9a", "e3f85d4529fb37583898876538cee332745be799"], "pr_author": "Ferroin", "pr_title": "Fix handling of package publishing detection in updater script.", "repo_name": "netdata/netdata"}, "repo": "netdata/netdata", "snapshot": "snapshots/192c94dec04b45f4f096864c18f5ad1ed4d870250770925776a2f942f5d85fa6.pack", "split": "rl", "task_id": "2addf12d5c04909bafd9215bf667e3b50d6206b115557e3bd60c52c0eef86dad"} {"base_sha": "e9705bdc753b6511a3b866f9877a79a1a6139c3e", "cohort": null, "context": {"canonical_pr_url": "https://github.com/equuscapital/hackathon-anhembi/pull/4", "id": "2cf740a434f369eba2877cffe4f54646235d7ac07ce93a84b97b19f55b2d021d", "preparation_mode": "source-only", "snapshot": {"base_ref": "e9705bdc753b6511a3b866f9877a79a1a6139c3e", "base_sha": "e9705bdc753b6511a3b866f9877a79a1a6139c3e", "body": "", "head_ref": "c9fd4b71bccffc6b4f845ed47e38f148866b1727", "head_sha": "c9fd4b71bccffc6b4f845ed47e38f148866b1727", "name": "hackathon-anhembi", "number": 4, "owner": "equuscapital", "pr_url": "https://github.com/equuscapital/hackathon-anhembi/pull/4", "title": ""}}, "head_sha": "c9fd4b71bccffc6b4f845ed47e38f148866b1727", "metadata": {"group_id": "9da5dd52ef98c57cb1f1567eb6a33bad1a20ad69eab5ed63fb5754062138769d", "snapshot": {"base_sha": "e9705bdc753b6511a3b866f9877a79a1a6139c3e", "external_requirements": [], "head_sha": "c9fd4b71bccffc6b4f845ed47e38f148866b1727", "objects": 17, "objects_sha256": "ccf4909ba00b5b3d03cdf1f655df9212a65853e670882160d8ee035f00fbac2b", "patch_sha256": "8fd14b9da71cc530836c6ca4c16b9e0bdf1dfe7a1653b739dd0abe33f8539181"}}, "pr_number": 4, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "d30bf95212e1", "description": "The density filter accepted candidate locations with only five establishments in a roughly 500 m cell, allowing sparse or edge locations into the top opportunities instead of requiring ten in a roughly 100 m cell.", "file_path": "worker.js"}, {"action_id": "A2", "action_type": "improvement", "category": "style", "commit_sha": "d30bf95212e1", "description": "The opportunity heatmap used a green gradient rather than the intended lighter blue gradient, and its layer legend showed the old green color.", "file_path": "index.html"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "d30bf95212e1", "description": "Opportunity point details labeled the density count as being within 500 m, which would misrepresent the updated 100 m density filter.", "file_path": "index.html"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "8d79bcfedd03", "description": "CORS allowed credentials while also allowing every origin with a wildcard, an incompatible configuration for credentialed cross-origin requests.", "file_path": "server.py"}], "commits_under_review": [{"author": "leonardonovais", "date": "2026-04-25T17:26:18Z", "files": [{"additions": 9, "deletions": 0, "filename": "server.py", "patch": "@@ -26,6 +26,7 @@\n \n import duckdb\n from fastapi import FastAPI, Query\n+from fastapi.middleware.cors import CORSMiddleware\n from fastapi.responses import FileResponse, JSONResponse\n from fastapi.staticfiles import StaticFiles\n from pydantic import BaseModel\n@@ -47,6 +48,14 @@\n # ─── App FastAPI ────────────────────────────────────────────────\n app = FastAPI(title=\"Nearby API\", version=\"2.0.0\")\n \n+app.add_middleware(\n+ CORSMiddleware,\n+ allow_origins=[\"*\"],\n+ allow_credentials=True,\n+ allow_methods=[\"*\"],\n+ allow_headers=[\"*\"],\n+)\n+\n # Conexão DuckDB (global, read-only)\n con = None\n parquet_path = None", "status": "modified"}], "message": "fix: add CORS middleware to allow cross-origin requests\n\nCo-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>", "sha": "c9fd4b71bccffc6b4f845ed47e38f148866b1727"}], "post_review_commits": ["d30bf95212e10b68c83588ac11a7d6bca994231c", "8d79bcfedd036c54f2966b3af915cae631167587"], "pr_author": "devin-ai-integration[bot]", "pr_title": "fix: CORS + density filter 10/100m + light blue opportunity heatmap", "repo_name": "equuscapital/hackathon-anhembi"}, "repo": "equuscapital/hackathon-anhembi", "snapshot": "snapshots/9da5dd52ef98c57cb1f1567eb6a33bad1a20ad69eab5ed63fb5754062138769d.pack", "split": "rl", "task_id": "2cf740a434f369eba2877cffe4f54646235d7ac07ce93a84b97b19f55b2d021d"} {"base_sha": "c830792f9bd5ddca58f5ddf919e9b87fc3d62ac0", "cohort": null, "context": {"canonical_pr_url": "https://github.com/Abhash-Chakraborty/Find/pull/281", "id": "2d676ee6e989515903786da32babdf6d72e2064aea2e27b1434bb6b6ec22897d", "preparation_mode": "source-only", "snapshot": {"base_ref": "c830792f9bd5ddca58f5ddf919e9b87fc3d62ac0", "base_sha": "c830792f9bd5ddca58f5ddf919e9b87fc3d62ac0", "body": "", "head_ref": "418a29f5e6a142dac5b131c7ebedd82e15fc40f0", "head_sha": "418a29f5e6a142dac5b131c7ebedd82e15fc40f0", "name": "Find", "number": 281, "owner": "Abhash-Chakraborty", "pr_url": "https://github.com/Abhash-Chakraborty/Find/pull/281", "title": ""}}, "head_sha": "418a29f5e6a142dac5b131c7ebedd82e15fc40f0", "metadata": {"group_id": "a7f7e7e10b5ff59041418516e688913652fdaa6892f604b27e26a0f28758d17d", "snapshot": {"base_sha": "c830792f9bd5ddca58f5ddf919e9b87fc3d62ac0", "external_requirements": [], "head_sha": "418a29f5e6a142dac5b131c7ebedd82e15fc40f0", "objects": 264, "objects_sha256": "b4434368a75c1c7cfe4e381ab9f7f02c564077b4e0792e944c4ae26b8ae0b7d2", "patch_sha256": "2e964bf3580e86191f5b6c2c395306a5f2566bfc4bb1081a17ab76eeb254ded4"}}, "pr_number": 281, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "documentation", "commit_sha": "a0b4d800a6a9", "description": "The migration table stated that both MINIO_* and STORAGE_* settings were already accepted and that STORAGE_* already took precedence, although the current runtime reads only MINIO_* settings.", "file_path": "docs/plans/not-started/storage-provider-neutrality-adr.md"}, {"action_id": "A2", "action_type": "improvement", "category": "documentation", "commit_sha": "5f5ac1ce0a60", "description": "The table's “New Alias” and “Status” headings, together with its removal note, still made the proposed STORAGE_* settings and legacy-key removal sound like current or unconditional behavior rather than steps governed by the planned migration timeline.", "file_path": "docs/plans/not-started/storage-provider-neutrality-adr.md"}], "commits_under_review": [{"author": "Janeeshareddy", "date": "2026-05-28T13:25:45Z", "files": [{"additions": 25, "deletions": 0, "filename": "docs/plans/not-started/storage-provider-neutrality-adr.md", "patch": "@@ -307,6 +307,31 @@ For compatibility, Find can temporarily support `MINIO_*` as aliases.\n \n Alias timeline: introduce `STORAGE_BACKEND`, `STORAGE_ENDPOINT`, `STORAGE_ACCESS_KEY`, `STORAGE_SECRET_KEY`, `STORAGE_BUCKET`, `STORAGE_SECURE`, `STORAGE_PUBLIC_ENDPOINT`, `STORAGE_PUBLIC_READ`, and `STORAGE_AUTO_CREATE_BUCKET` first, then support existing `MINIO_*` aliases for 2-3 releases or until RustFS validation completes, whichever comes first. Before removing the aliases, document a clear fallback: copy the existing `MINIO_*` values into the matching `STORAGE_*` keys and keep `STORAGE_BACKEND=s3`.\n \n+## Configuration Alias Migration Table\n+\n+The table below maps current `MINIO_*` variables to the proposed\n+provider-neutral `STORAGE_*` aliases. Both names are accepted during\n+the transition period.\n+\n+| Current Variable (`MINIO_*`) | New Alias (`STORAGE_*`) | Description | Status |\n+|------------------------------|----------------------------|----------------------------------------------|-------------------------|\n+| `MINIO_ENDPOINT` | `STORAGE_ENDPOINT` | Hostname / URL of the object storage service | `STORAGE_*` preferred |\n+| `MINIO_ACCESS_KEY` | `STORAGE_ACCESS_KEY` | Access key ID / username | `STORAGE_*` preferred |\n+| `MINIO_SECRET_KEY` | `STORAGE_SECRET_KEY` | Secret access key / password | `STORAGE_*` preferred |\n+| `MINIO_BUCKET` | `STORAGE_BUCKET` | Default bucket name | `STORAGE_*` preferred |\n+| `MINIO_SECURE` | `STORAGE_SECURE` | Enforce TLS (`true` / `false`) | `STORAGE_*` preferred |\n+| `MINIO_PUBLIC_ENDPOINT` | `STORAGE_PUBLIC_ENDPOINT` | Publicly accessible base URL for assets | `STORAGE_*` preferred |\n+| `MINIO_PUBLIC_READ` | `STORAGE_PUBLIC_READ` | Whether bucket allows public reads | `STORAGE_*` preferred |\n+| *(not present)* | `STORAGE_BACKEND` | Storage provider type (e.g. `s3`) | New — no alias needed |\n+| *(not present)* | `STORAGE_AUTO_CREATE_BUCKET` | Auto-create bucket on startup | New — no alias needed |\n+\n+> **Backward compatibility:** `MINIO_*` variables are compatibility aliases and\n+> remain fully supported during the transition period. If both a `MINIO_*` and\n+> its `STORAGE_*` counterpart are set, `STORAGE_*` takes precedence.\n+> `MINIO_*` aliases will be removed after 2–3 releases or once RustFS\n+> validation completes, whichever comes first. No runtime behavior is\n+> changed by this document.\n+\n ## Tradeoff Analysis For The Recommended Path\n \n ### Recommended path", "status": "modified"}], "message": "docs: add MINIO_* to STORAGE_* alias migration table (#267)", "sha": "418a29f5e6a142dac5b131c7ebedd82e15fc40f0"}], "post_review_commits": ["a0b4d800a6a98a3e64acd1183f6f82f6aea4ed0b", "5f5ac1ce0a60f542757afe400e38c9080f09ae27", "60cc52831ad1516b816d11ca07b4e631a78b288b"], "pr_author": "Janeeshareddy", "pr_title": "docs: add storage config alias migration table", "repo_name": "Abhash-Chakraborty/Find"}, "repo": "Abhash-Chakraborty/Find", "snapshot": "snapshots/a7f7e7e10b5ff59041418516e688913652fdaa6892f604b27e26a0f28758d17d.pack", "split": "rl", "task_id": "2d676ee6e989515903786da32babdf6d72e2064aea2e27b1434bb6b6ec22897d"} {"base_sha": "c32ed703cb7857d4b2bd438f6ea4cb4415cfcbef", "cohort": null, "context": {"canonical_pr_url": "https://github.com/acoseac/1-bit-bridge/pull/111", "id": "313183e03f22f6e74e5d2d2024bc68f9e2eb3a29b3a2594dc158c88483f3fc33", "preparation_mode": "source-only", "snapshot": {"base_ref": "c32ed703cb7857d4b2bd438f6ea4cb4415cfcbef", "base_sha": "c32ed703cb7857d4b2bd438f6ea4cb4415cfcbef", "body": "", "head_ref": "af451fd941fccf58a6a0ef123e14527aae538701", "head_sha": "af451fd941fccf58a6a0ef123e14527aae538701", "name": "1-bit-bridge", "number": 111, "owner": "acoseac", "pr_url": "https://github.com/acoseac/1-bit-bridge/pull/111", "title": ""}}, "head_sha": "af451fd941fccf58a6a0ef123e14527aae538701", "metadata": {"group_id": "8c7a4fb5c81010d80d2ffc6dd4450f269f4179f5528d257323c8f451b236ad35", "snapshot": {"base_sha": "c32ed703cb7857d4b2bd438f6ea4cb4415cfcbef", "external_requirements": [], "head_sha": "af451fd941fccf58a6a0ef123e14527aae538701", "objects": 242, "objects_sha256": "f6c5758351cbfbebe4afe447bac2d4ce19648a5a601abcd5364bd967e8415fb2", "patch_sha256": "d1a676fe11abab7f1bc4292d86c787c210bef684eb3e95886db21b755ac80149"}}, "pr_number": 111, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "performance", "commit_sha": "868481f2b672", "description": "The stats endpoint ran `transcode.PrecheckSox()` on every snapshot, spawning a process on each five-second poll instead of caching the result as the admin tile does.", "file_path": "cmd/bridge/main.go"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "868481f2b672", "description": "The disabled-pool test could pass with an incorrect `cachedVariants` value because it only checked whether the response contained the digit `5`; it also did not verify the exact `cachedBytes` value.", "file_path": "internal/api/upscale_stats_test.go"}, {"action_id": "A3", "action_type": "fix", "category": "documentation", "commit_sha": "868481f2b672", "description": "The fenced JSON response example lacked a blank line before the opening fence, violating markdownlint MD031.", "file_path": "PROTOCOL.md"}], "commits_under_review": [{"author": "ars", "date": "2026-05-01T07:41:23Z", "files": [{"additions": 38, "deletions": 1, "filename": "PROTOCOL.md", "patch": "@@ -283,7 +283,44 @@ Distinct from `upscale_disabled`. The pool's queue cap is operator-tunable via `\n \n **Idempotency**: the worker pool dedups jobs on `(source_path, variant_id)`. A duplicate request while a job is queued or running is a silent no-op (still counted in `enqueued`); the iOS app can mash \"Generate\" without server-side duplicate work.\n \n-**Asynchronous completion**: the response returns as soon as the jobs are queued. iOS discovers completed variants via the next `/v1/manifest` sync (which advertises the new `Track.variants` entries). There is no per-job status endpoint in v1.2; the manifest IS the authoritative completion signal.\n+**Asynchronous completion**: the response returns as soon as the jobs are queued. iOS discovers completed variants via the next `/v1/manifest` sync (which advertises the new `Track.variants` entries). For pool-level visibility while jobs are in flight (queue depth, lifetime totals, failure counts) iOS calls the companion `GET /v1/upscale/stats` endpoint described below; for per-track completion the manifest is still the authoritative signal.\n+\n+### `GET /v1/upscale/stats` (additive, since v1.2)\n+\n+Snapshot of the upscale feature's runtime + on-disk state. Designed for the iOS app's per-share \"Upscaling\" management section to show the operator how many jobs are queued, in flight, finished, or failed without surfacing the admin console externally. The wire shape is intentionally identical to the admin tile's `/api/upscale/stats` payload — same numbers in both places.\n+\n+**Authentication**: standard `Authorization: Bearer ` (same rule as every other `/v1/*` endpoint except `/v1/health` and the pairing routes).\n+\n+**Response** (`200 OK`, JSON):\n+```json\n+{\n+ \"enabled\": true,\n+ \"soxAvailable\": true,\n+ \"pool\": {\n+ \"workers\": 4,\n+ \"queueCap\": 5000,\n+ \"queueLen\": 12,\n+ \"inflight\": 4,\n+ \"enqueued\": 142,\n+ \"done\": 126,\n+ \"failed\": 0\n+ },\n+ \"cachedVariants\": 138,\n+ \"cachedBytes\": 4823917568\n+}\n+```\n+\n+| Field | Meaning |\n+|---|---|\n+| `enabled` | Live runtime state. False when `cfg.Upscale.Enabled` is false OR the sox-precheck demoted the feature at startup OR the operator just PATCHed the feature off (the long-lived Pool may still be alive, but the contract is \"feature is off live\", matching `/v1/health.upscaleEnabled`). |\n+| `soxAvailable` | The current `sox(1)`-on-PATH probe result. Omitted when the test harness didn't wire a precheck closure. Operators can install sox without restarting the bridge — within ~30 s the field flips to `true`. |\n+| `pool` | Live worker-pool snapshot. **Omitted when `enabled` is false** (no pool to query). `queueCap` is operator-tunable via `cfg.Upscale.QueueCap` (default 5000). `enqueued`/`done`/`failed` are lifetime counters since the bridge process started — they reset on restart; `cachedVariants` survives. |\n+| `cachedVariants` | Row count from `track_variants`. Survives across restarts and reflects historical conversion work — non-zero even when `enabled == false` if the operator disabled the feature without `--gc`. |\n+| `cachedBytes` | Total size of all sidecar files, summed from `track_variants.size_bytes`. Helps the operator gauge disk usage before deciding to re-enable or `--gc`. |\n+\n+**Empty / disabled bridge**: returns the zero-value response `{\"enabled\": false, \"cachedVariants\": 0, \"cachedBytes\": 0}`. iOS treats this identically to a 404 from a pre-v1.2 bridge — render \"feature off\" without distinguishing a missing endpoint from a disabled feature.\n+\n+**Polling cadence**: iOS polls every 5 s **only while the management page is foregrounded** (never in background). The handler is cheap enough — single SQL `COUNT` + a mutex-protected pool snapshot + a `sox` precheck — to absorb that cadence on Pi-class hosts.\n \n ### `GET /v1/artwork/{mbid}?size=` and `GET /v1/artist-image/{mbid}`\n ", "status": "modified"}, {"additions": 96, "deletions": 0, "filename": "cmd/bridge/main.go", "patch": "@@ -44,6 +44,13 @@ import (\n \t\"github.com/acoseac/1-bit-bridge/internal/version\"\n )\n \n+// Package-scoped logger for the cmd/bridge wiring layer. Most\n+// startup output is `fmt.Fprintf(stdout/stderr)` because it's user-\n+// facing; this is for backend-style telemetry from helpers like\n+// upscaleStatsAdapter that fire on every request and shouldn't spam\n+// the operator's terminal but should be visible via `bridge logs`.\n+var logger = logging.Component(\"bridge\")\n+\n // variantStoreAdapter implements api.VariantStore on top of a\n // manifest.Provider. Just translates between the two packages'\n // equivalent record shapes — the api package can't import the\n@@ -170,6 +177,65 @@ func (a *upscaleEnqueuerAdapter) EnqueueOne(libraryRelativePath string) error {\n \t}\n }\n \n+// upscaleStatsAdapter implements api.UpscaleStatsProvider. Mirrors\n+// the admin /api/upscale/stats handler's data sources field-for-\n+// field so the operator's Settings tile and a paired iOS client see\n+// the same numbers.\n+//\n+// Two pool-related closures (rather than a captured `*transcode.Pool`):\n+// the pool reference itself can be nil (operator never enabled the\n+// feature) AND the operator can flip `cfg.Upscale.Enabled = false`\n+// mid-flight without restart, leaving a live but logically-disabled\n+// Pool. The closures evaluate both conditions at snapshot time so\n+// `enabled` and the `pool` payload move together — same gating the\n+// admin `UpscaleStats` closure already uses.\n+type upscaleStatsAdapter struct {\n+\tpool func() *transcode.Pool\n+\tenabled func() bool\n+\tstore *manifest.Store\n+}\n+\n+func (a *upscaleStatsAdapter) UpscaleStatsSnapshot() api.UpscaleStats {\n+\tvar snap api.UpscaleStats\n+\tif a.enabled() {\n+\t\tif p := a.pool(); p != nil {\n+\t\t\ts := p.Stats()\n+\t\t\tsnap.Pool = &api.UpscalePoolStats{\n+\t\t\t\tWorkers: s.Workers,\n+\t\t\t\tQueueCap: s.QueueCap,\n+\t\t\t\tQueueLen: s.QueueLen,\n+\t\t\t\tInflight: s.Inflight,\n+\t\t\t\tEnqueued: s.Enqueued,\n+\t\t\t\tDone: s.Done,\n+\t\t\t\tFailed: s.Failed,\n+\t\t\t}\n+\t\t}\n+\t}\n+\tsnap.Enabled = (snap.Pool != nil)\n+\tif err := transcode.PrecheckSox(); err == nil {\n+\t\tt := true\n+\t\tsnap.SoxAvailable = &t\n+\t} else {\n+\t\tf := false\n+\t\tsnap.SoxAvailable = &f\n+\t}\n+\tif a.store != nil {\n+\t\tcount, bytes, err := a.store.CountVariants()\n+\t\tif err != nil {\n+\t\t\t// Same degrade-and-log policy the admin tile uses\n+\t\t\t// (PR #110): a SQL failure here shouldn't blank the\n+\t\t\t// whole response. Live counters still go out; the\n+\t\t\t// caller sees `cachedVariants: 0, cachedBytes: 0` and\n+\t\t\t// the operator can find the failure in logs.\n+\t\t\tlogger.Warn(\"upscale stats: count variants\", \"err\", err)\n+\t\t} else {\n+\t\t\tsnap.CachedVariants = count\n+\t\t\tsnap.CachedBytes = bytes\n+\t\t}\n+\t}\n+\treturn snap\n+}\n+\n // updateInfoAdapter bridges *updater.Updater to api.UpdaterStatus +\n // admin's read-side without coupling those packages to the updater\n // type. Trivial; lives here at the wiring point so the api / admin\n@@ -864,6 +930,36 @@ func runServe(ctx context.Context, opts serveOpts, stdout, stderr io.Writer) int\n \t\t\toutputDir: filepath.Join(cfg.DataDir, \"transcoded\"),\n \t\t})\n \t}\n+\n+\t// /v1/upscale/stats wiring. Always registered so paired iOS\n+\t// clients can render a clean \"feature off\" state on bridges where\n+\t// the operator hasn't enabled upscaling — same nil-safe contract\n+\t// the admin tile uses. The closure mirrors the admin\n+\t// /api/upscale/stats handler exactly so the operator's Settings\n+\t// page and the iOS management section show the same numbers.\n+\t//\n+\t// Three sources combined:\n+\t// 1. Live pool counters — only when upscalePool != nil AND\n+\t// cfg.Upscale.Enabled (operator can disable mid-flight via a\n+\t// PATCH; the long-lived Pool stays alive until restart, but\n+\t// we honour the live flag and report no pool to keep the wire\n+\t// semantics in lockstep with /v1/health.upscaleEnabled).\n+\t// 2. Cached-variants count + total bytes from `track_variants`\n+\t// — survives across restarts and reflects historical work,\n+\t// so it stays non-zero when the feature was disabled without\n+\t// `--gc`. SQL failure degrades to \"0 cached\" with a logged\n+\t// warning rather than turning the whole response into a 5xx.\n+\t// 3. Sox-availability probe — same `transcode.PrecheckSox` the\n+\t// admin tile consumes, gated by the same 30 s TTL cache the\n+\t// admin handler uses (the admin cache holds it; we re-probe\n+\t// directly here, accepting one extra fork-exec per 5 s poll\n+\t// since iOS only polls when the management page is fore-\n+\t// grounded — typically zero polls per minute on average).\n+\tapiSrv.WithUpscaleStats(&upscaleStatsAdapter{\n+\t\tpool: func() *transcode.Pool { return upscalePool },\n+\t\tenabled: func() bool { return upscalePool != nil && cfg.Upscale.Enabled },\n+\t\tstore: manifestStore,\n+\t})\n \thttpSrv := &http.Server{\n \t\tAddr: cfg.ListenAddress,\n \t\tHandler: apiSrv.Handler(),", "status": "modified"}, {"additions": 32, "deletions": 14, "filename": "internal/api/api.go", "patch": "@@ -45,20 +45,21 @@ var logger = logging.Component(\"api\")\n \n // Server owns the http.Handler and the per-request state it needs.\n type Server struct {\n-\tcfg *config.Config\n-\tstore *auth.Store\n-\tresolver *bridgefs.Resolver\n-\tmanifest ManifestProvider\n-\tartworkDirs ArtworkDirProvider\n-\tmbidProbe MBIDProbe\n-\tupdater UpdaterStatus\n-\tsessions SessionTracker\n-\tpairing *pairing.Store\n-\tvariantStore VariantStore // nil unless WithUpscale(true, vs) called\n-\tupscaleEnabled bool // mirrors cfg.Upscale.Enabled (and sox-probe outcome)\n-\tupscaleEnqueuer UpscaleEnqueuer // nil unless WithUpscaleEnqueuer wired (Phase 2.5)\n-\tfingerprint string\n-\tstartedAt time.Time\n+\tcfg *config.Config\n+\tstore *auth.Store\n+\tresolver *bridgefs.Resolver\n+\tmanifest ManifestProvider\n+\tartworkDirs ArtworkDirProvider\n+\tmbidProbe MBIDProbe\n+\tupdater UpdaterStatus\n+\tsessions SessionTracker\n+\tpairing *pairing.Store\n+\tvariantStore VariantStore // nil unless WithUpscale(true, vs) called\n+\tupscaleEnabled bool // mirrors cfg.Upscale.Enabled (and sox-probe outcome)\n+\tupscaleEnqueuer UpscaleEnqueuer // nil unless WithUpscaleEnqueuer wired (Phase 2.5)\n+\tupscaleStatsProvider UpscaleStatsProvider // nil unless WithUpscaleStats wired (v1.2 management UI)\n+\tfingerprint string\n+\tstartedAt time.Time\n }\n \n // ErrUpscaleQueueFull is the typed sentinel UpscaleEnqueuer\n@@ -282,6 +283,22 @@ func (s *Server) WithPairing(p *pairing.Store) *Server {\n \treturn s\n }\n \n+// WithUpscaleStats attaches the snapshot provider for GET\n+// /v1/upscale/stats. Optional — when nil the endpoint returns the\n+// zero-value UpscaleStats (`enabled=false`, no pool, no sox\n+// availability), which iOS treats as \"feature off\" without\n+// distinguishing missing-endpoint from disabled-feature. Lets older\n+// bridges expose the route without the wiring overhead.\n+//\n+// Wired in cmd/bridge serve startup with the same closure the admin\n+// `/api/upscale/stats` tile already consumes — the two surfaces\n+// stay in lockstep so the admin operator and the paired iOS client\n+// see the same numbers.\n+func (s *Server) WithUpscaleStats(p UpscaleStatsProvider) *Server {\n+\ts.upscaleStatsProvider = p\n+\treturn s\n+}\n+\n // Resolver returns the internal path Resolver so the admin console can\n // call SetRoots when adding or removing a library root at runtime. The\n // api handlers and admin handlers deliberately share the same Resolver\n@@ -308,6 +325,7 @@ func (s *Server) Handler() http.Handler {\n \t// when no Store is wired the handlers themselves return\n \t// `pairing_not_supported`.\n \tmux.HandleFunc(\"POST /v1/upscale\", s.authed(s.upscaleRequest))\n+\tmux.HandleFunc(\"GET /v1/upscale/stats\", s.authed(s.upscaleStats))\n \tmux.HandleFunc(\"POST /v1/pairing/requests\", s.pairingRequest)\n \tmux.HandleFunc(\"GET /v1/pairing/{requestID}\", s.pairingPoll)\n \tmux.HandleFunc(\"DELETE /v1/pairing/{requestID}\", s.pairingDelete)", "status": "modified"}, {"additions": 90, "deletions": 0, "filename": "internal/api/upscale_stats.go", "patch": "@@ -0,0 +1,90 @@\n+package api\n+\n+import (\n+\t\"net/http\"\n+)\n+\n+// UpscaleStatsProvider is the interface GET /v1/upscale/stats reads.\n+// Mirrors the admin tile's data sources but lives here so the api\n+// package doesn't import internal/admin or internal/transcode.\n+//\n+// The cmd/bridge wiring constructs an adapter that returns the same\n+// pool snapshot the admin handler consumes — the two surfaces stay\n+// in lockstep.\n+//\n+// Nil-safe: when WithUpscaleStats wasn't called (test harness, or\n+// builds without the upscale wiring), the handler returns the\n+// zero-value UpscaleStats — `enabled=false, cachedVariants=0,\n+// cachedBytes=0, pool=nil, soxAvailable=nil`. iOS renders that as\n+// \"feature off\" without distinguishing a missing endpoint from a\n+// disabled feature, which matches the /v1/health.upscaleEnabled\n+// contract iOS already gates on.\n+type UpscaleStatsProvider interface {\n+\tUpscaleStatsSnapshot() UpscaleStats\n+}\n+\n+// UpscaleStats is the wire shape GET /v1/upscale/stats returns.\n+//\n+// Field-for-field compatible with the admin /api/upscale/stats\n+// payload — the JSON shapes intentionally match so an operator\n+// inspecting the bridge with `curl -k https://…/v1/upscale/stats`\n+// (with bearer token) sees the same body the Settings tile is\n+// already showing them. iOS uses it for the \"Upscaling\" management\n+// section inside BridgeEditorView (counts of cached / in-flight /\n+// failed jobs).\n+//\n+// - Enabled mirrors live runtime state, NOT the persisted\n+// `cfg.Upscale.Enabled` flag. The two diverge in two real\n+// cases the admin handler documents (see CLAUDE.md / PR #110):\n+// (a) startup demoted the feature when sox-precheck failed\n+// even though the flag was on; (b) the operator just PATCHed\n+// the flag off but the long-lived Pool is still alive until\n+// restart. Both surface as `pool == nil` from the wiring\n+// closure, and we report `enabled = (pool != nil)` so the\n+// iOS-facing /v1/health.upscaleEnabled and this endpoint\n+// agree about what \"active\" means.\n+// - Pool is omitted when the feature is off (no pool to query).\n+// - SoxAvailable is omitted when the test harness didn't wire a\n+// precheck closure.\n+type UpscaleStats struct {\n+\tEnabled bool `json:\"enabled\"`\n+\tSoxAvailable *bool `json:\"soxAvailable,omitempty\"`\n+\tPool *UpscalePoolStats `json:\"pool,omitempty\"`\n+\tCachedVariants int `json:\"cachedVariants\"`\n+\tCachedBytes int64 `json:\"cachedBytes\"`\n+}\n+\n+// UpscalePoolStats mirrors `transcode.PoolStats` field-for-field\n+// but lives here so the api package compiles without importing\n+// internal/transcode. The wiring closure in cmd/bridge/main.go\n+// translates between the two value types — same indirection the\n+// admin package already uses.\n+type UpscalePoolStats struct {\n+\tWorkers int `json:\"workers\"`\n+\tQueueCap int `json:\"queueCap\"`\n+\tQueueLen int `json:\"queueLen\"`\n+\tInflight int `json:\"inflight\"`\n+\tEnqueued uint64 `json:\"enqueued\"`\n+\tDone uint64 `json:\"done\"`\n+\tFailed uint64 `json:\"failed\"`\n+}\n+\n+// upscaleStats: GET /v1/upscale/stats\n+//\n+// Authenticated read-only snapshot of the upscale feature's\n+// runtime + on-disk state. Mirrors the admin /api/upscale/stats\n+// tile but exposed on the public protocol so paired iOS clients\n+// can render an \"Upscaling\" management section without needing\n+// admin auth. The wire shape is documented in docs/BridgeProtocol.md.\n+//\n+// Cheap (single SQL COUNT + a mutex-protected pool snapshot + a\n+// TTL-cached sox precheck — the closure dedupes against the same\n+// admin-side cache by sharing the precheck function reference).\n+// iOS calls every 5 s while the management page is foregrounded.\n+func (s *Server) upscaleStats(w http.ResponseWriter, r *http.Request) {\n+\tvar resp UpscaleStats\n+\tif s.upscaleStatsProvider != nil {\n+\t\tresp = s.upscaleStatsProvider.UpscaleStatsSnapshot()\n+\t}\n+\twriteJSON(w, http.StatusOK, resp)\n+}", "status": "added"}, {"additions": 174, "deletions": 0, "filename": "internal/api/upscale_stats_test.go", "patch": "@@ -0,0 +1,174 @@\n+package api\n+\n+import (\n+\t\"encoding/json\"\n+\t\"io\"\n+\t\"net/http\"\n+\t\"net/http/httptest\"\n+\t\"path/filepath\"\n+\t\"strings\"\n+\t\"testing\"\n+\n+\t\"github.com/acoseac/1-bit-bridge/internal/auth\"\n+\t\"github.com/acoseac/1-bit-bridge/internal/config\"\n+)\n+\n+// stubStatsProvider is a test double for api.UpscaleStatsProvider.\n+// Returns a fixed snapshot so tests can assert the wire shape and\n+// the auth gate without standing up a transcode pool.\n+type stubStatsProvider struct {\n+\tsnap UpscaleStats\n+}\n+\n+func (s *stubStatsProvider) UpscaleStatsSnapshot() UpscaleStats { return s.snap }\n+\n+func upscaleStatsFixture(t *testing.T, withProvider bool, snap UpscaleStats) (string /* baseURL */, string /* token */) {\n+\tt.Helper()\n+\ttmp := t.TempDir()\n+\tcfg := &config.Config{\n+\t\tLibraryRoots: []string{filepath.Join(tmp, \"lib\")},\n+\t\tListenAddress: \":7788\",\n+\t\tLibraryName: \"Test\",\n+\t}\n+\tstore, _ := auth.OpenStore(filepath.Join(tmp, \"tokens.json\"))\n+\traw, _, _ := store.Mint(\"test\")\n+\n+\tsrv := New(cfg, store, nil, \"fp\")\n+\tif withProvider {\n+\t\tsrv = srv.WithUpscaleStats(&stubStatsProvider{snap: snap})\n+\t}\n+\ths := httptest.NewServer(srv.Handler())\n+\tt.Cleanup(hs.Close)\n+\treturn hs.URL, raw\n+}\n+\n+// TestUpscaleStatsRequiresAuth — endpoint is bearer-token gated\n+// (same rule as POST /v1/upscale and every other /v1/* except\n+// /v1/health and the pairing routes).\n+func TestUpscaleStatsRequiresAuth(t *testing.T) {\n+\turl, _ := upscaleStatsFixture(t, true, UpscaleStats{Enabled: true})\n+\tresp, err := http.Get(url + \"/v1/upscale/stats\")\n+\tif err != nil {\n+\t\tt.Fatalf(\"GET: %v\", err)\n+\t}\n+\tdefer resp.Body.Close()\n+\tif resp.StatusCode != http.StatusUnauthorized {\n+\t\tt.Errorf(\"status: got %d, want 401\", resp.StatusCode)\n+\t}\n+}\n+\n+// TestUpscaleStatsNoProviderReturnsZero — when WithUpscaleStats\n+// wasn't wired (test harness, or build without upscale support)\n+// the handler returns the zero-value UpscaleStats. iOS treats this\n+// as \"feature off\" without distinguishing a missing endpoint from\n+// a disabled feature.\n+func TestUpscaleStatsNoProviderReturnsZero(t *testing.T) {\n+\turl, tok := upscaleStatsFixture(t, false, UpscaleStats{})\n+\tgot := getUpscaleStats(t, url, tok)\n+\tif got.Enabled {\n+\t\tt.Errorf(\"Enabled: got true, want false (no provider wired)\")\n+\t}\n+\tif got.Pool != nil {\n+\t\tt.Errorf(\"Pool: got %+v, want nil\", got.Pool)\n+\t}\n+\tif got.SoxAvailable != nil {\n+\t\tt.Errorf(\"SoxAvailable: got %+v, want nil\", got.SoxAvailable)\n+\t}\n+\tif got.CachedVariants != 0 || got.CachedBytes != 0 {\n+\t\tt.Errorf(\"cached counters: got (%d, %d), want (0, 0)\", got.CachedVariants, got.CachedBytes)\n+\t}\n+}\n+\n+// TestUpscaleStatsHappyPathWireShape — golden-shape test for the\n+// fully-populated payload iOS decodes against. The JSON field\n+// names are the contract — renaming any of them is a wire-breaking\n+// change even though they live behind an authed endpoint.\n+func TestUpscaleStatsHappyPathWireShape(t *testing.T) {\n+\ttru := true\n+\twant := UpscaleStats{\n+\t\tEnabled: true,\n+\t\tSoxAvailable: &tru,\n+\t\tPool: &UpscalePoolStats{\n+\t\t\tWorkers: 4,\n+\t\t\tQueueCap: 5000,\n+\t\t\tQueueLen: 12,\n+\t\t\tInflight: 4,\n+\t\t\tEnqueued: 142,\n+\t\t\tDone: 126,\n+\t\t\tFailed: 0,\n+\t\t},\n+\t\tCachedVariants: 138,\n+\t\tCachedBytes: 4823917568,\n+\t}\n+\turl, tok := upscaleStatsFixture(t, true, want)\n+\tgot := getUpscaleStats(t, url, tok)\n+\tif got.Enabled != want.Enabled {\n+\t\tt.Errorf(\"Enabled: got %v, want %v\", got.Enabled, want.Enabled)\n+\t}\n+\tif got.SoxAvailable == nil || *got.SoxAvailable != true {\n+\t\tt.Errorf(\"SoxAvailable: got %v, want true\", got.SoxAvailable)\n+\t}\n+\tif got.Pool == nil {\n+\t\tt.Fatalf(\"Pool: got nil, want non-nil\")\n+\t}\n+\tif *got.Pool != *want.Pool {\n+\t\tt.Errorf(\"Pool: got %+v, want %+v\", *got.Pool, *want.Pool)\n+\t}\n+\tif got.CachedVariants != want.CachedVariants || got.CachedBytes != want.CachedBytes {\n+\t\tt.Errorf(\"cached: got (%d, %d), want (%d, %d)\",\n+\t\t\tgot.CachedVariants, got.CachedBytes, want.CachedVariants, want.CachedBytes)\n+\t}\n+}\n+\n+// TestUpscaleStatsDisabledPoolOmitted — when the snapshot reports\n+// disabled, the `pool` and `soxAvailable` fields are documented as\n+// `omitempty`. Verify the wire JSON actually drops the keys (not\n+// just emits null) so the iOS decoder's lenient default path\n+// stays correct.\n+func TestUpscaleStatsDisabledPoolOmitted(t *testing.T) {\n+\turl, tok := upscaleStatsFixture(t, true, UpscaleStats{Enabled: false, CachedVariants: 5, CachedBytes: 1024})\n+\treq, _ := http.NewRequest(\"GET\", url+\"/v1/upscale/stats\", nil)\n+\treq.Header.Set(\"Authorization\", \"Bearer \"+tok)\n+\tresp, err := http.DefaultClient.Do(req)\n+\tif err != nil {\n+\t\tt.Fatalf(\"GET: %v\", err)\n+\t}\n+\tdefer resp.Body.Close()\n+\tbody, _ := io.ReadAll(resp.Body)\n+\tbs := string(body)\n+\tif strings.Contains(bs, `\"pool\"`) {\n+\t\tt.Errorf(\"pool field should be omitted when nil; got body: %s\", bs)\n+\t}\n+\tif strings.Contains(bs, `\"soxAvailable\"`) {\n+\t\tt.Errorf(\"soxAvailable field should be omitted when nil; got body: %s\", bs)\n+\t}\n+\t// The numeric fields are NOT omitempty (they always appear) —\n+\t// document that contract by asserting they're present even\n+\t// when zero would otherwise be omitted. writeJSON pretty-\n+\t// prints with `: ` separators, so match the field name and\n+\t// the value via `Contains` on each side rather than asserting\n+\t// the literal `\"cachedVariants\":5` form.\n+\tif !strings.Contains(bs, `\"cachedVariants\"`) || !strings.Contains(bs, `5`) {\n+\t\tt.Errorf(\"cachedVariants must always be present; got body: %s\", bs)\n+\t}\n+}\n+\n+func getUpscaleStats(t *testing.T, baseURL, token string) UpscaleStats {\n+\tt.Helper()\n+\treq, _ := http.NewRequest(\"GET\", baseURL+\"/v1/upscale/stats\", nil)\n+\treq.Header.Set(\"Authorization\", \"Bearer \"+token)\n+\tresp, err := http.DefaultClient.Do(req)\n+\tif err != nil {\n+\t\tt.Fatalf(\"GET: %v\", err)\n+\t}\n+\tdefer resp.Body.Close()\n+\tif resp.StatusCode != http.StatusOK {\n+\t\tbody, _ := io.ReadAll(resp.Body)\n+\t\tt.Fatalf(\"status: got %d, want 200 (body: %s)\", resp.StatusCode, string(body))\n+\t}\n+\tvar got UpscaleStats\n+\tif err := json.NewDecoder(resp.Body).Decode(&got); err != nil {\n+\t\tt.Fatalf(\"decode: %v\", err)\n+\t}\n+\treturn got\n+}", "status": "added"}], "message": "feat(api): public GET /v1/upscale/stats — paired-client view of pool + cache\n\nMirrors the admin /api/upscale/stats tile field-for-field, but\nexposes it on the public protocol so paired iOS clients can render\nan \"Upscaling\" management section without admin auth.\n\nWire shape additive — no protocol version bump. Pre-v1.2 bridges\nreturn 404, which iOS treats identically to {enabled: false}: clean\n\"feature off\" state without distinguishing missing-endpoint from\ndisabled-feature.\n\n* `enabled` matches /v1/health.upscaleEnabled (live runtime, not the\n persisted cfg flag — handles startup-demoted / mid-flight-PATCHed\n states the same way the admin handler does).\n* `pool` is omitempty when feature is off (no zero-padded clutter).\n* `cachedVariants`/`cachedBytes` survive across restarts and the\n feature-off→on round trip.\n\ncmd/bridge wiring uses the same pool snapshot the admin closure\nalready consumes, so the operator's Settings tile and the iOS\nclient see the same numbers — no drift between the two surfaces.\n\nAuthenticated (bearer token), same as POST /v1/upscale and every\nother /v1/* except /v1/health and the pairing routes.\n\nMirror-PR partner: iOS-side BridgeUpscaleService consumes this\nendpoint to render server-side queueLen / inflight / failed\ncounters in the per-share management section.\n\nCo-Authored-By: Claude Opus 4.7 (1M context) ", "sha": "af451fd941fccf58a6a0ef123e14527aae538701"}], "post_review_commits": ["868481f2b67224333c6c76c8ec98acccb46debd8"], "pr_author": "acoseac", "pr_title": "feat(api): public GET /v1/upscale/stats endpoint (additive, mirror of admin tile)", "repo_name": "acoseac/1-bit-bridge"}, "repo": "acoseac/1-bit-bridge", "snapshot": "snapshots/8c7a4fb5c81010d80d2ffc6dd4450f269f4179f5528d257323c8f451b236ad35.pack", "split": "rl", "task_id": "313183e03f22f6e74e5d2d2024bc68f9e2eb3a29b3a2594dc158c88483f3fc33"} {"base_sha": "eca1a723801a8dbd9b21108612b27e00a3a38b6b", "cohort": null, "context": {"canonical_pr_url": "https://github.com/jainal09/envdrift/pull/405", "id": "325df678731696f1fb19ba9bfee96c4bc9081c73a7d028aacb3c3119ecc16323", "preparation_mode": "source-only", "snapshot": {"base_ref": "eca1a723801a8dbd9b21108612b27e00a3a38b6b", "base_sha": "eca1a723801a8dbd9b21108612b27e00a3a38b6b", "body": "", "head_ref": "dc95289ecb7a1a9fa7948505a47342522504674f", "head_sha": "dc95289ecb7a1a9fa7948505a47342522504674f", "name": "envdrift", "number": 405, "owner": "jainal09", "pr_url": "https://github.com/jainal09/envdrift/pull/405", "title": ""}}, "head_sha": "dc95289ecb7a1a9fa7948505a47342522504674f", "metadata": {"group_id": "32a98e7a536ef6cabce4c849f0f1601b7001be3a49d420145636b198f273e181", "snapshot": {"base_sha": "eca1a723801a8dbd9b21108612b27e00a3a38b6b", "external_requirements": [], "head_sha": "dc95289ecb7a1a9fa7948505a47342522504674f", "objects": 396, "objects_sha256": "3b5fa32474fd6ee135978c703b0893b5eeb3387c0b1ff2b80948f6b8eeaa634e", "patch_sha256": "eb58130a77b5b4f1a842e449799d1443ca377ffb5154d0d56be9b0afdb6fa746"}}, "pr_number": 405, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "26da1689f7b4", "description": "A write failure after os.fdopen closed the temporary file caused the exception handler to close the descriptor again. The resulting EBADF masked the original error and prevented cleanup, leaving a temporary file that could contain secret data.", "file_path": "src/envdrift/sync/operations.py"}, {"action_id": "A2", "action_type": "fix", "category": "security", "commit_sha": "26da1689f7b4", "description": "Mode preservation used path.stat(), which followed a destination symlink. An attacker could point that symlink at a permissive file and cause the newly written secret to inherit its mode instead of the requested restrictive permissions.", "file_path": "src/envdrift/sync/operations.py"}, {"action_id": "A3", "action_type": "improvement", "category": "bug", "commit_sha": "26da1689f7b4", "description": "The temporary file was renamed without fsync, so an atomic write could appear complete before its contents were durable on disk.", "file_path": "src/envdrift/sync/operations.py"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "26da1689f7b4", "description": "The predictable-temp-name test checked for the file only after failure cleanup had removed it, so it also passed against the vulnerable implementation and did not guard against writing through a planted symlink.", "file_path": "tests/unit/test_sync_operations.py"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "26da1689f7b4", "description": "The temp-name test assigned directly to os.replace, mutating a shared module function rather than using a test-scoped patch; this made teardown and parallel test execution less safe.", "file_path": "tests/unit/test_sync_operations.py"}], "commits_under_review": [{"author": "jainal09", "date": "2026-06-07T03:48:31Z", "files": [{"additions": 34, "deletions": 6, "filename": "src/envdrift/sync/operations.py", "patch": "@@ -2,10 +2,13 @@\n \n from __future__ import annotations\n \n+import contextlib\n import hashlib\n+import os\n import re\n import secrets\n import shutil\n+import tempfile\n from datetime import datetime\n from pathlib import Path\n \n@@ -118,18 +121,43 @@ def atomic_write(path: Path, content: str, permissions: int = 0o600) -> None:\n \"\"\"\n Write file atomically with proper permissions.\n \n- Uses a temporary file and rename to ensure atomicity.\n+ Creates the temp file in the destination directory with an unguessable name\n+ via ``tempfile.mkstemp`` (``O_EXCL``, owned by us, never following a\n+ pre-existing symlink) and applies permissions to the *fd we created* with\n+ ``os.fchmod`` -- not a path-based ``chmod`` that could be redirected through\n+ a symlinked sibling. The temp file is then atomically renamed onto ``path``.\n+ If the destination already exists, its current mode is preserved instead of\n+ unconditionally forcing ``permissions``.\n \"\"\"\n # Ensure parent directory exists\n path.parent.mkdir(parents=True, exist_ok=True)\n \n- tmp_path = path.with_suffix(\".tmp\")\n+ # Preserve the destination's existing mode if it already exists; otherwise\n+ # use the requested default. Resolve before creating the temp file.\n+ mode = permissions\n+ with contextlib.suppress(FileNotFoundError):\n+ mode = path.stat().st_mode & 0o777\n+\n+ fd, tmp_name = tempfile.mkstemp(\n+ dir=str(path.parent), prefix=f\".{path.name}.\", suffix=\".envdrift-tmp\"\n+ )\n+ tmp_path = Path(tmp_name)\n try:\n- tmp_path.write_text(content)\n- tmp_path.chmod(permissions)\n+ # ``os.fchmod`` applies to the fd we own, never a symlink target. It is\n+ # absent on Windows, where permission bits are largely a no-op anyway.\n+ if hasattr(os, \"fchmod\"):\n+ os.fchmod(fd, mode)\n+ with os.fdopen(fd, \"w\") as tmp_file:\n+ tmp_file.write(content)\n+ # fdopen has consumed the fd; closing it again would error.\n+ fd = -1\n tmp_path.replace(path)\n- except Exception:\n- tmp_path.unlink(missing_ok=True)\n+ except BaseException:\n+ if fd != -1:\n+ os.close(fd)\n+ # Only ever unlink the temp file we created, never the destination.\n+ with contextlib.suppress(FileNotFoundError):\n+ tmp_path.unlink()\n raise\n \n ", "status": "modified"}, {"additions": 92, "deletions": 0, "filename": "tests/unit/test_sync_operations.py", "patch": "@@ -219,6 +219,98 @@ def test_atomic_write_overwrites_existing(self, tmp_path: Path) -> None:\n \n assert file_path.read_text() == \"New content\"\n \n+ @pytest.mark.skipif(os.name == \"nt\", reason=\"symlink/fchmod semantics differ on non-POSIX\")\n+ def test_atomic_write_does_not_follow_predictable_tmp_symlink(self, tmp_path: Path) -> None:\n+ \"\"\"A pre-planted symlink at the predictable temp name is not written through.\n+\n+ The old implementation wrote to ``path.with_suffix('.tmp')`` with\n+ ``write_text``, which follows a symlink and clobbers its target. An\n+ attacker who can create ``.tmp`` (or ``.env.tmp`` for ``.env.keys``)\n+ as a symlink to a file they don't own could redirect the secret write.\n+ \"\"\"\n+ dest = tmp_path / \".env.keys\"\n+\n+ outside = tmp_path / \"outside_target\"\n+ outside.write_text(\"ORIGINAL_OUTSIDE\")\n+\n+ # Plant symlinks at every predictable sibling the old code could pick.\n+ for predictable in (dest.with_suffix(\".tmp\"), Path(str(dest) + \".tmp\")):\n+ if not predictable.exists():\n+ predictable.symlink_to(outside)\n+\n+ atomic_write(dest, \"SECRET_DEST_CONTENT\")\n+\n+ # The real destination got the content; the outside target is untouched.\n+ assert dest.read_text() == \"SECRET_DEST_CONTENT\"\n+ assert outside.read_text() == \"ORIGINAL_OUTSIDE\"\n+ # The destination is a real file, not a symlink to the outside file.\n+ assert not dest.is_symlink()\n+\n+ @pytest.mark.skipif(os.name == \"nt\", reason=\"symlink/fchmod semantics differ on non-POSIX\")\n+ def test_atomic_write_does_not_use_literal_predictable_tmp_name(self, tmp_path: Path) -> None:\n+ \"\"\"The temp file used is not the literal ``path.with_suffix('.tmp')``.\n+\n+ We block ``os.replace`` from completing so the temp file is left behind,\n+ then assert the leftover is an unguessable ``mkstemp`` name rather than\n+ the predictable sibling the vulnerable code used.\n+ \"\"\"\n+ dest = tmp_path / \"secret.txt\"\n+ predictable = dest.with_suffix(\".tmp\")\n+\n+ # Make os.replace fail so the temp file is not consumed/renamed away.\n+ original_replace = os.replace\n+\n+ def boom(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None:\n+ raise OSError(\"blocked replace for test\")\n+\n+ os.replace = boom # type: ignore[assignment]\n+ try:\n+ with pytest.raises(OSError, match=\"blocked replace\"):\n+ atomic_write(dest, \"data\")\n+ finally:\n+ os.replace = original_replace # type: ignore[assignment]\n+\n+ # The vulnerable predictable name must never have been created...\n+ assert not predictable.exists()\n+ # ...and atomic_write cleans up its own (unguessable) temp file on failure.\n+ leftovers = [\n+ p\n+ for p in tmp_path.iterdir()\n+ if p.name.startswith(\".secret.txt.\") and p.name.endswith(\".envdrift-tmp\")\n+ ]\n+ assert leftovers == []\n+\n+ @pytest.mark.skipif(os.name == \"nt\", reason=\"symlink/fchmod semantics differ on non-POSIX\")\n+ def test_atomic_write_chmod_targets_destination_not_symlink(self, tmp_path: Path) -> None:\n+ \"\"\"chmod is applied to the file we create, not a followed symlink target.\"\"\"\n+ dest = tmp_path / \"new_secret.txt\"\n+\n+ outside = tmp_path / \"victim\"\n+ outside.write_text(\"victim content\")\n+ outside.chmod(0o644)\n+\n+ # Plant a symlink at the predictable temp name pointing at the victim.\n+ dest.with_suffix(\".tmp\").symlink_to(outside)\n+\n+ atomic_write(dest, \"secret\", permissions=0o600)\n+\n+ # Destination has the tight mode; the victim's mode is unchanged.\n+ assert dest.stat().st_mode & 0o777 == 0o600\n+ assert outside.stat().st_mode & 0o777 == 0o644\n+ assert outside.read_text() == \"victim content\"\n+\n+ @pytest.mark.skipif(os.name == \"nt\", reason=\"POSIX mode semantics\")\n+ def test_atomic_write_preserves_existing_destination_mode(self, tmp_path: Path) -> None:\n+ \"\"\"Overwriting an existing file preserves its current mode (no force 0o600).\"\"\"\n+ dest = tmp_path / \"existing.txt\"\n+ dest.write_text(\"old\")\n+ dest.chmod(0o640)\n+\n+ atomic_write(dest, \"new\", permissions=0o600)\n+\n+ assert dest.read_text() == \"new\"\n+ assert dest.stat().st_mode & 0o777 == 0o640\n+\n \n class TestRedactValue:\n \"\"\"Tests for redact_value -- the non-reversible secret discriminator.\"\"\"", "status": "modified"}], "message": "fix(sync): harden atomic_write against temp-file symlink attacks\n\natomic_write wrote to a predictable sibling (path.with_suffix(\".tmp\")) via\nwrite_text and applied a path-based chmod. Both follow symlinks, so an attacker\nwho can pre-create that name as a symlink could redirect a secret write to a\nfile they don't own and weaken its mode.\n\nCreate the temp file in the destination directory with tempfile.mkstemp (O_EXCL,\nunguessable name, owned by us), write through os.fdopen on the returned fd, and\napply permissions with os.fchmod on that fd -- never a path that could resolve\nthrough a symlink. Atomically rename onto the destination and only ever unlink\nthe temp file we created on failure. Preserve the destination's existing mode\nwhen it already exists instead of unconditionally forcing 0o600.\n\nRegression tests (POSIX-only) assert: a planted symlink at every predictable\nsibling is not written through (outside target unchanged, real destination gets\nthe content); the temp name is not the literal predictable sibling; chmod lands\non the destination, not a symlink target; and an existing mode is preserved.\n\nCo-Authored-By: Claude Opus 4.8 (1M context) ", "sha": "dc95289ecb7a1a9fa7948505a47342522504674f"}], "post_review_commits": ["26da1689f7b4527e31e920b35d02254f66343913", "ee078cb59af72e1e0a5b925f12e32142603ba72a"], "pr_author": "jainal09", "pr_title": "fix(sync): atomic_write via mkstemp to block predictable-tmp symlink", "repo_name": "jainal09/envdrift"}, "repo": "jainal09/envdrift", "snapshot": "snapshots/32a98e7a536ef6cabce4c849f0f1601b7001be3a49d420145636b198f273e181.pack", "split": "rl", "task_id": "325df678731696f1fb19ba9bfee96c4bc9081c73a7d028aacb3c3119ecc16323"} {"base_sha": "550c911f16367e4745c93a8eafaaa44c6a1e0a92", "cohort": null, "context": {"canonical_pr_url": "https://github.com/weicj/vLLM-2080Ti-Definitive/pull/116", "id": "35947367c542d4c744d4ec4f1aedc15d8586d42130318ad282baca2450a71440", "preparation_mode": "source-only", "snapshot": {"base_ref": "550c911f16367e4745c93a8eafaaa44c6a1e0a92", "base_sha": "550c911f16367e4745c93a8eafaaa44c6a1e0a92", "body": "", "head_ref": "24f4f824913ca49716ebb7b62ead62dc398dd7f7", "head_sha": "24f4f824913ca49716ebb7b62ead62dc398dd7f7", "name": "vLLM-2080Ti-Definitive", "number": 116, "owner": "weicj", "pr_url": "https://github.com/weicj/vLLM-2080Ti-Definitive/pull/116", "title": ""}}, "head_sha": "24f4f824913ca49716ebb7b62ead62dc398dd7f7", "metadata": {"group_id": "7e634951301505e8ae371f28847d381d43c8810872b9d13ae5883d00ad4af8db", "snapshot": {"base_sha": "550c911f16367e4745c93a8eafaaa44c6a1e0a92", "external_requirements": [], "head_sha": "24f4f824913ca49716ebb7b62ead62dc398dd7f7", "objects": 2749, "objects_sha256": "dff4d2a83d90622145f651393f62521d7eff636cb5da093505f036e9db28c6c7", "patch_sha256": "a53905109a0ae02c27465401692fc6654008b2a85856d90b1ef79afbc1b0c0f1"}}, "pr_number": 116, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "184d69dec15e", "description": "When a tool call had no recognizable function name, `_extract_function_name` returned `None`, which could overwrite `current_function_name` and cause streaming `DeltaFunctionCall` chunks to emit `name=None`, breaking clients expecting a string.", "file_path": "vllm/tool_parsers/qwen3xml_tool_parser.py"}], "commits_under_review": [{"author": "lingyuzeng", "date": "2026-08-19T14:49:58Z", "files": [{"additions": 11, "deletions": 11, "filename": "vllm/tool_parsers/qwen3xml_tool_parser.py", "patch": "@@ -290,7 +290,7 @@ def _process_complete_xml_elements(self) -> bool:\n index=self.tool_call_index - 1,\n id=self.current_call_id,\n type=\"function\",\n- function=DeltaFunctionCall(name=None, arguments=\"\"),\n+ function=DeltaFunctionCall(name=self.current_function_name, arguments=\"\"),\n )\n ],\n )\n@@ -684,7 +684,7 @@ def _start_element(self, name: str, attrs: dict[str, str]):\n id=self.current_call_id,\n type=\"function\",\n function=DeltaFunctionCall(\n- name=None, arguments=json_start\n+ name=self.current_function_name, arguments=json_start\n ),\n )\n ]\n@@ -702,7 +702,7 @@ def _start_element(self, name: str, attrs: dict[str, str]):\n id=self.current_call_id,\n type=\"function\",\n function=DeltaFunctionCall(\n- name=None, arguments=json_continue\n+ name=self.current_function_name, arguments=json_continue\n ),\n )\n ]\n@@ -744,7 +744,7 @@ def _char_data(self, data: str):\n index=self.tool_call_index - 1,\n id=self.current_call_id,\n type=\"function\",\n- function=DeltaFunctionCall(name=None, arguments='\"'),\n+ function=DeltaFunctionCall(name=self.current_function_name, arguments='\"'),\n )\n ]\n )\n@@ -779,7 +779,7 @@ def _char_data(self, data: str):\n index=self.tool_call_index - 1,\n id=self.current_call_id,\n type=\"function\",\n- function=DeltaFunctionCall(name=None, arguments=delta_data),\n+ function=DeltaFunctionCall(name=self.current_function_name, arguments=delta_data),\n )\n ]\n )\n@@ -837,7 +837,7 @@ def _end_element(self, name: str):\n id=self.current_call_id,\n type=\"function\",\n function=DeltaFunctionCall(\n- name=None, arguments=output_arguments\n+ name=self.current_function_name, arguments=output_arguments\n ),\n )\n ]\n@@ -872,7 +872,7 @@ def _end_element(self, name: str):\n index=self.tool_call_index - 1,\n id=self.current_call_id,\n type=\"function\",\n- function=DeltaFunctionCall(name=None, arguments='\"\"'),\n+ function=DeltaFunctionCall(name=self.current_function_name, arguments='\"\"'),\n )\n ]\n )\n@@ -885,7 +885,7 @@ def _end_element(self, name: str):\n index=self.tool_call_index - 1,\n id=self.current_call_id,\n type=\"function\",\n- function=DeltaFunctionCall(name=None, arguments='\"'),\n+ function=DeltaFunctionCall(name=self.current_function_name, arguments='\"'),\n )\n ]\n )\n@@ -908,7 +908,7 @@ def _end_element(self, name: str):\n index=self.tool_call_index - 1,\n id=self.current_call_id,\n type=\"function\",\n- function=DeltaFunctionCall(name=None, arguments=\"}\"),\n+ function=DeltaFunctionCall(name=self.current_function_name, arguments=\"}\"),\n )\n ]\n )\n@@ -921,7 +921,7 @@ def _end_element(self, name: str):\n index=self.tool_call_index - 1,\n id=self.current_call_id,\n type=\"function\",\n- function=DeltaFunctionCall(name=None, arguments=\"{}\"),\n+ function=DeltaFunctionCall(name=self.current_function_name, arguments=\"{}\"),\n )\n ]\n )\n@@ -944,7 +944,7 @@ def _end_element(self, name: str):\n index=self.tool_call_index - 1,\n id=self.current_call_id,\n type=\"function\",\n- function=DeltaFunctionCall(name=None, arguments=\"\"),\n+ function=DeltaFunctionCall(name=self.current_function_name, arguments=\"\"),\n )\n ]\n )", "status": "modified"}], "message": "fix(tool_parser): preserve function name in all streaming chunks for qwen3_xml parser\n\nThe qwen3_xml tool parser was emitting name=None in streaming chunks after\nthe first one, causing clients like OpenCode and Codex to fail with\n\"Expected 'function.name' to be a string\" when parsing tool calls.\n\nFix: Use self.current_function_name instead of None in all DeltaFunctionCall\nemissions during streaming, ensuring every chunk contains the function name.\n\nThis matches the behavior expected by OpenAI-compatible clients that parse\nstreaming tool calls.", "sha": "03157bb1a6db578c13f0bd910df858bd342255b1"}, {"author": "lingyuzeng", "date": "2026-08-19T15:17:36Z", "files": [{"additions": 2, "deletions": 2, "filename": "vllm/tool_parsers/qwen3xml_tool_parser.py", "patch": "@@ -59,7 +59,7 @@ def reset_streaming_state(self):\n self.tool_call_index = 0\n self.current_call_id = None\n self.last_completed_call_id = None\n- self.current_function_name = None\n+ self.current_function_name = \"\"\n self.current_function_open = False\n self.parameters = {}\n self.current_param_name = None\n@@ -1128,7 +1128,7 @@ def _reset_xml_parser_after_tool_call(self):\n if self.current_call_id:\n self.last_completed_call_id = self.current_call_id\n self.current_call_id = None\n- self.current_function_name = None\n+ self.current_function_name = \"\"\n self.current_function_open = False\n self.parameters = {}\n self.current_param_name = None", "status": "modified"}], "message": "fix(tool_parser): initialize current_function_name as empty string\n\nChange initial/reset value from None to \"\" to guarantee function.name\nis always a string type in streaming output, even in edge cases where\nthe XML stream might not include a tag before .\n\nThis addresses the cubic AI review concern about potential None emission\nin parameter/char_data/end_element handlers.", "sha": "24f4f824913ca49716ebb7b62ead62dc398dd7f7"}], "post_review_commits": ["184d69dec15ed1443c8159248a78300ed4adb453"], "pr_author": "hotwa", "pr_title": "fix(tool_parser): prevent None function name in streaming tool call chunks", "repo_name": "weicj/vLLM-2080Ti-Definitive"}, "repo": "weicj/vLLM-2080Ti-Definitive", "snapshot": "snapshots/7e634951301505e8ae371f28847d381d43c8810872b9d13ae5883d00ad4af8db.pack", "split": "rl", "task_id": "35947367c542d4c744d4ec4f1aedc15d8586d42130318ad282baca2450a71440"} {"base_sha": "a52ee3767d8456d10828aaf614422788c5ad38c7", "cohort": null, "context": {"canonical_pr_url": "https://github.com/polarsource/polar/pull/14798", "id": "36c21b66d0afa3c315baa13e9b59cc1157a1f9601a4ebd8aad8decd5cf2f2840", "preparation_mode": "source-only", "snapshot": {"base_ref": "a52ee3767d8456d10828aaf614422788c5ad38c7", "base_sha": "a52ee3767d8456d10828aaf614422788c5ad38c7", "body": "", "head_ref": "7ccdf34d878dceb5273886cb02c866442a7044ce", "head_sha": "7ccdf34d878dceb5273886cb02c866442a7044ce", "name": "polar", "number": 14798, "owner": "polarsource", "pr_url": "https://github.com/polarsource/polar/pull/14798", "title": ""}}, "head_sha": "7ccdf34d878dceb5273886cb02c866442a7044ce", "metadata": {"group_id": "1e0604b6ec08d08c4f7f05d130b4450c499132bf5e76ca6ba50c6af051b7c423", "snapshot": {"base_sha": "a52ee3767d8456d10828aaf614422788c5ad38c7", "external_requirements": [], "head_sha": "7ccdf34d878dceb5273886cb02c866442a7044ce", "objects": 6056, "objects_sha256": "bbf6f3b68a8f915a8ca479cbb86c86843324804ffbfc428cc169c7a9df2e0ee2", "patch_sha256": "7eae4b3988d536edc379b4d6b16bd476f795ace849004f7b1dc9b172fc6d8d2b"}}, "pr_number": 14798, "references": {"actions": [{"action_id": "A1", "action_type": "cleanup", "category": "other", "commit_sha": "93bf793da5de", "description": "Stripe account creation and update emitted low-value operation logs.", "file_path": "server/polar/integrations/stripe/service.py"}, {"action_id": "A2", "action_type": "cleanup", "category": "other", "commit_sha": "93bf793da5de", "description": "Stripe customer creation and update emitted low-value operation logs.", "file_path": "server/polar/integrations/stripe/service.py"}], "commits_under_review": [{"author": "simonxabris", "date": "2026-09-24T06:39:08Z", "files": [{"additions": 3, "deletions": 6, "filename": "server/polar/integrations/stripe/service.py", "patch": "@@ -88,7 +88,7 @@ async def retrieve_intent(self, id: str) -> stripe_lib.PaymentIntent:\n async def create_account(\n self, country: str, name: str | None\n ) -> stripe_lib.Account:\n- log.info(\"stripe.account.create\", country=country, name=name)\n+ log.info(\"stripe.account.create\", country=country)\n create_params: AccountCreateParams = {\n \"country\": country,\n \"type\": \"express\",\n@@ -110,7 +110,6 @@ async def update_account(self, id: str, name: str | None) -> None:\n log.info(\n \"stripe.account.update\",\n account_id=id,\n- name=name,\n )\n obj = {}\n if name:\n@@ -433,8 +432,7 @@ async def create_customer(\n ) -> stripe_lib.Customer:\n log.info(\n \"stripe.customer.create\",\n- email=params.get(\"email\"),\n- name=params.get(\"name\"),\n+ provided_fields=list(params),\n )\n return await stripe_lib.Customer.create_async(**params)\n \n@@ -447,8 +445,7 @@ async def update_customer(\n log.info(\n \"stripe.customer.update\",\n customer_id=id,\n- email=params.get(\"email\"),\n- name=params.get(\"name\"),\n+ updated_fields=list(params),\n tax_id_type=tax_id.get(\"type\") if tax_id else None,\n )\n params = {**params, \"expand\": [\"tax_ids\"]}", "status": "modified"}], "message": "Remove emails and names from Stripe customer and account logs", "sha": "7ccdf34d878dceb5273886cb02c866442a7044ce"}], "post_review_commits": ["8b01b0aa34a4c00ecc9d560215ec7ae45de1e76b", "93bf793da5de46b21e6b7631cc3eac80bf0e1bdc"], "pr_author": "simonxabris", "pr_title": "fix: Remove Stripe customer and account operation logs", "repo_name": "polarsource/polar"}, "repo": "polarsource/polar", "snapshot": "snapshots/1e0604b6ec08d08c4f7f05d130b4450c499132bf5e76ca6ba50c6af051b7c423.pack", "split": "rl", "task_id": "36c21b66d0afa3c315baa13e9b59cc1157a1f9601a4ebd8aad8decd5cf2f2840"} {"base_sha": "fbc7b3fcdf541246c48eba58dc4475c2e4e18f4f", "cohort": null, "context": {"canonical_pr_url": "https://github.com/egovernments/Citizen-Complaint-Resolution-System/pull/1328", "id": "3ac9e358574f49cc7932b7522285b1cd844b3c73bdc29cdef279a62c57738ffc", "preparation_mode": "source-only", "snapshot": {"base_ref": "fbc7b3fcdf541246c48eba58dc4475c2e4e18f4f", "base_sha": "fbc7b3fcdf541246c48eba58dc4475c2e4e18f4f", "body": "", "head_ref": "6708ea66b1bf6b625b797be735037522d66ee94d", "head_sha": "6708ea66b1bf6b625b797be735037522d66ee94d", "name": "Citizen-Complaint-Resolution-System", "number": 1328, "owner": "egovernments", "pr_url": "https://github.com/egovernments/Citizen-Complaint-Resolution-System/pull/1328", "title": ""}}, "head_sha": "6708ea66b1bf6b625b797be735037522d66ee94d", "metadata": {"group_id": "8de503316da0d3cbe7d203a7744a262b2b34d01259f1193af5919826e8168482", "snapshot": {"base_sha": "fbc7b3fcdf541246c48eba58dc4475c2e4e18f4f", "external_requirements": [{"commit": "036362024eeb8dcb016777e2892e6419e31ba99f", "path": "local-setup/ansible/nairobi-mdms", "snapshot": "6708ea66b1bf6b625b797be735037522d66ee94d", "type": "submodule"}, {"commit": "036362024eeb8dcb016777e2892e6419e31ba99f", "path": "local-setup/ansible/nairobi-mdms", "snapshot": "fbc7b3fcdf541246c48eba58dc4475c2e4e18f4f", "type": "submodule"}], "head_sha": "6708ea66b1bf6b625b797be735037522d66ee94d", "objects": 7468, "objects_sha256": "3e13792f7be7122aa9119f49b5fb713c4aa18ffb6d920201272f4400a88990db", "patch_sha256": "cd8295a77e5a237533a29d3a7c6e71857ea3ea5e953ddaa8bd711e5afb4c3456"}}, "pr_number": 1328, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "984978f6b030", "description": "Value-taking arguments without a usable value were parsed as boolean true, allowing values such as CFG.tenant or CFG.bannerUrl to become the string 'true' instead of triggering the required-argument Usage error.", "file_path": "docs/migration/ccrs-migrate.cjs"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "984978f6b030", "description": "The JSON report used CFG.tenant after the per-city CMS loop had mutated it, so multi-tenant runs reported only the last tenant rather than the full tenant list.", "file_path": "docs/migration/ccrs-migrate.cjs"}], "commits_under_review": [{"author": "Hari-egov", "date": "2026-07-20T09:27:20Z", "files": [{"additions": 48, "deletions": 12, "filename": "docs/migration/ccrs-migrate.cjs", "patch": "@@ -63,8 +63,11 @@ function parseArgs(argv) {\n const a = argv[i];\n if (!a.startsWith('--')) continue;\n const key = a.slice(2);\n- const flag = ['dry-run', 'cms', 'update-wf', 'gzip', 'no-color', 'help'].includes(key);\n- out[key] = flag ? true : argv[++i];\n+ const flag = ['dry-run', 'cms', 'update-wf', 'gzip', 'no-color', 'help', 'update-masters'].includes(key);\n+ // Never let a value-taking arg swallow a following --flag (a missing\n+ // allowlist entry once made `--update-masters --dry-run` eat the dry-run).\n+ const next = argv[i + 1];\n+ out[key] = flag || next === undefined || String(next).startsWith('--') ? true : argv[++i];\n }\n return out;\n }\n@@ -97,6 +100,11 @@ const CFG = {\n gzip: !!ARGS.gzip || truthy(process.env.GZIP),\n nginxConf: ARGS['nginx-conf'] || process.env.NGINX_CONF || '',\n };\n+// --tenant accepts a comma-separated list (e.g. mz,mz.ige,mz.igsae): the\n+// state-level phases run ONCE against the shared state root; only the\n+// city-scoped cms phase repeats for each additional tenant in the list.\n+CFG.tenants = String(CFG.tenant).split(',').map((s) => s.trim()).filter(Boolean);\n+CFG.tenant = CFG.tenants[0] || '';\n CFG.state = CFG.tenant.includes('.') ? CFG.tenant.split('.')[0] : CFG.tenant;\n // OAUTH_BASIC: legacy scripts disagreed (plaintext vs base64) — accept both.\n CFG.basic = /^[A-Za-z0-9+/]+=*$/.test(CFG.basicRaw) && !CFG.basicRaw.includes(':')\n@@ -107,6 +115,10 @@ if (!CFG.base || !CFG.tenant) {\n console.error('Usage: node ccrs-migrate.cjs --host --tenant [options] (--help for all options)');\n process.exit(2);\n }\n+if (CFG.tenants.some((t) => (t.includes('.') ? t.split('.')[0] : t) !== CFG.state)) {\n+ console.error(`All --tenant entries must share one state root (got: ${CFG.tenants.join(', ')})`);\n+ process.exit(2);\n+}\n \n const REPO = path.join(__dirname, '..', '..');\n const SEED = {\n@@ -624,7 +636,7 @@ async function phasePgrMasters() {\n return record('pgr-masters', failed ? OUTCOME.FAILED : OUTCOME.PARTIAL, detail,\n empty.length ? 'MASTER_EMPTY_AFTER_SEED' : 'ROW_CREATE_FAILED', failures.slice(0, 6).join(' | ') || `Empty after seed: ${empty.join(', ')}`);\n }\n- return record('pgr-masters', created ? OUTCOME.OK : OUTCOME.SKIPPED, detail);\n+ return record('pgr-masters', (created || updated) ? OUTCOME.OK : OUTCOME.SKIPPED, detail);\n }\n \n /* ═══════════════════════════ PHASE: landing ═══════════════════════════ */\n@@ -713,11 +725,20 @@ async function cmsSearchAll(schemaCode, tenantId = CFG.state) {\n }\n const cmsUserInfo = () => ({ id: 1, uuid: 'cms-migration', userName: CFG.user, type: 'EMPLOYEE', tenantId: CFG.state, roles: [{ code: 'SUPERUSER', name: 'Super User', tenantId: CFG.state }] });\n \n+// One summary row per tenant when a tenant LIST was passed.\n+const CMS_PH = () => (CFG.tenants.length > 1 ? `cms@${CFG.tenant}` : 'cms');\n+\n async function phaseCms() {\n- if (!CFG.cms) return record('cms', OUTCOME.SKIPPED, 'opt-in phase — pass --cms to run');\n+ if (!CFG.cms) return record(CMS_PH(), OUTCOME.SKIPPED, 'opt-in phase — pass --cms to run');\n const city = CFG.tenant.includes('.') ? CFG.tenant : null;\n- if (!city) return record('cms', OUTCOME.FAILED, 'CMS workflow needs a city tenant (e.g. mz.igsae), got a state root', 'CMS_TENANT_REQUIRED',\n- 'Re-run with --tenant --phases cms --cms');\n+ if (!city) {\n+ // A state-root entry in a tenant list legitimately has no cms run of its\n+ // own — the city entries that follow carry it. Only a SINGLE state-root\n+ // tenant is an operator error.\n+ if (CFG.tenants.length > 1) return record(CMS_PH(), OUTCOME.SKIPPED, 'state root — cms runs at the city tenants in the list');\n+ return record('cms', OUTCOME.FAILED, 'CMS workflow needs a city tenant (e.g. mz.igsae), got a state root', 'CMS_TENANT_REQUIRED',\n+ 'Re-run with --tenant --phases cms --cms');\n+ }\n const failures = [];\n try {\n // 1: roles — at the STATE root and the CITY tenant. MDMS v1 role lookups\n@@ -769,11 +790,11 @@ async function phaseCms() {\n info('workflow BusinessService already present — in-place diff/patch requires the legacy UPDATE_WF path; differences (if any) are not fatal');\n }\n } catch (e) {\n- return record('cms', OUTCOME.FAILED, `unexpected: ${e.message}`, 'CMS_UNEXPECTED', e.stack ? truncate(e.stack, 300) : null);\n+ return record(CMS_PH(), OUTCOME.FAILED, `unexpected: ${e.message}`, 'CMS_UNEXPECTED', e.stack ? truncate(e.stack, 300) : null);\n }\n- if (CFG.dryRun) return record('cms', OUTCOME.SKIPPED, 'dry-run: plan printed above');\n- if (failures.length) return record('cms', OUTCOME.PARTIAL, `${failures.length} step(s) failed`, 'CMS_STEP_FAILED', failures.slice(0, 6).join(' | '));\n- return record('cms', OUTCOME.OK, 'roles, actions, grants, workflow ensured');\n+ if (CFG.dryRun) return record(CMS_PH(), OUTCOME.SKIPPED, 'dry-run: plan printed above');\n+ if (failures.length) return record(CMS_PH(), OUTCOME.PARTIAL, `${failures.length} step(s) failed`, 'CMS_STEP_FAILED', failures.slice(0, 6).join(' | '));\n+ return record(CMS_PH(), OUTCOME.OK, 'roles, actions, grants, workflow ensured');\n }\n \n /* ═══════════════════════════ PHASE: banner ════════════════════════════ */\n@@ -980,7 +1001,7 @@ async function phaseVerify() {\n (async () => {\n const started = Date.now();\n console.log(C.b(`\\nCCRS unified migration${CFG.dryRun ? ' [DRY-RUN — no writes]' : ''}`));\n- console.log(C.d(`host=${CFG.base} tenant=${CFG.tenant} (state=${CFG.state}) phases=${CFG.phases.join(',')}\\n${'═'.repeat(64)}`));\n+ console.log(C.d(`host=${CFG.base} tenant=${CFG.tenants.join(',')} (state=${CFG.state}) phases=${CFG.phases.join(',')}\\n${'═'.repeat(64)}`));\n \n const PIPELINE = [\n ['auth', async () => {\n@@ -1002,8 +1023,12 @@ async function phaseVerify() {\n \n let n = 0;\n const enabled = PIPELINE.filter(([id]) => CFG.phases.includes(id));\n+ // Tenant list: state-level phases run once (against tenants[0] / the state\n+ // root); only the city-scoped cms phase repeats for the additional tenants.\n+ const extraCmsTenants = CFG.tenants.length > 1 && CFG.phases.includes('cms') ? CFG.tenants.slice(1) : [];\n+ const total = enabled.length + extraCmsTenants.length;\n for (const [id, fn] of enabled) {\n- section(++n, enabled.length, id);\n+ section(++n, total, id);\n if (id !== 'auth' && !RI) { record(id, OUTCOME.SKIPPED, 'skipped: no authentication', 'NO_AUTH'); warn('skipped (auth failed)'); continue; }\n try {\n await fn();\n@@ -1012,6 +1037,17 @@ async function phaseVerify() {\n bad(`unexpected: ${e.message}`);\n }\n }\n+ for (const t of extraCmsTenants) {\n+ CFG.tenant = t;\n+ section(++n, total, `cms (${t})`);\n+ if (!RI) { record(`cms@${t}`, OUTCOME.SKIPPED, 'skipped: no authentication', 'NO_AUTH'); warn('skipped (auth failed)'); continue; }\n+ try {\n+ await phaseCms();\n+ } catch (e) {\n+ record(`cms@${t}`, OUTCOME.FAILED, `unexpected error: ${e.message}`, 'UNEXPECTED', e.stack ? truncate(e.stack, 400) : null);\n+ bad(`unexpected: ${e.message}`);\n+ }\n+ }\n \n /* summary */\n console.log(`\\n${C.b('SUMMARY')}\\n${'═'.repeat(64)}`);", "status": "modified"}, {"additions": 75, "deletions": 0, "filename": "docs/migration/enable-gzip.sh", "patch": "@@ -0,0 +1,75 @@\n+#!/usr/bin/env bash\n+# enable-gzip.sh — guided, single-run gzip enablement for /digit-ui.\n+#\n+# RUN THIS ON THE BOX THAT SERVES THE SITE (the gzip phase edits that\n+# machine's nginx — running it anywhere else edits the wrong machine).\n+#\n+# bash enable-gzip.sh # host defaults to http://127.0.0.1\n+# HOST=http://localhost bash enable-gzip.sh\n+# OAUTH_USER=ADMIN OAUTH_PASS='secret' bash enable-gzip.sh # non-default creds\n+#\n+# Safe by design: shows a dry-run plan and waits for Enter before writing;\n+# the apply step itself takes a timestamped backup and auto-rolls-back if\n+# `nginx -t` rejects the change. Re-running any number of times is safe.\n+\n+HOST=\"${HOST:-http://127.0.0.1}\"\n+RUNNER=\"$(dirname \"$0\")/ccrs-migrate.cjs\"\n+PROBE_URL=\"$HOST/digit-ui/index.js\"\n+\n+say() { printf '\\n\\033[1m%s\\033[0m\\n' \"$*\"; }\n+pause(){ printf '\\n'; read -r -p \">>> $1 — press Enter to continue (Ctrl+C to abort) \"; }\n+\n+say \"═══ CCRS gzip enablement — $(hostname) ═══\"\n+\n+# ── 0. sanity: right machine? right files? ──────────────────────────────\n+if [ ! -f \"$RUNNER\" ]; then\n+ echo \"✖ ccrs-migrate.cjs not found next to this script — run from the repo's docs/migration/ directory.\"\n+ exit 1\n+fi\n+if [ -e /etc/nginx/sites-enabled/localhost ] && [ \"$(hostname)\" != \"${EXPECTED_HOSTNAME:-}\" ]; then\n+ echo \"⚠ This machine has an nginx site named 'localhost' — that usually means a LOCAL dev box.\"\n+ read -r -p \">>> Type YES if you are sure this is the serving box for $HOST: \" ok\n+ [ \"$ok\" = \"YES\" ] || { echo \"aborted.\"; exit 1; }\n+fi\n+\n+# ── 1. baseline ─────────────────────────────────────────────────────────\n+say \"[1/5] Baseline — current state of $PROBE_URL\"\n+enc=$(curl -sI --max-time 15 -H 'Accept-Encoding: gzip' \"$PROBE_URL\" | grep -i '^content-encoding' | tr -d '\\r')\n+size=$(curl -s --max-time 60 -o /dev/null -w '%{size_download}' -H 'Accept-Encoding: gzip' --compressed \"$PROBE_URL\")\n+echo \" content-encoding: ${enc:-'(none)'}\"\n+echo \" transferred: ${size:-?} bytes\"\n+if [ -n \"$enc\" ]; then\n+ echo \"✔ gzip already active — nothing to do. (Re-run after a redeploy if it ever regresses.)\"\n+ exit 0\n+fi\n+echo \"→ gzip is OFF (raw transfer). Proceeding will enable it.\"\n+\n+# ── 2. sudo prime (the runner shells out with sudo for nginx edits) ─────\n+say \"[2/5] Priming sudo (nginx edit + test + reload need it)\"\n+sudo -v || { echo \"✖ sudo required\"; exit 1; }\n+\n+# ── 3. dry-run plan ──────────────────────────────────────────────────────\n+say \"[3/5] Dry-run — plan only, no writes\"\n+node \"$RUNNER\" --host \"$HOST\" --tenant \"${TENANT:-mz}\" --phases auth,gzip --gzip --dry-run --no-color || {\n+ echo \"✖ dry-run failed (see AUTH_FAILED detail above: ENOTFOUND = wrong host; 400 = wrong creds — set OAUTH_USER/OAUTH_PASS; 500 JDBC = env DB down)\"; exit 1; }\n+pause \"Apply the plan above (backup → insert gzip block → nginx -t → reload)\"\n+\n+# ── 4. apply ─────────────────────────────────────────────────────────────\n+say \"[4/5] Applying\"\n+node \"$RUNNER\" --host \"$HOST\" --tenant \"${TENANT:-mz}\" --phases auth,gzip --gzip --no-color || { echo \"✖ apply failed\"; exit 1; }\n+# keep runner backups out of nginx's include glob (they confuse re-runs and get include-loaded)\n+sudo mkdir -p /etc/nginx/ccrs-backups\n+sudo mv /etc/nginx/sites-enabled/*.ccrs-gzip.bak* /etc/nginx/ccrs-backups/ 2>/dev/null || true\n+\n+# ── 5. verify ────────────────────────────────────────────────────────────\n+say \"[5/5] Verify\"\n+enc=$(curl -sI --max-time 15 -H 'Accept-Encoding: gzip' \"$PROBE_URL\" | grep -i '^content-encoding' | tr -d '\\r')\n+cc=$(curl -sI --max-time 15 -H 'Accept-Encoding: gzip' \"$PROBE_URL\" | grep -i '^cache-control' | head -1 | tr -d '\\r')\n+size=$(curl -s --max-time 60 -o /dev/null -w '%{size_download}' -H 'Accept-Encoding: gzip' --compressed \"$PROBE_URL\")\n+echo \" ${enc:-content-encoding: (none)}\"\n+echo \" ${cc:-cache-control: (none)}\"\n+echo \" transferred: ${size:-?} bytes\"\n+case \"$enc\" in\n+ *gzip*) say \"✔ SUCCESS — gzip active (expect ~2.1–2.5MB instead of ~8MB). Backups in /etc/nginx/ccrs-backups/.\" ;;\n+ *) say \"✖ still not compressed — send the [4/5] output to the team; backup untouched in /etc/nginx/ccrs-backups/.\" ; exit 1 ;;\n+esac", "status": "added"}], "message": "feat(migration): tenant-list support, arg-parser hardening, guided gzip script\n\n1. --tenant now accepts a comma-separated list (mz,mz.ige,mz.igsae):\n state-level phases run once against the shared state root; the\n city-scoped cms phase repeats per additional tenant (cms@\n summary rows). A single state-root tenant still errors with\n CMS_TENANT_REQUIRED; mixed state roots are rejected up front.\n2. parseArgs: register update-masters as a boolean flag and never let a\n value-taking arg swallow a following --flag (a missing allowlist\n entry made '--update-masters --dry-run' silently drop the dry-run —\n caught live on mctd). pgr-masters now reports OK (not SKIPPED) when\n rows were updated.\n3. enable-gzip.sh: guided single-run gzip enablement (machine guard,\n baseline probe with already-enabled short-circuit, dry-run plan +\n press-Enter confirmation, apply via the runner's backup/nginx -t/\n rollback path, backup relocation out of nginx's include glob, final\n verify).\n\nVerified live: tenant-list dry-run + real run (cms@mz SKIPPED,\ncms@mz.ige OK), parser shows DRY-RUN banner after --update-masters,\nmixed-root rejection, gzip script guard + short-circuit paths.\n\nCo-Authored-By: Claude Opus 4.8 \n(cherry picked from commit c9dd06aa0cc10c8d066a25325645d71010598b5b)", "sha": "6708ea66b1bf6b625b797be735037522d66ee94d"}], "post_review_commits": ["984978f6b030bcc7ec06c43902f75c81a818760e"], "pr_author": "Hari-egov", "pr_title": "feat(migration): tenant-list runs, arg-parser hardening, guided gzip script", "repo_name": "egovernments/Citizen-Complaint-Resolution-System"}, "repo": "egovernments/Citizen-Complaint-Resolution-System", "snapshot": "snapshots/8de503316da0d3cbe7d203a7744a262b2b34d01259f1193af5919826e8168482.pack", "split": "rl", "task_id": "3ac9e358574f49cc7932b7522285b1cd844b3c73bdc29cdef279a62c57738ffc"} {"base_sha": "b15de15065ea5a4e551cd25421953598650a4c65", "cohort": null, "context": {"canonical_pr_url": "https://github.com/OpenRTMP/librtmp2-server-panel/pull/57", "id": "3beb3a2f22465178d0d1de90b7247ec893cdaefe9bf922be88e707fa58af927b", "preparation_mode": "source-only", "snapshot": {"base_ref": "b15de15065ea5a4e551cd25421953598650a4c65", "base_sha": "b15de15065ea5a4e551cd25421953598650a4c65", "body": "", "head_ref": "d25690ca90825ddd8d7fd5b7bb619bdc85325d7c", "head_sha": "d25690ca90825ddd8d7fd5b7bb619bdc85325d7c", "name": "librtmp2-server-panel", "number": 57, "owner": "OpenRTMP", "pr_url": "https://github.com/OpenRTMP/librtmp2-server-panel/pull/57", "title": ""}}, "head_sha": "d25690ca90825ddd8d7fd5b7bb619bdc85325d7c", "metadata": {"group_id": "28a9887f33ae545ef3b98ce70ad79629d205d32931ef5f3984b73ee571d91805", "snapshot": {"base_sha": "b15de15065ea5a4e551cd25421953598650a4c65", "external_requirements": [], "head_sha": "d25690ca90825ddd8d7fd5b7bb619bdc85325d7c", "objects": 50, "objects_sha256": "19811892a7f8661fa768fdc4207b515d2552b15e0cf936911a8d7bf63221afe8", "patch_sha256": "37333ce8dc50cb9c11d990e1716d9eeb1aa668e41b5623ce3655c98f87ba16ac"}}, "pr_number": 57, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "f0d6683b0ac7", "description": "Stream deletion API failures were shown only through a session flash error and were not logged, leaving operators without a server-side record of failed revocations.", "file_path": "app.py"}, {"action_id": "A2", "action_type": "fix", "category": "performance", "commit_sha": "ffadf852d45a", "description": "Gunicorn used a non-threaded worker, so a long-running stream deletion could block the panel from serving other requests.", "file_path": "Dockerfile"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "e267f0cdce07", "description": "The runtime test read the Dockerfile relative to the process working directory and checked raw text fragments rather than the actual CMD arguments, making it fragile and capable of passing for the wrong command.", "file_path": "tests/test_delete_runtime.py"}], "commits_under_review": [{"author": "cursoragent", "date": "2026-07-15T03:04:31Z", "files": [{"additions": 24, "deletions": 5, "filename": ".cursor/bug-scan-progress.md", "patch": "@@ -1,18 +1,37 @@\n # Bug scan progress\n \n-Last scanned: app.py rate limiter — 2026-07-11\n+Last scanned: app.py — 2026-07-15\n \n ## Module checklist\n \n - [x] `app.py` — Flask routes, auth, session handling, stream CRUD\n-- [x] `lrtmp2_client.py` — librtmp2-server REST API client\n-- [x] `config.py` — startup validation and environment configuration\n-- [x] `templates/` — Jinja2 templates (XSS, CSRF forms)\n-- [x] `static/js/` — frontend JavaScript (DOM injection, fetch logic)\n+- [ ] `lrtmp2_client.py` — librtmp2-server REST API client\n+- [ ] `config.py` — startup validation and environment configuration\n+- [ ] `templates/` — Jinja2 templates (XSS, CSRF forms)\n+- [ ] `static/js/` — frontend JavaScript (DOM injection, fetch logic)\n \n (`templates/`/`static/js/` were actually scanned 2026-07-05/06, see findings\n below — checkboxes just hadn't been ticked.)\n \n+## Findings (2026-07-15 app.py pass)\n+\n+- **Bug (fixed):** `delete_stream()` moved deletes into a daemon background\n+ thread (`c29362a`) and always flashed \"Stream deletion started…\" before\n+ redirecting. `Lrtmp2ApiError` from the thread was only logged — never shown\n+ in the UI. Scenario: operator deletes a compromised stream during incident\n+ response; API is down or the 35s RTMP drain times out; panel shows\n+ \"deletion started\" but the stream (and publish/play keys) remain listed\n+ with no error. Impact: failed revoke appears successful — keys stay valid\n+ when the operator believes they are being removed. Fixed by restoring\n+ synchronous `client.delete_stream()` so failures surface via `flash_error`\n+ (Gunicorn `--timeout 60` still covers the client's 35s drain window).\n+- Reviewed but not a bug: auth/session (`login_required` on all sensitive\n+ routes, `session.clear()` on login, `hmac.compare_digest`, CSRF on POSTs,\n+ security headers incl. `Cache-Control: no-store` on JSON); stream/player ID\n+ and access-key validation; stats rate limits (per-IP + per-stream,\n+ invalid-ID exempt); Redis limiter socket timeouts; `build_urls` /\n+ `rtmps_health` caller chains; no open redirects or unguarded routes.\n+\n ## Findings (2026-07-11 Redis rate-limiter pass)\n \n Reviewed the Redis-backed shared login rate limiter added since the last", "status": "modified"}, {"additions": 4, "deletions": 22, "filename": "app.py", "patch": "@@ -1,7 +1,6 @@\n import hmac\n import re\n import secrets\n-import threading\n from functools import wraps\n from urllib.parse import urlencode\n \n@@ -381,27 +380,10 @@ def delete_stream(stream_id):\n if not _is_valid_stream_id(stream_id):\n session[\"flash_error\"] = \"Invalid stream ID\"\n return redirect(url_for(\"index\"))\n-\n- def _delete_in_background(valid_stream_id):\n- with app.app_context():\n- try:\n- client.delete_stream(valid_stream_id)\n- except Lrtmp2ApiError as exc:\n- app.logger.error(\n- \"Background delete for stream %s failed: %s\",\n- valid_stream_id,\n- exc,\n- )\n-\n- threading.Thread(\n- target=_delete_in_background,\n- args=(stream_id,),\n- daemon=True,\n- ).start()\n- session[\"flash_error\"] = (\n- \"Stream deletion started. Active RTMP sessions may take up to 35 \"\n- \"seconds to drain.\"\n- )\n+ try:\n+ client.delete_stream(stream_id)\n+ except Lrtmp2ApiError as exc:\n+ session[\"flash_error\"] = str(exc)\n return redirect(url_for(\"index\"))\n \n stats_ip_limit = f\"{app.config['STATS_RATE_LIMIT_PER_IP']} per minute\"", "status": "modified"}, {"additions": 10, "deletions": 25, "filename": "tests/test_app.py", "patch": "@@ -637,7 +637,7 @@ def test_stream_created_redirects_when_stream_not_listed(monkeypatch):\n assert b\"not listed yet\" in r2.data\n \n \n-def test_delete_stream_background_failure_is_logged(monkeypatch):\n+def test_delete_stream_surfaces_api_error(monkeypatch):\n with patch(\"app.Lrtmp2Client\") as mock_client_cls:\n from lrtmp2_client import Lrtmp2ApiError\n \n@@ -647,7 +647,6 @@ def test_delete_stream_background_failure_is_logged(monkeypatch):\n mock_client.delete_stream.side_effect = Lrtmp2ApiError(\"delete failed\")\n \n import app as app_module\n- import time\n \n monkeypatch.setattr(app_module.Config, \"SESSION_COOKIE_SECURE\", False)\n application = app_module.create_app()\n@@ -659,19 +658,13 @@ def test_delete_stream_background_failure_is_logged(monkeypatch):\n data={\"username\": \"admin\", \"password\": os.environ[\"PASSWORD\"]},\n )\n \n- with patch.object(application.logger, \"error\") as mock_log:\n- r = client.post(\"/streams/fail/delete\")\n- assert r.status_code == 302\n-\n- deadline = time.time() + 2.0\n- while time.time() < deadline:\n- if mock_log.called:\n- break\n- time.sleep(0.05)\n+ r = client.post(\"/streams/fail/delete\")\n+ assert r.status_code == 302\n \n- mock_log.assert_called_once()\n- assert mock_log.call_args.args[1] == \"fail\"\n- assert \"delete failed\" in str(mock_log.call_args.args[2])\n+ r2 = client.get(\"/\")\n+ assert r2.status_code == 200\n+ assert b\"delete failed\" in r2.data\n+ mock_client.delete_stream.assert_called_once_with(\"fail\")\n \n \n def test_create_stream_shows_keys_without_session_storage(monkeypatch):\n@@ -854,7 +847,7 @@ def test_add_player_forwards_custom_play_key(monkeypatch):\n )\n \n \n-def test_delete_stream_starts_background_delete(monkeypatch):\n+def test_delete_stream_calls_api_before_redirect(monkeypatch):\n with patch(\"app.Lrtmp2Client\") as mock_client_cls:\n mock_client = mock_client_cls.return_value\n mock_client.health.return_value = {\"rtmps_enabled\": False}\n@@ -875,19 +868,11 @@ def test_delete_stream_starts_background_delete(monkeypatch):\n \n r = client.post(\"/streams/gone/delete\")\n assert r.status_code == 302\n+ mock_client.delete_stream.assert_called_once_with(\"gone\")\n \n r2 = client.get(\"/\")\n assert r2.status_code == 200\n- assert b\"deletion started\" in r2.data.lower()\n-\n- import time\n-\n- deadline = time.time() + 2.0\n- while time.time() < deadline:\n- if mock_client.delete_stream.called:\n- break\n- time.sleep(0.05)\n- mock_client.delete_stream.assert_called_once_with(\"gone\")\n+ assert b\"deletion started\" not in r2.data.lower()\n \n \n def test_create_stream_rejects_path_unsafe_stream_id(monkeypatch):", "status": "modified"}], "message": "fix(app): surface stream delete failures to operators\n\nBackground delete (c29362a) always flashed 'deletion started' and only\nlogged API errors from the daemon thread. Restore synchronous\nclient.delete_stream() so Lrtmp2ApiError reaches flash_error — failed\nrevokes during incident response are no longer invisible.\n\nCo-authored-by: Alexander Wagner ", "sha": "d25690ca90825ddd8d7fd5b7bb619bdc85325d7c"}], "post_review_commits": ["f0d6683b0ac71e39fd84103c605ab6dc46e29a5f", "ffadf852d45a04e5a79e51bd4be064750134a691", "297268a7e8aa30340b0e22b3f4d5845cf36f7a29", "e267f0cdce070e3513418e90b9456014220697a2"], "pr_author": "cursor[bot]", "pr_title": "fix(app): surface stream delete failures to operators", "repo_name": "OpenRTMP/librtmp2-server-panel"}, "repo": "OpenRTMP/librtmp2-server-panel", "snapshot": "snapshots/28a9887f33ae545ef3b98ce70ad79629d205d32931ef5f3984b73ee571d91805.pack", "split": "rl", "task_id": "3beb3a2f22465178d0d1de90b7247ec893cdaefe9bf922be88e707fa58af927b"} {"base_sha": "f804d0ffc36798f8a81ceca463d732e699f26ce6", "cohort": null, "context": {"canonical_pr_url": "https://github.com/Arzaroth/TokenGauge/pull/29", "id": "3c13f9127c5a469068dd269e38a8aac0c288e30af585c5694be20e1682d0f9dc", "preparation_mode": "source-only", "snapshot": {"base_ref": "f804d0ffc36798f8a81ceca463d732e699f26ce6", "base_sha": "f804d0ffc36798f8a81ceca463d732e699f26ce6", "body": "", "head_ref": "49def72c8b5da3d67b012e7a5a32adba138eafc5", "head_sha": "49def72c8b5da3d67b012e7a5a32adba138eafc5", "name": "TokenGauge", "number": 29, "owner": "Arzaroth", "pr_url": "https://github.com/Arzaroth/TokenGauge/pull/29", "title": ""}}, "head_sha": "49def72c8b5da3d67b012e7a5a32adba138eafc5", "metadata": {"group_id": "66ea03541c855fdd1f4365b586d380b7745fcd87180312fe9240880f6215c2fd", "snapshot": {"base_sha": "f804d0ffc36798f8a81ceca463d732e699f26ce6", "external_requirements": [], "head_sha": "49def72c8b5da3d67b012e7a5a32adba138eafc5", "objects": 358, "objects_sha256": "e1911b0ad9addcc874d22eb8550cdd889610f4b52010c2028180e6920b675b50", "patch_sha256": "3138ce455401e393c3a525dcf9ca6c3e9e77a9971384dcc47790df3b5a67b8fb"}}, "pr_number": 29, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "e892678969eb", "description": "Switching the tray tooltip to on_hover_ui for monospace text removed the default tooltip width cap, allowing long sync transport errors to stretch the popup excessively.", "file_path": "crates/tokengauge-tray/src/main.rs"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "2ec8760e4f5d", "description": "The refresh sentinel test raced the background fetch: the fetch could remove the sentinel after the acknowledgment but before the assertion, causing intermittent CI failures.", "file_path": "crates/tokengauge-waybar/src/daemon.rs"}], "commits_under_review": [{"author": "Arzaroth", "date": "2026-08-31T19:07:45Z", "files": [{"additions": 11, "deletions": 0, "filename": "CHANGELOG.md", "patch": "@@ -5,6 +5,17 @@ All notable changes to this project will be documented in this file.\n The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\n and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n \n+## [Unreleased]\n+\n+### Fixed\n+\n+- **Panel tooltips line up again on Plasma, GNOME and the Windows tray.** The\n+ sub-tables a tooltip carries - a day's split by model and by device, a model's\n+ split by device - are padded to a monospace grid by the panel spec, but those\n+ three surfaces drew them in their toolkit's proportional font, so the token\n+ and cost columns landed wherever the labels happened to end. All three now\n+ render tooltip text in a monospace face, as the waybar tooltip already did.\n+\n ## [0.28.0] - 2026-08-31\n \n ### Added", "status": "modified"}, {"additions": 13, "deletions": 6, "filename": "crates/tokengauge-tray/src/main.rs", "patch": "@@ -522,6 +522,17 @@ mod win {\n }\n }\n \n+ /// The spec pads its sub-tables with spaces, so a tooltip only lines up in\n+ /// a monospace face; egui's default hover text is proportional.\n+ fn hover_tooltip(response: &egui::Response, tooltip: &str) {\n+ if tooltip.is_empty() {\n+ return;\n+ }\n+ response.clone().on_hover_ui(|ui| {\n+ ui.label(RichText::new(tooltip).monospace());\n+ });\n+ }\n+\n /// Label and value on one line, a full-width bar under it, then the reset\n /// note and the pace badge.\n fn meter_row(ui: &mut egui::Ui, row: &tokengauge_core::PanelRow) {\n@@ -591,9 +602,7 @@ mod win {\n egui::FontId::monospace(12.0),\n color,\n );\n- if !row.tooltip.is_empty() {\n- response.on_hover_text(&row.tooltip);\n- }\n+ hover_tooltip(&response, &row.tooltip);\n }\n \n /// Label and value on one line; a badge and a suffix drop to a caption line\n@@ -633,9 +642,7 @@ mod win {\n // The suffix is the spec's ellipsized copy for surfaces that cannot\n // wrap; the tooltip carries the whole sentence, and the sync detail is\n // the row that actually needs it.\n- if !row.tooltip.is_empty() {\n- line.response.on_hover_text(&row.tooltip);\n- }\n+ hover_tooltip(&line.response, &row.tooltip);\n }\n \n fn card(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) {", "status": "modified"}, {"additions": 3, "deletions": 0, "filename": "gnome/tokengauge@arzaroth.github.io/stylesheet.css", "patch": "@@ -131,6 +131,9 @@\n }\n \n .tokengauge-tooltip {\n+ /* The panel spec pads its sub-tables with spaces: they only line up in a\n+ monospace face. */\n+ font-family: monospace;\n background-color: rgba(0, 0, 0, 0.88);\n border: 1px solid rgba(255, 255, 255, 0.15);\n border-radius: 6px;", "status": "modified"}, {"additions": 42, "deletions": 5, "filename": "plasma/org.tokengauge.plasmoid/contents/ui/FullRep.qml", "patch": "@@ -27,6 +27,39 @@ Item {\n return suffix === \"\" ? String(row.value || \"\") : row.value + \" · \" + suffix\n }\n \n+ // The spec pads a tooltip's sub-tables - a day by model, a day by device -\n+ // with spaces, so they only line up in a monospace face, and the styled\n+ // tooltip wraps at 14 gridUnits, which a padded line already brushes\n+ // against. The attached tooltip carries neither font nor width, hence an\n+ // instance of our own.\n+ component MonoToolTip: PlasmaComponents.ToolTip {\n+ id: tip\n+ readonly property real maxTextWidth: Kirigami.Units.gridUnit * 30\n+ font.family: \"monospace\"\n+ contentItem: Item {\n+ implicitWidth: Math.min(tip.maxTextWidth, tipLabel.contentWidth)\n+ implicitHeight: tipLabel.implicitHeight\n+ PlasmaComponents.Label {\n+ id: tipLabel\n+ text: tip.text\n+ font: tip.font\n+ wrapMode: Text.Wrap\n+ // Device and model names come from a provider API, and rich\n+ // text would collapse the padding this whole component exists\n+ // to keep.\n+ textFormat: Text.PlainText\n+ Kirigami.Theme.colorSet: Kirigami.Theme.Tooltip\n+ Kirigami.Theme.inherit: false\n+ // Only a transport error is long enough to reach this; the\n+ // tables are far short of it and stay on one line each.\n+ onLineLaidOut: (line) => {\n+ if (line.implicitWidth > tip.maxTextWidth)\n+ line.width = tip.maxTextWidth\n+ }\n+ }\n+ }\n+ }\n+\n // Label and value on one line, a full-width bar under it, then the reset\n // note and the pace badge. The limit gauges.\n component Meter: ColumnLayout {\n@@ -120,9 +153,11 @@ Item {\n font.bold: modelData.emphasized === true\n }\n }\n- PlasmaComponents.ToolTip.text: modelData.tooltip || \"\"\n- PlasmaComponents.ToolTip.visible: String(modelData.tooltip || \"\") !== \"\" && barHover.hovered\n- PlasmaComponents.ToolTip.delay: 300\n+ MonoToolTip {\n+ text: modelData.tooltip || \"\"\n+ visible: text !== \"\" && barHover.hovered\n+ delay: 300\n+ }\n HoverHandler { id: barHover }\n }\n \n@@ -182,8 +217,10 @@ Item {\n // The suffix is the spec's ellipsized copy for surfaces that cannot\n // wrap; the tooltip carries the whole sentence.\n HoverHandler { id: keyHover }\n- PlasmaComponents.ToolTip.text: keyRow.modelData.tooltip || \"\"\n- PlasmaComponents.ToolTip.visible: String(keyRow.modelData.tooltip || \"\") !== \"\" && keyHover.hovered\n+ MonoToolTip {\n+ text: keyRow.modelData.tooltip || \"\"\n+ visible: text !== \"\" && keyHover.hovered\n+ }\n }\n \n QQC2.ButtonGroup { id: tabGroup }", "status": "modified"}], "message": "[fix/panel-tooltip-monospace] fix: panel tooltips line up on plasma, gnome and the tray\n\nThe panel spec pads a tooltip's sub-tables - a day by model, a day by\ndevice, a model by device - with spaces, so they only line up in a\nmonospace face. Waybar wraps its tooltip in ; Plasma, GNOME and the\nWindows tray drew the same text in their toolkit's proportional font, so\nthe token and cost columns landed wherever the labels happened to end.\n\nPlasma's attached ToolTip is the shared styled instance and carries no\nfont to set per row, hence MonoToolTip: a monospace, plain-text tooltip\nwhose wrap cap is 30 gridUnits rather than the style's 14, because a\nmonospace line is wider than the proportional one that already brushed\nagainst the old limit. Plain text also keeps a provider-supplied name\nfrom being read as markup and collapsing the padding.\n\nCo-Authored-By: Claude Opus 5 (1M context) \nClaude-Session: https://claude.ai/code/session_01AFGH8i8VPNRFjMzSVPm7Q8", "sha": "49def72c8b5da3d67b012e7a5a32adba138eafc5"}], "post_review_commits": ["e892678969eb93a24632cee08fa6f2588ffc30df", "2ec8760e4f5d6c3c10318b8564cde002e8bbb7b1"], "pr_author": "Arzaroth", "pr_title": "Panel tooltips line up on Plasma, GNOME and the tray", "repo_name": "Arzaroth/TokenGauge"}, "repo": "Arzaroth/TokenGauge", "snapshot": "snapshots/66ea03541c855fdd1f4365b586d380b7745fcd87180312fe9240880f6215c2fd.pack", "split": "rl", "task_id": "3c13f9127c5a469068dd269e38a8aac0c288e30af585c5694be20e1682d0f9dc"} {"base_sha": "f0a989357e4067593dc6bd5ebe615acbc64aee1d", "cohort": null, "context": {"canonical_pr_url": "https://github.com/xifan2333/ftty/pull/113", "id": "3d4992da375eb4db9e1749563efb313d0451aed9c29e727404d96fc5ff7172e2", "preparation_mode": "source-only", "snapshot": {"base_ref": "f0a989357e4067593dc6bd5ebe615acbc64aee1d", "base_sha": "f0a989357e4067593dc6bd5ebe615acbc64aee1d", "body": "", "head_ref": "c0ace41edbeddfd5705fe3b9999d5bd270a5639a", "head_sha": "c0ace41edbeddfd5705fe3b9999d5bd270a5639a", "name": "ftty", "number": 113, "owner": "xifan2333", "pr_url": "https://github.com/xifan2333/ftty/pull/113", "title": ""}}, "head_sha": "c0ace41edbeddfd5705fe3b9999d5bd270a5639a", "metadata": {"group_id": "04f9b39af097d28a54f50315a6085a70d4b548e28a899f1bc4ffe4fc180457a2", "snapshot": {"base_sha": "f0a989357e4067593dc6bd5ebe615acbc64aee1d", "external_requirements": [], "head_sha": "c0ace41edbeddfd5705fe3b9999d5bd270a5639a", "objects": 102, "objects_sha256": "22bfac2b546db7bc78827a1970a59a176935a7300c0f1e054cf79d2d4f31569b", "patch_sha256": "37ed9cd7cf8859cecb43f496c0290a08e60999e969e905b4a6d43c32d35c3bf1"}}, "pr_number": 113, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "other", "commit_sha": "af747b9f1df3", "description": "The PTY registration guard was embedded in the event loop, making its behavior across Wayland lifecycle states difficult to test directly. The existing test checked only the initial unconfigured state, leaving registration after configuration and prevention of duplicate registration unverified.", "file_path": "src/event_loop/tests.rs"}], "commits_under_review": [{"author": "xifan2333", "date": "2026-09-18T10:54:32Z", "files": [], "message": "perf(startup): start gating PTY registration strictly on wayland configure (#112)", "sha": "0e106086d34b27198bd2c8c5557c292b91d972cc"}, {"author": "xifan2333", "date": "2026-09-18T10:57:00Z", "files": [{"additions": 1, "deletions": 14, "filename": "src/event_loop/mod.rs", "patch": "@@ -218,17 +218,6 @@ impl AppState {\n pty_registered: false,\n })\n }\n-\n- /// Pre-warms EGL display, OpenGL context, and shader compilation immediately\n- /// following window surface creation so the first configure only needs a sub-millisecond resize.\n- pub fn prewarm_renderer(&mut self, connection: &Connection) {\n- if let Some(surface) = &self.wayland.surface {\n- let size = [self.wayland.width, self.wayland.height];\n- if let Ok(renderer) = Renderer::new(surface, connection, size) {\n- self.renderer = Some(renderer);\n- }\n- }\n- }\n }\n \n // ---------------------------------------------------------------------------\n@@ -253,8 +242,6 @@ pub fn run_event_loop(mut app_state: AppState) -> Result<(), FttyError> {\n conn.flush()\n .map_err(|e| WaylandError::Dispatch(e.to_string()))?;\n \n- app_state.prewarm_renderer(&conn);\n-\n run_event_loop_with_connection(app_state, conn, event_queue)\n }\n \n@@ -337,7 +324,7 @@ pub fn run_event_loop_with_connection(\n \n // Register PTY read source exactly once after initial configure establishes\n // final tiling dimensions and creates the renderer, preventing busy-looping and SIGWINCH restarts.\n- if !app_state.pty_registered && app_state.renderer.is_some() {\n+ if !app_state.pty_registered && app_state.wayland.configured {\n app_state.pty_registered = true;\n let pty_master = app_state.pty.try_clone_master()?;\n let pty_source = Generic::new(pty_master, Interest::READ, Mode::Level);", "status": "modified"}, {"additions": 5, "deletions": 10, "filename": "src/event_loop/tests.rs", "patch": "@@ -577,19 +577,14 @@ fn test_pre_event_loop_window_creation_and_surface_setup() {\n }\n \n #[test]\n-fn test_prewarm_renderer_noop_without_surface() {\n- let (client, server) = std::os::unix::net::UnixStream::pair().expect(\"socketpair\");\n- let conn = wayland_client::Connection::from_socket(client).expect(\"conn\");\n+fn test_pty_registration_guarded_by_wayland_configured() {\n let term = Terminal::new(80, 24, 100);\n let pty = Pty::spawn(Some(&[\"/bin/sh\"]), 80, 24).expect(\"PTY spawn\");\n- let mut app = AppState::new(term, pty).expect(\"app\");\n+ let app = AppState::new(term, pty).expect(\"app\");\n \n- // Before surface creation, prewarm must be a deterministic no-op\n- assert!(app.wayland.surface.is_none());\n- assert!(app.renderer.is_none());\n- app.prewarm_renderer(&conn);\n- assert!(app.renderer.is_none());\n- drop(server);\n+ // Unconfigured state must never register PTY reading\n+ assert!(!app.wayland.configured);\n+ assert!(!app.pty_registered);\n }\n \n #[test]", "status": "modified"}, {"additions": 0, "deletions": 4, "filename": "src/main.rs", "patch": "@@ -138,10 +138,6 @@ fn main() {\n std::process::exit(1);\n }\n \n- // Step 4: Pre-warm EGL display, OpenGL context, and shader compilation immediately\n- // after window surface creation so the first configure only needs a sub-millisecond resize.\n- app_state.prewarm_renderer(&conn);\n-\n if let Err(e) = run_event_loop_with_connection(app_state, conn, event_queue) {\n eprintln!(\"ftty error: {e}\");\n std::process::exit(1);", "status": "modified"}], "message": "perf(startup): gate PTY reading strictly on wayland configure and remove DRI prewarm (#112)", "sha": "c0ace41edbeddfd5705fe3b9999d5bd270a5639a"}], "post_review_commits": ["af747b9f1df3620061341aae5844dcf4ddc08718"], "pr_author": "xifan2333", "pr_title": "perf(startup): gate PTY registration on wayland configure and remove blocking DRI prewarm (#112)", "repo_name": "xifan2333/ftty"}, "repo": "xifan2333/ftty", "snapshot": "snapshots/04f9b39af097d28a54f50315a6085a70d4b548e28a899f1bc4ffe4fc180457a2.pack", "split": "rl", "task_id": "3d4992da375eb4db9e1749563efb313d0451aed9c29e727404d96fc5ff7172e2"} {"base_sha": "36c4e9cf5c0123e33d65f2af9497ee090404b532", "cohort": null, "context": {"canonical_pr_url": "https://github.com/pingdotgg/t3code/pull/9479", "id": "40f98c927bfcdd5f4b8140506c9ac43d47112100741f275ad00d5d93839bd4a9", "preparation_mode": "source-only", "snapshot": {"base_ref": "36c4e9cf5c0123e33d65f2af9497ee090404b532", "base_sha": "36c4e9cf5c0123e33d65f2af9497ee090404b532", "body": "", "head_ref": "f121bc4782e5eeac9a054b4ff649a9fcf24c9e77", "head_sha": "f121bc4782e5eeac9a054b4ff649a9fcf24c9e77", "name": "t3code", "number": 9479, "owner": "pingdotgg", "pr_url": "https://github.com/pingdotgg/t3code/pull/9479", "title": ""}}, "head_sha": "f121bc4782e5eeac9a054b4ff649a9fcf24c9e77", "metadata": {"group_id": "54d3067f235797652f288436173de0fbecae4354b891c34c1cc2252e70a3b7fa", "snapshot": {"base_sha": "36c4e9cf5c0123e33d65f2af9497ee090404b532", "external_requirements": [{"commit": "c9f5e549cf023632c3df948c207a58336192b3c7", "path": ".repos/alchemy-effect/.vendor/alchemy", "snapshot": "36c4e9cf5c0123e33d65f2af9497ee090404b532", "type": "submodule"}, {"commit": "c9f5e549cf023632c3df948c207a58336192b3c7", "path": ".repos/alchemy-effect/.vendor/alchemy", "snapshot": "f121bc4782e5eeac9a054b4ff649a9fcf24c9e77", "type": "submodule"}], "head_sha": "f121bc4782e5eeac9a054b4ff649a9fcf24c9e77", "objects": 17826, "objects_sha256": "df47ced3f9ccb98d5dffcc7b1cab0291504af08c6eeac101ba2d2621549ee3db", "patch_sha256": "0645e678727c24e1824b1535e4c2af5e70dce254c7f45ccecad84678ed3b2090"}}, "pr_number": 9479, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "eb4f6e840963", "description": "The PR reviewer and label pickers used a popover and command list instead of the shared combobox, leaving their search and selection behavior inconsistent with the project and branch pickers.", "file_path": "apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "12fc9a91702a", "description": "After selecting a reviewer or label, ignoring the combobox's item-press close request kept the popup open but still let it freeze the query and return focus to the trigger, so the next keystroke did not reach the search box.", "file_path": "apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx"}], "commits_under_review": [{"author": "juliusmarminge", "date": "2026-09-03T20:41:18Z", "files": [{"additions": 54, "deletions": 46, "filename": "apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx", "patch": "@@ -2,12 +2,15 @@\n * The menu shell the reviewer and label pickers share: an icon trigger, a search box, and a\n * scrolling body that says when the list is loading, could not be read, is empty, or is not all\n * of it. The rows and the words are the caller's; the frame is the same either way.\n+ *\n+ * Built on a popover and the command list rather than a menu: a menu's typeahead claims every\n+ * keypress to jump between rows, which is exactly what a search box cannot share.\n */\n import type { ReactNode } from \"react\";\n \n import { Button } from \"../ui/button\";\n-import { Input } from \"../ui/input\";\n-import { Menu, MenuItem, MenuPopup, MenuTrigger } from \"../ui/menu\";\n+import { Command, CommandInput, CommandItem, CommandList } from \"../ui/command\";\n+import { Popover, PopoverPopup, PopoverTrigger } from \"../ui/popover\";\n import { Tooltip, TooltipPopup, TooltipTrigger } from \"../ui/tooltip\";\n import { PullRequestPeopleGhost } from \"./PullRequestGhosts\";\n \n@@ -79,58 +82,63 @@ export function PullRequestCandidatePicker({\n }\n \n return (\n- \n- \n+ \n {icon}\n \n }\n />\n- \n-
\n- onQueryChange(event.currentTarget.value)}\n+ \n+ {/* The caller narrows the list, so the command does no filtering of its own. */}\n+ \n+ \n-
\n-
\n- {isPending ? (\n- \n- ) : error !== null ? (\n-

\n- {errorLabel} {error}\n-

\n- ) : candidates.length === 0 ? (\n-

\n- {query.length > 0 ? noMatchLabel : emptyLabel}\n-

\n- ) : (\n- candidates.map((candidate) => (\n- // Stays open on press: a change is confirmed by the row's own check turning over,\n- // and a second label or reviewer is usually wanted right after the first.\n- onSelect(candidate)}\n- className=\"min-h-0 py-1.5 text-xs sm:min-h-0 sm:text-xs\"\n- >\n- {children(candidate)}\n- \n- ))\n- )}\n- {truncated ? (\n- // Typing filters what arrived; it does not ask the host again, so this says what the\n- // list is rather than offering a search that would find nothing further.\n-

{truncatedLabel}

\n- ) : null}\n-
\n-
\n-
\n+ \n+ {isPending ? (\n+ \n+ ) : error !== null ? (\n+

\n+ {errorLabel} {error}\n+

\n+ ) : candidates.length === 0 ? (\n+

\n+ {query.length > 0 ? noMatchLabel : emptyLabel}\n+

\n+ ) : (\n+ candidates.map((candidate) => (\n+ // Stays open on press: a change is confirmed by the row's own check turning over,\n+ // and a second label or reviewer is usually wanted right after the first.\n+ onSelect(candidate)}\n+ className=\"min-h-0 cursor-pointer gap-2 py-1.5 text-xs sm:min-h-0 sm:text-xs\"\n+ >\n+ {children(candidate)}\n+ \n+ ))\n+ )}\n+ {truncated ? (\n+ // Typing filters what arrived; it does not ask the host again, so this says what the\n+ // list is rather than offering a search that would find nothing further.\n+

{truncatedLabel}

\n+ ) : null}\n+
\n+ \n+ \n+ \n );\n }", "status": "modified"}], "message": "fix(web): let the PR reviewer and label search boxes take keystrokes\n\nThe reviewer and label pickers on the PR summary were built on a Menu, whose typeahead claims every printable key to jump between rows. Typing into the search box highlighted the matching row instead of filtering.\n\nRebuild the shared picker shell on a Popover with the command list, so the input owns typing and arrow keys and Enter still walk and pick rows.\n\nCo-Authored-By: Claude Code ", "sha": "f121bc4782e5eeac9a054b4ff649a9fcf24c9e77"}], "post_review_commits": ["eb4f6e8409638bf0e9d8514fec857ddc5ddd9c79", "12fc9a91702a37468277378a9c15708494ac8aca"], "pr_author": "juliusmarminge", "pr_title": "fix(web): let the PR reviewer and label search boxes take keystrokes", "repo_name": "pingdotgg/t3code"}, "repo": "pingdotgg/t3code", "snapshot": "snapshots/54d3067f235797652f288436173de0fbecae4354b891c34c1cc2252e70a3b7fa.pack", "split": "rl", "task_id": "40f98c927bfcdd5f4b8140506c9ac43d47112100741f275ad00d5d93839bd4a9"} {"base_sha": "6c594a989438cff594a39671e4ee91481af6f863", "cohort": null, "context": {"canonical_pr_url": "https://github.com/testingbot/TestingBot-Jenkins-Plugin/pull/40", "id": "40fa11ff28465f93c69fa695a3599472d74c60b3faabb140d9d6e8caac2ae7a2", "preparation_mode": "source-only", "snapshot": {"base_ref": "6c594a989438cff594a39671e4ee91481af6f863", "base_sha": "6c594a989438cff594a39671e4ee91481af6f863", "body": "", "head_ref": "a6f8dc4e209032903bf2ae4ad742d3cbf6b0424f", "head_sha": "a6f8dc4e209032903bf2ae4ad742d3cbf6b0424f", "name": "TestingBot-Jenkins-Plugin", "number": 40, "owner": "testingbot", "pr_url": "https://github.com/testingbot/TestingBot-Jenkins-Plugin/pull/40", "title": ""}}, "head_sha": "a6f8dc4e209032903bf2ae4ad742d3cbf6b0424f", "metadata": {"group_id": "0ca908dddead5076a15bffa4d40fb38e6e0b637f0c54d3112bc2cfd16a12ee77", "snapshot": {"base_sha": "6c594a989438cff594a39671e4ee91481af6f863", "external_requirements": [], "head_sha": "a6f8dc4e209032903bf2ae4ad742d3cbf6b0424f", "objects": 103, "objects_sha256": "f7464d54c83c8caf1751d15ccff86136434e7359fa8707ad5a58f68e816b5ce7", "patch_sha256": "df431568445ba373a2d35f602c0f45644d4c4cc003894cb92e1e6b4173e68919"}}, "pr_number": 40, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "refactor", "commit_sha": "f9e5f942b0e3", "description": "Test Connection result handling was embedded in the network- and permission-dependent verification method, leaving its null-user and optional identity/plan branches without isolated regression coverage. The result logic was extracted without changing behavior and covered by unit tests.", "file_path": "src/main/java/testingbot/TestingBotCredentials.java"}], "commits_under_review": [{"author": "jochen-testingbot", "date": "2026-07-17T14:13:12Z", "files": [{"additions": 13, "deletions": 33, "filename": "src/main/java/testingbot/TestingBotCredentials.java", "patch": "@@ -7,7 +7,6 @@\n import org.kohsuke.stapler.export.Exported;\n import org.kohsuke.stapler.verb.POST;\n \n-import com.cloudbees.plugins.credentials.BaseCredentials;\n import com.cloudbees.plugins.credentials.Credentials;\n import com.cloudbees.plugins.credentials.CredentialsDescriptor;\n import com.cloudbees.plugins.credentials.CredentialsMatcher;\n@@ -28,7 +27,6 @@\n import com.testingbot.testingbotrest.TestingbotREST;\n import com.testingbot.testingbotrest.TestingbotUnauthorizedException;\n import edu.umd.cs.findbugs.annotations.CheckForNull;\n-import edu.umd.cs.findbugs.annotations.NonNull;\n import hudson.Extension;\n import hudson.Util;\n import hudson.model.AbstractItem;\n@@ -56,19 +54,15 @@\n import java.util.logging.Logger;\n \n @NameWith(value = TestingBotCredentials.NameProvider.class)\n-public class TestingBotCredentials extends BaseCredentials implements StandardCredentials {\n+public class TestingBotCredentials extends BaseStandardCredentials {\n private static final String CREDENTIAL_DISPLAY_NAME = \"TestingBot\";\n \n- private final String id;\n- private final String description;\n private final String key;\n private final Secret secret;\n \n @DataBoundConstructor\n public TestingBotCredentials(String id, String description, String key, String secret) {\n- super(CredentialsScope.GLOBAL);\n- this.id = IdCredentials.Helpers.fixEmptyId(id);\n- this.description = Util.fixNull(description);\n+ super(CredentialsScope.GLOBAL, IdCredentials.Helpers.fixEmptyId(id), Util.fixNull(description));\n this.key = Util.fixNull(key);\n this.secret = Secret.fromString(secret);\n }\n@@ -86,28 +80,6 @@ public String getDecryptedSecret() {\n return secret.getPlainText();\n }\n \n- @NonNull\n- @Exported\n- public String getDescription() {\n- return description;\n- }\n-\n- @NonNull\n- @Exported\n- public String getId() {\n- return id;\n- }\n-\n- @Override\n- public final boolean equals(Object o) {\n- return IdCredentials.Helpers.equals(this, o);\n- }\n-\n- @Override\n- public final int hashCode() {\n- return IdCredentials.Helpers.hashCode(this);\n- }\n-\n private static List getLegacyCredentials() {\n DataInputStream in = null;\n BufferedReader br = null;\n@@ -330,12 +302,20 @@ public FormValidation doVerifyCredentials(@QueryParameter String key, @QueryPara\n String plainSecret = Secret.fromString(secret).getPlainText();\n try (TestingbotREST rest = new TestingbotREST(key.trim(), plainSecret)) {\n TestingbotUser user = rest.getUserInfo();\n- if (user == null || Util.fixEmptyAndTrim(user.getEmail()) == null) {\n+ if (user == null) {\n return FormValidation.error(\"Could not verify these credentials with TestingBot.\");\n }\n+ // A valid TestingBot account may not expose an email (e.g. sub-accounts); the\n+ // authenticated user object itself is proof the key/secret work. Prefer the email,\n+ // fall back to the account's first name, so verification never fails on a null email.\n+ String who = Util.fixEmptyAndTrim(user.getEmail());\n+ if (who == null) {\n+ who = Util.fixEmptyAndTrim(user.getFirstName());\n+ }\n String plan = Util.fixEmptyAndTrim(user.getPlan());\n- return FormValidation.ok(\"Connection successful — signed in as %s%s\",\n- user.getEmail(), plan != null ? \" (\" + plan + \" plan)\" : \"\");\n+ return FormValidation.ok(\"Connection successful%s%s\",\n+ who != null ? \" — signed in as \" + who : \"\",\n+ plan != null ? \" (\" + plan + \" plan)\" : \"\");\n } catch (TestingbotUnauthorizedException | TestingbotApiException e) {\n // The REST client's typed failures: bad key/secret, and network/parse errors (it wraps\n // IOException into TestingbotApiException). Unexpected runtime exceptions propagate.", "status": "modified"}], "message": "Fix TestingBot credential resolution and Test Connection\n\nTwo correctness fixes surfaced by an end-to-end run against a real account.\n\n1. Credentials never resolved at build time.\n TestingBotCredentials extended BaseCredentials (implements StandardCredentials).\n CredentialsProvider.lookupCredentialsInItem(TestingBotCredentials.class, ...) —\n used by the build wrapper's getCredentials(), availableCredentials() and every\n credential dropdown — returned an empty list for it, even though the stored\n objects are instances of the class (a StandardCredentials.class lookup found\n them; a UsernamePasswordCredentialsImpl, which extends BaseStandardCredentials,\n is found by concrete class). As a result the freestyle wrapper silently\n resolved null credentials, so TB_KEY/TB_SECRET/TESTINGBOT_BUILD were never\n injected and the dropdowns were empty.\n\n Make TestingBotCredentials extend BaseStandardCredentials, which owns id and\n description (and the id-based equals/hashCode), so concrete-type lookups work.\n Old-format credentials.xml (scope/id/description/key/secret) still deserializes\n unchanged — field names are identical.\n\n2. Test Connection failed for accounts without an email.\n doVerifyCredentials required a non-null user email; a valid account can return\n 200 with a null email (e.g. sub-accounts), which produced a false 'Could not\n verify these credentials' for working key/secret. Treat any authenticated user\n as success, preferring the email and falling back to the account first name.", "sha": "a6f8dc4e209032903bf2ae4ad742d3cbf6b0424f"}], "post_review_commits": ["f9e5f942b0e332c972e9851c552044104e34d06d"], "pr_author": "jochen-testingbot", "pr_title": "Fix TestingBot credential resolution and Test Connection", "repo_name": "testingbot/TestingBot-Jenkins-Plugin"}, "repo": "testingbot/TestingBot-Jenkins-Plugin", "snapshot": "snapshots/0ca908dddead5076a15bffa4d40fb38e6e0b637f0c54d3112bc2cfd16a12ee77.pack", "split": "rl", "task_id": "40fa11ff28465f93c69fa695a3599472d74c60b3faabb140d9d6e8caac2ae7a2"} {"base_sha": "02d1b25921e292b4d5fa3015712f1b002734e789", "cohort": null, "context": {"canonical_pr_url": "https://github.com/transistir/CadeiaDominial/pull/17", "id": "41e9dc8163f8dfc7bd5ff4fe9f37e44aefe689ede976e7b9e7876364a09292a2", "preparation_mode": "source-only", "snapshot": {"base_ref": "02d1b25921e292b4d5fa3015712f1b002734e789", "base_sha": "02d1b25921e292b4d5fa3015712f1b002734e789", "body": "", "head_ref": "1a64f1d659224a6ec14fdfd4252b5f62bcb60fd7", "head_sha": "1a64f1d659224a6ec14fdfd4252b5f62bcb60fd7", "name": "CadeiaDominial", "number": 17, "owner": "transistir", "pr_url": "https://github.com/transistir/CadeiaDominial/pull/17", "title": ""}}, "head_sha": "1a64f1d659224a6ec14fdfd4252b5f62bcb60fd7", "metadata": {"group_id": "723b02e6a0883dbe14d8b1be07bc9a6407276779706316d7a09c682215bc54ec", "snapshot": {"base_sha": "02d1b25921e292b4d5fa3015712f1b002734e789", "external_requirements": [], "head_sha": "1a64f1d659224a6ec14fdfd4252b5f62bcb60fd7", "objects": 235, "objects_sha256": "e3ec4a758a4df38aed13219c0a78efa721ef64f212881fe6ec2c1f9402c24423", "patch_sha256": "7a3f57b9beb2acc936be6a88bba76de1c37dfe2f1a7308cb3f14e6bbd732ed23"}}, "pr_number": 17, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "documentation", "commit_sha": "11b087d8f922", "description": "The domain README displayed the obsolete `../react-flow.md` path as link text, but the link opened the migration guide instead of the renamed React Flow quick reference. Readers could not navigate to the document the link appeared to promise.", "file_path": "docs/domain/README.md"}], "commits_under_review": [{"author": "hermes-agent", "date": "2026-06-02T01:11:56Z", "files": [{"additions": 1, "deletions": 1, "filename": "README.md", "patch": "@@ -16,7 +16,7 @@\n - 🌳 **Interactive Tree Visualization**: Visual exploration of property chains with zoom/pan\n - 👥 **Multi-User Support**: Role-based access (admin, editor, viewer)\n \n-💡 **[Entendendo a Cadeia Dominial (Guia Didático)](docs/cadeia-dominial/ENTENDENDO_CADEIA_DOMINIAL.md)** — Uma explicação simples sobre como o sistema funciona.\n+💡 **[Entendendo a Cadeia Dominial (Guia Didático)](docs/domain/overview.md)** — Uma explicação simples sobre como o sistema funciona.\n \n This is a **modern TypeScript rewrite** of the original Django application, leveraging Cloudflare's edge platform for global performance and scalability.\n ", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "docs/MIGRATION_CHECKLIST.md", "patch": "@@ -2,6 +2,8 @@\n \n Checklist for migrating CadeiaDominial from Django to **React + Vite + Hono** on Cloudflare.\n \n+> **Looking for the technical deep-dive?** See [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) — architecture decisions, directory structure, tech stack details, and CI/CD. This checklist is the **execution companion** (what to do, in what order).\n+\n ---\n \n ## Phase 1: Preparation & Planning", "status": "modified"}, {"additions": 3, "deletions": 1, "filename": "docs/MIGRATION_GUIDE.md", "patch": "@@ -2,6 +2,8 @@\n \n This guide outlines our migration from a Django monolith to a modern full-stack TypeScript architecture using **React + Vite** (frontend), **Hono** (backend API), and **Drizzle** (ORM) on the Cloudflare platform.\n \n+> **Looking for the execution plan?** See [`MIGRATION_CHECKLIST.md`](./MIGRATION_CHECKLIST.md) — phase-by-phase to-do list. This guide is the **technical companion** (why and how).\n+\n ---\n \n ## Migration Context\n@@ -64,7 +66,7 @@ The current **Cadeia Dominial** system is a Django 5.2.3 application:\n - ✅ Built-in zoom/pan and easy node/edge customization\n - ✅ Supports rapid iteration before adding advanced layouts\n \n-> **Reference**: [ADR-007 in ARCHITECTURE_DECISIONS.md](./ARCHITECTURE_DECISIONS.md) and [React Flow Quick Reference](./react-flow.md)\n+> **Reference**: [ADR-007 in ARCHITECTURE_DECISIONS.md](./ARCHITECTURE_DECISIONS.md) and [React Flow Quick Reference](./domain/react-flow-quick-reference.md)\n \n **How to use (baseline)**:\n ", "status": "modified"}, {"additions": 33, "deletions": 0, "filename": "docs/README.md", "patch": "@@ -0,0 +1,33 @@\n+# CadeiaDominial — Documentation Index\n+\n+This directory holds the project's primary documentation. Start here for navigation.\n+\n+## 🗂 Structure\n+\n+| Directory / file | Purpose |\n+|---|---|\n+| [`domain/`](./domain/) | Domain model — what a land-registry chain **is** (lançamentos, fim de cadeia, tree shape, D3 visualization) |\n+| [`db/`](./db/) | Database schema (v2 — the **current** target) |\n+| [`prd/`](./prd/) | Product Requirements Documents for the TypeScript monorepo bootstrap |\n+| [`legacy-django/`](./legacy-django/) | Reference docs for the historical Django/Postgres implementation (now frozen in `old/`) |\n+| [`ARCHITECTURE_DECISIONS.md`](./ARCHITECTURE_DECISIONS.md) | ADRs (Architecture Decision Records) for the v2 stack |\n+| [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) | Full technical guide for the Django → TypeScript migration |\n+| [`MIGRATION_CHECKLIST.md`](./MIGRATION_CHECKLIST.md) | Phase-by-phase execution checklist (companion to MIGRATION_GUIDE) |\n+| [`DEPLOYMENT.md`](./DEPLOYMENT.md) | Cloudflare Workers + D1 deployment notes |\n+| [`DEVELOPMENT_FLOW.mermaid`](./DEVELOPMENT_FLOW.mermaid) | High-level development flow diagram |\n+| [`D1_IMPORT.md`](./D1_IMPORT.md) | Importing legacy data into Cloudflare D1 |\n+| [`D1_LOCAL_DEV.md`](./D1_LOCAL_DEV.md) | Running D1 locally for development |\n+| [`CODEX_COMMANDS.md`](./CODEX_COMMANDS.md) | Codex CLI command reference |\n+\n+## 🚦 Where to start\n+\n+- **New to the project?** → [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) → [`ARCHITECTURE_DECISIONS.md`](./ARCHITECTURE_DECISIONS.md) → [`domain/overview.md`](./domain/overview.md)\n+- **Working on the schema?** → [`db/README.md`](./db/README.md) (read this first — it points to the **gate decisions** in `SCHEMA_DECISOES_PENDENTES.md`)\n+- **Implementing a feature in the v2 monorepo?** → [`prd/`](./prd/) for the relevant PRD\n+- **Cross-referencing legacy behavior?** → [`legacy-django/`](./legacy-django/)\n+\n+## 🔗 Related\n+\n+- `../TASKS.md` — Roadmap & task list (T-000 through T-403+)\n+- `../BOOTSTRAP_PROGRESS.md` — Monorepo bootstrap status\n+- `../README.md` — Top-level project README", "status": "added"}, {"additions": 19, "deletions": 14, "filename": "docs/db/README.md", "patch": "@@ -1,19 +1,24 @@\n-# docs/db - Fonte de verdade\n+# Database — Schema v2 (current)\n \n-Este diretorio contem apenas os documentos **oficiais** do schema final.\n+Documents the **current target** schema for the CadeiaDominial system (Drizzle ORM on Cloudflare D1 / SQLite).\n \n-## Fonte de verdade\n-- `SCHEMA_CONSOLIDATED.md`\n-- `SCHEMA_CONSOLIDATED_ERD.mmd`\n-- `SCHEMA_CONSOLIDATED_ERD_LEGEND.md`\n-- `SCHEMA_CONSTRAINTS.md`\n+## 🚦 STOP — read before doing schema work\n \n-## Registro de decisoes\n-- `SCHEMA_RESPOSTAS.md`\n+> **Phase 0 (BLOCKING):** Six open decisions in [`SCHEMA_DECISOES_PENDENTES.md`](./SCHEMA_DECISOES_PENDENTES.md) must be answered by Luandro before any new schema code lands. See task **T-001** in `../../TASKS.md`.\n \n-## Questoes (historico)\n-- `SCHEMA_QUESTOES.md` (resolvido; manter como historico)\n+## Files\n \n-## Referencias legadas\n-Todo material anterior, analises e propostas historicas foi movido para `docs/db/legacy/`.\n-Use apenas como contexto; o schema final esta consolidado em `SCHEMA_CONSOLIDATED.md`.\n+| File | Purpose |\n+|---|---|\n+| [`SCHEMA_CONSOLIDATED.md`](./SCHEMA_CONSOLIDATED.md) | Consolidated v2 schema (canonical reference) |\n+| [`erd-v2.mmd`](./erd-v2.mmd) | Mermaid ERD of the v2 model |\n+| [`erd-v2-legend.md`](./erd-v2-legend.md) | Legend / column notes for the ERD |\n+| [`SCHEMA_CONSTRAINTS.md`](./SCHEMA_CONSTRAINTS.md) | Cross-table constraints (uniqueness, FK invariants) |\n+| [`SCHEMA_QUESTOES.md`](./SCHEMA_QUESTOES.md) | Open audit questions (Q1–Q25) about the v2 schema |\n+| [`SCHEMA_RESPOSTAS.md`](./SCHEMA_RESPOSTAS.md) | Answers to Q1–Q25 |\n+| [`legacy/`](./legacy/) | Per-table analyses of the **previous** Django schema (PascalCase tables) |\n+\n+## Cross-reference\n+\n+- The blindspot review of this schema is in `../../SCHEMA_V2_BLINDSPOT_REVIEW.md` (PR #15).\n+- The legacy Django model is documented in [`../legacy-django/03-database-models.md`](../legacy-django/03-database-models.md).", "status": "modified"}, {"additions": 0, "deletions": 0, "filename": "docs/db/erd-v2-legend.md", "patch": "", "status": "renamed"}, {"additions": 0, "deletions": 0, "filename": "docs/db/erd-v2.mmd", "patch": "", "status": "renamed"}, {"additions": 18, "deletions": 0, "filename": "docs/domain/README.md", "patch": "@@ -0,0 +1,18 @@\n+# Domain — Cadeia Dominial\n+\n+Documents describing **what a land-registry chain is** in this system. Independent of any specific technology stack; the same concepts apply to the legacy Django implementation and the v2 TypeScript rewrite.\n+\n+## Reading order\n+\n+1. [`overview.md`](./overview.md) — Quick orientation (37L, 2-minute read)\n+2. [`lancamento-tipos.md`](./lancamento-tipos.md) — All types of \"lançamentos\" (registrations) on a property\n+3. [`tree-model.md`](./tree-model.md) — How properties form trees via transmissões\n+4. [`fim-de-cadeia.md`](./fim-de-cadeia.md) — End-of-chain semantics\n+5. [`visualization-d3.md`](./visualization-d3.md) — Full D3 chain visualization flow\n+6. [`visualization-d3-reference.md`](./visualization-d3-reference.md) — D3 technical reference\n+7. [`visualization-d3-analysis.md`](./visualization-d3-analysis.md) — D3 documentation-vs-code analysis\n+8. [`react-flow-quick-reference.md`](./react-flow-quick-reference.md) — React Flow quick reference for the v2 UI\n+\n+## Migration note\n+\n+The D3 documents describe the **legacy Django** visualization. The v2 frontend uses **React Flow** instead — see [`../react-flow.md`](../MIGRATION_GUIDE.md) in the migration guide and [`ARCHITECTURE_DECISIONS.md`](../ARCHITECTURE_DECISIONS.md) for the rationale.", "status": "added"}, {"additions": 0, "deletions": 0, "filename": "docs/domain/fim-de-cadeia.md", "patch": "", "status": "renamed"}, {"additions": 1, "deletions": 1, "filename": "docs/domain/lancamento-tipos.md", "patch": "@@ -449,7 +449,7 @@ Quando a cadeia chega ao fim, o sistema **deve pedir** para marcar uma das opç\n - Se ficar ilegível, não tem problema, mas essa informação sobre a origem (lídima, sem origem ou inconclusa) será o principal\n - Em algum lugar, precisa aparecer uma **lista de imóveis com essa condição**\n \n-> **📋 Documentação Complementar:** Para informações detalhadas sobre fim de cadeia, tipos, classificações e implementação, consulte o documento: [`FIM_DE_CADEIA.md`](./FIM_DE_CADEIA.md).\n+> **📋 Documentação Complementar:** Para informações detalhadas sobre fim de cadeia, tipos, classificações e implementação, consulte o documento: [`fim-de-cadeia.md`](./fim-de-cadeia.md).\n \n ### Exemplos de Uso\n ", "status": "renamed"}, {"additions": 0, "deletions": 0, "filename": "docs/domain/overview.md", "patch": "", "status": "renamed"}, {"additions": 0, "deletions": 0, "filename": "docs/domain/react-flow-quick-reference.md", "patch": "", "status": "renamed"}, {"additions": 1, "deletions": 1, "filename": "docs/domain/tree-model.md", "patch": "@@ -249,7 +249,7 @@ Regra prática:\n - **Sem origem**: documento não \"puxa\" pais novos para a árvore.\n - **Com origem**: cada código `M123`/`T456` citado em `lancamento.origem` vira um documento pai (já existente ou criado automaticamente, dependendo do caso) e aparece conectado ao documento atual.\n \n-> **📋 Documentação Complementar:** Para informações detalhadas sobre todos os tipos de lançamento (Averbação, Registro, Início de Matrícula), seus campos obrigatórios, particularidades e regras de preenchimento, consulte o documento auxiliar: [`TIPOS_LANCAMENTO.md`](./TIPOS_LANCAMENTO.md).\n+> **📋 Documentação Complementar:** Para informações detalhadas sobre todos os tipos de lançamento (Averbação, Registro, Início de Matrícula), seus campos obrigatórios, particularidades e regras de preenchimento, consulte o documento auxiliar: [`lancamento-tipos.md`](./lancamento-tipos.md).\n \n **Como as origens são interpretadas no backend**\n ", "status": "renamed"}, {"additions": 0, "deletions": 0, "filename": "docs/domain/visualization-d3-analysis.md", "patch": "", "status": "renamed"}, {"additions": 0, "deletions": 0, "filename": "docs/domain/visualization-d3-reference.md", "patch": "", "status": "renamed"}, {"additions": 0, "deletions": 0, "filename": "docs/domain/visualization-d3.md", "patch": "", "status": "renamed"}, {"additions": 34, "deletions": 0, "filename": "docs/prd/README.md", "patch": "@@ -0,0 +1,34 @@\n+# Product Requirements Documents\n+\n+PRDs for the TypeScript monorepo bootstrap. Each PRD is a JSON file consumed by the Codex PRD workflow (see `.codex/`).\n+\n+## Index\n+\n+| PRD | Title | Status |\n+|---|---|---|\n+| PRD-000 | Alignment & preflight | bootstrap |\n+| PRD-001 | Monorepo scaffolding (pnpm workspaces + Turborepo) | bootstrap |\n+| PRD-002 | Shared package (types, utils) | bootstrap |\n+| PRD-003 | API service (Hono) | bootstrap |\n+| PRD-004 | D1 + Drizzle ORM integration | bootstrap |\n+| PRD-005 | Authentication (Auth.js / Clerk) | bootstrap |\n+| PRD-006 | Web app (Vite + React) | bootstrap |\n+| PRD-007 | TanStack Query client setup | bootstrap |\n+| PRD-008 | React Flow chain visualization | bootstrap |\n+| PRD-009 | Tooling (ESLint, Prettier, TypeScript strict) | bootstrap |\n+| PRD-010 | Testing (Vitest + Playwright, 80% coverage) | bootstrap |\n+| PRD-011 | Deployment (Cloudflare Workers + D1) | bootstrap |\n+| PRD-012 | Local dev environment | bootstrap |\n+| PRD-013 | ADR implementation | bootstrap |\n+| PRD-014 | PDF export of chain reports | bootstrap |\n+| PRD-015 | File storage (R2) | bootstrap |\n+\n+## How to use\n+\n+- Codex: `plan-prd ` → `implement-prd ` → `review-implementation `\n+- See `../../.codex/` for skill definitions.\n+- See `../../BOOTSTRAP_PROGRESS.md` for execution status.\n+\n+## Renaming policy\n+\n+The PRD filename (`PRD-NNN-slug.json`) is the stable identifier referenced by `.codex/` skills and the bootstrap progress tracker. **Do not rename these files** without updating the references in `.codex/` and `BOOTSTRAP_PROGRESS.md`.", "status": "added"}], "message": "docs(structure): reorganize docs/ for navigation and clarity\n\n- Rename docs/cadeia-dominial/ -> docs/domain/ (cleaner, English)\n- Rename 7 domain docs to kebab-case (overview, lancamento-tipos, etc.)\n- Move docs/react-flow.md -> docs/domain/react-flow-quick-reference.md\n- Rename docs/db/SCHEMA_CONSOLIDATED_ERD.{mmd,_LEGEND.md} -> erd-v2.{mmd,-legend.md}\n- Add docs/README.md (root index with reading paths)\n- Add docs/domain/README.md (domain docs index)\n- Add docs/db/README.md (with link to T-001 gate decisions)\n- Add docs/prd/README.md (PRD index with 15 entries)\n- Cross-link MIGRATION_GUIDE.md <-> MIGRATION_CHECKLIST.md\n- Fix 3 broken cross-references in tree-model.md, lancamento-tipos.md, MIGRATION_GUIDE.md\n- Fix broken link to Entendendo a Cadeia in top-level README.md\n\nProposed as T-403 (Phase 4: Cleanup, alongside T-401/T-402).\nBase: v2. No source code or schemas touched.", "sha": "1a64f1d659224a6ec14fdfd4252b5f62bcb60fd7"}], "post_review_commits": ["11b087d8f922016ec5eb8f8647e5cd7db0b55bf7"], "pr_author": "hiurequeiroz", "pr_title": "docs(structure): reorganize docs/ for navigation and clarity", "repo_name": "transistir/CadeiaDominial"}, "repo": "transistir/CadeiaDominial", "snapshot": "snapshots/723b02e6a0883dbe14d8b1be07bc9a6407276779706316d7a09c682215bc54ec.pack", "split": "rl", "task_id": "41e9dc8163f8dfc7bd5ff4fe9f37e44aefe689ede976e7b9e7876364a09292a2"} {"base_sha": "c32ed703cb7857d4b2bd438f6ea4cb4415cfcbef", "cohort": null, "context": {"canonical_pr_url": "https://github.com/acoseac/1-bit-bridge/pull/111", "id": "426ade36be371c54adb749a291b260c069156f510293e920f781746b868a1ff2", "preparation_mode": "source-only", "snapshot": {"base_ref": "c32ed703cb7857d4b2bd438f6ea4cb4415cfcbef", "base_sha": "c32ed703cb7857d4b2bd438f6ea4cb4415cfcbef", "body": "", "head_ref": "af451fd941fccf58a6a0ef123e14527aae538701", "head_sha": "af451fd941fccf58a6a0ef123e14527aae538701", "name": "1-bit-bridge", "number": 111, "owner": "acoseac", "pr_url": "https://github.com/acoseac/1-bit-bridge/pull/111", "title": ""}}, "head_sha": "af451fd941fccf58a6a0ef123e14527aae538701", "metadata": {"group_id": "8c7a4fb5c81010d80d2ffc6dd4450f269f4179f5528d257323c8f451b236ad35", "snapshot": {"base_sha": "c32ed703cb7857d4b2bd438f6ea4cb4415cfcbef", "external_requirements": [], "head_sha": "af451fd941fccf58a6a0ef123e14527aae538701", "objects": 242, "objects_sha256": "f6c5758351cbfbebe4afe447bac2d4ce19648a5a601abcd5364bd967e8415fb2", "patch_sha256": "d1a676fe11abab7f1bc4292d86c787c210bef684eb3e95886db21b755ac80149"}}, "pr_number": 111, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "performance", "commit_sha": "868481f2b672", "description": "The stats endpoint ran `transcode.PrecheckSox()` on every request, spawning `sox --version` on each five-second poll instead of caching the result.", "file_path": "cmd/bridge/main.go"}, {"action_id": "A2", "action_type": "improvement", "category": "bug", "commit_sha": "868481f2b672", "description": "The disabled-pool test could pass with an incorrect `cachedVariants` value because it only searched for the digit `5` anywhere in the response; it also did not verify the exact `cachedBytes` value.", "file_path": "internal/api/upscale_stats_test.go"}, {"action_id": "A3", "action_type": "fix", "category": "documentation", "commit_sha": "868481f2b672", "description": "The protocol documentation's fenced JSON response block lacked the blank-line separation required by Markdown rule MD031.", "file_path": "PROTOCOL.md"}, {"action_id": "A4", "action_type": "improvement", "category": "documentation", "commit_sha": "868481f2b672", "description": "The adapter documentation did not disclose that its unsynchronized read of `cfg.Upscale.Enabled` races with admin PATCH writes; the race itself remains unfixed.", "file_path": "cmd/bridge/main.go"}], "commits_under_review": [{"author": "ars", "date": "2026-05-01T07:41:23Z", "files": [{"additions": 38, "deletions": 1, "filename": "PROTOCOL.md", "patch": "@@ -283,7 +283,44 @@ Distinct from `upscale_disabled`. The pool's queue cap is operator-tunable via `\n \n **Idempotency**: the worker pool dedups jobs on `(source_path, variant_id)`. A duplicate request while a job is queued or running is a silent no-op (still counted in `enqueued`); the iOS app can mash \"Generate\" without server-side duplicate work.\n \n-**Asynchronous completion**: the response returns as soon as the jobs are queued. iOS discovers completed variants via the next `/v1/manifest` sync (which advertises the new `Track.variants` entries). There is no per-job status endpoint in v1.2; the manifest IS the authoritative completion signal.\n+**Asynchronous completion**: the response returns as soon as the jobs are queued. iOS discovers completed variants via the next `/v1/manifest` sync (which advertises the new `Track.variants` entries). For pool-level visibility while jobs are in flight (queue depth, lifetime totals, failure counts) iOS calls the companion `GET /v1/upscale/stats` endpoint described below; for per-track completion the manifest is still the authoritative signal.\n+\n+### `GET /v1/upscale/stats` (additive, since v1.2)\n+\n+Snapshot of the upscale feature's runtime + on-disk state. Designed for the iOS app's per-share \"Upscaling\" management section to show the operator how many jobs are queued, in flight, finished, or failed without surfacing the admin console externally. The wire shape is intentionally identical to the admin tile's `/api/upscale/stats` payload — same numbers in both places.\n+\n+**Authentication**: standard `Authorization: Bearer ` (same rule as every other `/v1/*` endpoint except `/v1/health` and the pairing routes).\n+\n+**Response** (`200 OK`, JSON):\n+```json\n+{\n+ \"enabled\": true,\n+ \"soxAvailable\": true,\n+ \"pool\": {\n+ \"workers\": 4,\n+ \"queueCap\": 5000,\n+ \"queueLen\": 12,\n+ \"inflight\": 4,\n+ \"enqueued\": 142,\n+ \"done\": 126,\n+ \"failed\": 0\n+ },\n+ \"cachedVariants\": 138,\n+ \"cachedBytes\": 4823917568\n+}\n+```\n+\n+| Field | Meaning |\n+|---|---|\n+| `enabled` | Live runtime state. False when `cfg.Upscale.Enabled` is false OR the sox-precheck demoted the feature at startup OR the operator just PATCHed the feature off (the long-lived Pool may still be alive, but the contract is \"feature is off live\", matching `/v1/health.upscaleEnabled`). |\n+| `soxAvailable` | The current `sox(1)`-on-PATH probe result. Omitted when the test harness didn't wire a precheck closure. Operators can install sox without restarting the bridge — within ~30 s the field flips to `true`. |\n+| `pool` | Live worker-pool snapshot. **Omitted when `enabled` is false** (no pool to query). `queueCap` is operator-tunable via `cfg.Upscale.QueueCap` (default 5000). `enqueued`/`done`/`failed` are lifetime counters since the bridge process started — they reset on restart; `cachedVariants` survives. |\n+| `cachedVariants` | Row count from `track_variants`. Survives across restarts and reflects historical conversion work — non-zero even when `enabled == false` if the operator disabled the feature without `--gc`. |\n+| `cachedBytes` | Total size of all sidecar files, summed from `track_variants.size_bytes`. Helps the operator gauge disk usage before deciding to re-enable or `--gc`. |\n+\n+**Empty / disabled bridge**: returns the zero-value response `{\"enabled\": false, \"cachedVariants\": 0, \"cachedBytes\": 0}`. iOS treats this identically to a 404 from a pre-v1.2 bridge — render \"feature off\" without distinguishing a missing endpoint from a disabled feature.\n+\n+**Polling cadence**: iOS polls every 5 s **only while the management page is foregrounded** (never in background). The handler is cheap enough — single SQL `COUNT` + a mutex-protected pool snapshot + a `sox` precheck — to absorb that cadence on Pi-class hosts.\n \n ### `GET /v1/artwork/{mbid}?size=` and `GET /v1/artist-image/{mbid}`\n ", "status": "modified"}, {"additions": 96, "deletions": 0, "filename": "cmd/bridge/main.go", "patch": "@@ -44,6 +44,13 @@ import (\n \t\"github.com/acoseac/1-bit-bridge/internal/version\"\n )\n \n+// Package-scoped logger for the cmd/bridge wiring layer. Most\n+// startup output is `fmt.Fprintf(stdout/stderr)` because it's user-\n+// facing; this is for backend-style telemetry from helpers like\n+// upscaleStatsAdapter that fire on every request and shouldn't spam\n+// the operator's terminal but should be visible via `bridge logs`.\n+var logger = logging.Component(\"bridge\")\n+\n // variantStoreAdapter implements api.VariantStore on top of a\n // manifest.Provider. Just translates between the two packages'\n // equivalent record shapes — the api package can't import the\n@@ -170,6 +177,65 @@ func (a *upscaleEnqueuerAdapter) EnqueueOne(libraryRelativePath string) error {\n \t}\n }\n \n+// upscaleStatsAdapter implements api.UpscaleStatsProvider. Mirrors\n+// the admin /api/upscale/stats handler's data sources field-for-\n+// field so the operator's Settings tile and a paired iOS client see\n+// the same numbers.\n+//\n+// Two pool-related closures (rather than a captured `*transcode.Pool`):\n+// the pool reference itself can be nil (operator never enabled the\n+// feature) AND the operator can flip `cfg.Upscale.Enabled = false`\n+// mid-flight without restart, leaving a live but logically-disabled\n+// Pool. The closures evaluate both conditions at snapshot time so\n+// `enabled` and the `pool` payload move together — same gating the\n+// admin `UpscaleStats` closure already uses.\n+type upscaleStatsAdapter struct {\n+\tpool func() *transcode.Pool\n+\tenabled func() bool\n+\tstore *manifest.Store\n+}\n+\n+func (a *upscaleStatsAdapter) UpscaleStatsSnapshot() api.UpscaleStats {\n+\tvar snap api.UpscaleStats\n+\tif a.enabled() {\n+\t\tif p := a.pool(); p != nil {\n+\t\t\ts := p.Stats()\n+\t\t\tsnap.Pool = &api.UpscalePoolStats{\n+\t\t\t\tWorkers: s.Workers,\n+\t\t\t\tQueueCap: s.QueueCap,\n+\t\t\t\tQueueLen: s.QueueLen,\n+\t\t\t\tInflight: s.Inflight,\n+\t\t\t\tEnqueued: s.Enqueued,\n+\t\t\t\tDone: s.Done,\n+\t\t\t\tFailed: s.Failed,\n+\t\t\t}\n+\t\t}\n+\t}\n+\tsnap.Enabled = (snap.Pool != nil)\n+\tif err := transcode.PrecheckSox(); err == nil {\n+\t\tt := true\n+\t\tsnap.SoxAvailable = &t\n+\t} else {\n+\t\tf := false\n+\t\tsnap.SoxAvailable = &f\n+\t}\n+\tif a.store != nil {\n+\t\tcount, bytes, err := a.store.CountVariants()\n+\t\tif err != nil {\n+\t\t\t// Same degrade-and-log policy the admin tile uses\n+\t\t\t// (PR #110): a SQL failure here shouldn't blank the\n+\t\t\t// whole response. Live counters still go out; the\n+\t\t\t// caller sees `cachedVariants: 0, cachedBytes: 0` and\n+\t\t\t// the operator can find the failure in logs.\n+\t\t\tlogger.Warn(\"upscale stats: count variants\", \"err\", err)\n+\t\t} else {\n+\t\t\tsnap.CachedVariants = count\n+\t\t\tsnap.CachedBytes = bytes\n+\t\t}\n+\t}\n+\treturn snap\n+}\n+\n // updateInfoAdapter bridges *updater.Updater to api.UpdaterStatus +\n // admin's read-side without coupling those packages to the updater\n // type. Trivial; lives here at the wiring point so the api / admin\n@@ -864,6 +930,36 @@ func runServe(ctx context.Context, opts serveOpts, stdout, stderr io.Writer) int\n \t\t\toutputDir: filepath.Join(cfg.DataDir, \"transcoded\"),\n \t\t})\n \t}\n+\n+\t// /v1/upscale/stats wiring. Always registered so paired iOS\n+\t// clients can render a clean \"feature off\" state on bridges where\n+\t// the operator hasn't enabled upscaling — same nil-safe contract\n+\t// the admin tile uses. The closure mirrors the admin\n+\t// /api/upscale/stats handler exactly so the operator's Settings\n+\t// page and the iOS management section show the same numbers.\n+\t//\n+\t// Three sources combined:\n+\t// 1. Live pool counters — only when upscalePool != nil AND\n+\t// cfg.Upscale.Enabled (operator can disable mid-flight via a\n+\t// PATCH; the long-lived Pool stays alive until restart, but\n+\t// we honour the live flag and report no pool to keep the wire\n+\t// semantics in lockstep with /v1/health.upscaleEnabled).\n+\t// 2. Cached-variants count + total bytes from `track_variants`\n+\t// — survives across restarts and reflects historical work,\n+\t// so it stays non-zero when the feature was disabled without\n+\t// `--gc`. SQL failure degrades to \"0 cached\" with a logged\n+\t// warning rather than turning the whole response into a 5xx.\n+\t// 3. Sox-availability probe — same `transcode.PrecheckSox` the\n+\t// admin tile consumes, gated by the same 30 s TTL cache the\n+\t// admin handler uses (the admin cache holds it; we re-probe\n+\t// directly here, accepting one extra fork-exec per 5 s poll\n+\t// since iOS only polls when the management page is fore-\n+\t// grounded — typically zero polls per minute on average).\n+\tapiSrv.WithUpscaleStats(&upscaleStatsAdapter{\n+\t\tpool: func() *transcode.Pool { return upscalePool },\n+\t\tenabled: func() bool { return upscalePool != nil && cfg.Upscale.Enabled },\n+\t\tstore: manifestStore,\n+\t})\n \thttpSrv := &http.Server{\n \t\tAddr: cfg.ListenAddress,\n \t\tHandler: apiSrv.Handler(),", "status": "modified"}, {"additions": 32, "deletions": 14, "filename": "internal/api/api.go", "patch": "@@ -45,20 +45,21 @@ var logger = logging.Component(\"api\")\n \n // Server owns the http.Handler and the per-request state it needs.\n type Server struct {\n-\tcfg *config.Config\n-\tstore *auth.Store\n-\tresolver *bridgefs.Resolver\n-\tmanifest ManifestProvider\n-\tartworkDirs ArtworkDirProvider\n-\tmbidProbe MBIDProbe\n-\tupdater UpdaterStatus\n-\tsessions SessionTracker\n-\tpairing *pairing.Store\n-\tvariantStore VariantStore // nil unless WithUpscale(true, vs) called\n-\tupscaleEnabled bool // mirrors cfg.Upscale.Enabled (and sox-probe outcome)\n-\tupscaleEnqueuer UpscaleEnqueuer // nil unless WithUpscaleEnqueuer wired (Phase 2.5)\n-\tfingerprint string\n-\tstartedAt time.Time\n+\tcfg *config.Config\n+\tstore *auth.Store\n+\tresolver *bridgefs.Resolver\n+\tmanifest ManifestProvider\n+\tartworkDirs ArtworkDirProvider\n+\tmbidProbe MBIDProbe\n+\tupdater UpdaterStatus\n+\tsessions SessionTracker\n+\tpairing *pairing.Store\n+\tvariantStore VariantStore // nil unless WithUpscale(true, vs) called\n+\tupscaleEnabled bool // mirrors cfg.Upscale.Enabled (and sox-probe outcome)\n+\tupscaleEnqueuer UpscaleEnqueuer // nil unless WithUpscaleEnqueuer wired (Phase 2.5)\n+\tupscaleStatsProvider UpscaleStatsProvider // nil unless WithUpscaleStats wired (v1.2 management UI)\n+\tfingerprint string\n+\tstartedAt time.Time\n }\n \n // ErrUpscaleQueueFull is the typed sentinel UpscaleEnqueuer\n@@ -282,6 +283,22 @@ func (s *Server) WithPairing(p *pairing.Store) *Server {\n \treturn s\n }\n \n+// WithUpscaleStats attaches the snapshot provider for GET\n+// /v1/upscale/stats. Optional — when nil the endpoint returns the\n+// zero-value UpscaleStats (`enabled=false`, no pool, no sox\n+// availability), which iOS treats as \"feature off\" without\n+// distinguishing missing-endpoint from disabled-feature. Lets older\n+// bridges expose the route without the wiring overhead.\n+//\n+// Wired in cmd/bridge serve startup with the same closure the admin\n+// `/api/upscale/stats` tile already consumes — the two surfaces\n+// stay in lockstep so the admin operator and the paired iOS client\n+// see the same numbers.\n+func (s *Server) WithUpscaleStats(p UpscaleStatsProvider) *Server {\n+\ts.upscaleStatsProvider = p\n+\treturn s\n+}\n+\n // Resolver returns the internal path Resolver so the admin console can\n // call SetRoots when adding or removing a library root at runtime. The\n // api handlers and admin handlers deliberately share the same Resolver\n@@ -308,6 +325,7 @@ func (s *Server) Handler() http.Handler {\n \t// when no Store is wired the handlers themselves return\n \t// `pairing_not_supported`.\n \tmux.HandleFunc(\"POST /v1/upscale\", s.authed(s.upscaleRequest))\n+\tmux.HandleFunc(\"GET /v1/upscale/stats\", s.authed(s.upscaleStats))\n \tmux.HandleFunc(\"POST /v1/pairing/requests\", s.pairingRequest)\n \tmux.HandleFunc(\"GET /v1/pairing/{requestID}\", s.pairingPoll)\n \tmux.HandleFunc(\"DELETE /v1/pairing/{requestID}\", s.pairingDelete)", "status": "modified"}, {"additions": 90, "deletions": 0, "filename": "internal/api/upscale_stats.go", "patch": "@@ -0,0 +1,90 @@\n+package api\n+\n+import (\n+\t\"net/http\"\n+)\n+\n+// UpscaleStatsProvider is the interface GET /v1/upscale/stats reads.\n+// Mirrors the admin tile's data sources but lives here so the api\n+// package doesn't import internal/admin or internal/transcode.\n+//\n+// The cmd/bridge wiring constructs an adapter that returns the same\n+// pool snapshot the admin handler consumes — the two surfaces stay\n+// in lockstep.\n+//\n+// Nil-safe: when WithUpscaleStats wasn't called (test harness, or\n+// builds without the upscale wiring), the handler returns the\n+// zero-value UpscaleStats — `enabled=false, cachedVariants=0,\n+// cachedBytes=0, pool=nil, soxAvailable=nil`. iOS renders that as\n+// \"feature off\" without distinguishing a missing endpoint from a\n+// disabled feature, which matches the /v1/health.upscaleEnabled\n+// contract iOS already gates on.\n+type UpscaleStatsProvider interface {\n+\tUpscaleStatsSnapshot() UpscaleStats\n+}\n+\n+// UpscaleStats is the wire shape GET /v1/upscale/stats returns.\n+//\n+// Field-for-field compatible with the admin /api/upscale/stats\n+// payload — the JSON shapes intentionally match so an operator\n+// inspecting the bridge with `curl -k https://…/v1/upscale/stats`\n+// (with bearer token) sees the same body the Settings tile is\n+// already showing them. iOS uses it for the \"Upscaling\" management\n+// section inside BridgeEditorView (counts of cached / in-flight /\n+// failed jobs).\n+//\n+// - Enabled mirrors live runtime state, NOT the persisted\n+// `cfg.Upscale.Enabled` flag. The two diverge in two real\n+// cases the admin handler documents (see CLAUDE.md / PR #110):\n+// (a) startup demoted the feature when sox-precheck failed\n+// even though the flag was on; (b) the operator just PATCHed\n+// the flag off but the long-lived Pool is still alive until\n+// restart. Both surface as `pool == nil` from the wiring\n+// closure, and we report `enabled = (pool != nil)` so the\n+// iOS-facing /v1/health.upscaleEnabled and this endpoint\n+// agree about what \"active\" means.\n+// - Pool is omitted when the feature is off (no pool to query).\n+// - SoxAvailable is omitted when the test harness didn't wire a\n+// precheck closure.\n+type UpscaleStats struct {\n+\tEnabled bool `json:\"enabled\"`\n+\tSoxAvailable *bool `json:\"soxAvailable,omitempty\"`\n+\tPool *UpscalePoolStats `json:\"pool,omitempty\"`\n+\tCachedVariants int `json:\"cachedVariants\"`\n+\tCachedBytes int64 `json:\"cachedBytes\"`\n+}\n+\n+// UpscalePoolStats mirrors `transcode.PoolStats` field-for-field\n+// but lives here so the api package compiles without importing\n+// internal/transcode. The wiring closure in cmd/bridge/main.go\n+// translates between the two value types — same indirection the\n+// admin package already uses.\n+type UpscalePoolStats struct {\n+\tWorkers int `json:\"workers\"`\n+\tQueueCap int `json:\"queueCap\"`\n+\tQueueLen int `json:\"queueLen\"`\n+\tInflight int `json:\"inflight\"`\n+\tEnqueued uint64 `json:\"enqueued\"`\n+\tDone uint64 `json:\"done\"`\n+\tFailed uint64 `json:\"failed\"`\n+}\n+\n+// upscaleStats: GET /v1/upscale/stats\n+//\n+// Authenticated read-only snapshot of the upscale feature's\n+// runtime + on-disk state. Mirrors the admin /api/upscale/stats\n+// tile but exposed on the public protocol so paired iOS clients\n+// can render an \"Upscaling\" management section without needing\n+// admin auth. The wire shape is documented in docs/BridgeProtocol.md.\n+//\n+// Cheap (single SQL COUNT + a mutex-protected pool snapshot + a\n+// TTL-cached sox precheck — the closure dedupes against the same\n+// admin-side cache by sharing the precheck function reference).\n+// iOS calls every 5 s while the management page is foregrounded.\n+func (s *Server) upscaleStats(w http.ResponseWriter, r *http.Request) {\n+\tvar resp UpscaleStats\n+\tif s.upscaleStatsProvider != nil {\n+\t\tresp = s.upscaleStatsProvider.UpscaleStatsSnapshot()\n+\t}\n+\twriteJSON(w, http.StatusOK, resp)\n+}", "status": "added"}, {"additions": 174, "deletions": 0, "filename": "internal/api/upscale_stats_test.go", "patch": "@@ -0,0 +1,174 @@\n+package api\n+\n+import (\n+\t\"encoding/json\"\n+\t\"io\"\n+\t\"net/http\"\n+\t\"net/http/httptest\"\n+\t\"path/filepath\"\n+\t\"strings\"\n+\t\"testing\"\n+\n+\t\"github.com/acoseac/1-bit-bridge/internal/auth\"\n+\t\"github.com/acoseac/1-bit-bridge/internal/config\"\n+)\n+\n+// stubStatsProvider is a test double for api.UpscaleStatsProvider.\n+// Returns a fixed snapshot so tests can assert the wire shape and\n+// the auth gate without standing up a transcode pool.\n+type stubStatsProvider struct {\n+\tsnap UpscaleStats\n+}\n+\n+func (s *stubStatsProvider) UpscaleStatsSnapshot() UpscaleStats { return s.snap }\n+\n+func upscaleStatsFixture(t *testing.T, withProvider bool, snap UpscaleStats) (string /* baseURL */, string /* token */) {\n+\tt.Helper()\n+\ttmp := t.TempDir()\n+\tcfg := &config.Config{\n+\t\tLibraryRoots: []string{filepath.Join(tmp, \"lib\")},\n+\t\tListenAddress: \":7788\",\n+\t\tLibraryName: \"Test\",\n+\t}\n+\tstore, _ := auth.OpenStore(filepath.Join(tmp, \"tokens.json\"))\n+\traw, _, _ := store.Mint(\"test\")\n+\n+\tsrv := New(cfg, store, nil, \"fp\")\n+\tif withProvider {\n+\t\tsrv = srv.WithUpscaleStats(&stubStatsProvider{snap: snap})\n+\t}\n+\ths := httptest.NewServer(srv.Handler())\n+\tt.Cleanup(hs.Close)\n+\treturn hs.URL, raw\n+}\n+\n+// TestUpscaleStatsRequiresAuth — endpoint is bearer-token gated\n+// (same rule as POST /v1/upscale and every other /v1/* except\n+// /v1/health and the pairing routes).\n+func TestUpscaleStatsRequiresAuth(t *testing.T) {\n+\turl, _ := upscaleStatsFixture(t, true, UpscaleStats{Enabled: true})\n+\tresp, err := http.Get(url + \"/v1/upscale/stats\")\n+\tif err != nil {\n+\t\tt.Fatalf(\"GET: %v\", err)\n+\t}\n+\tdefer resp.Body.Close()\n+\tif resp.StatusCode != http.StatusUnauthorized {\n+\t\tt.Errorf(\"status: got %d, want 401\", resp.StatusCode)\n+\t}\n+}\n+\n+// TestUpscaleStatsNoProviderReturnsZero — when WithUpscaleStats\n+// wasn't wired (test harness, or build without upscale support)\n+// the handler returns the zero-value UpscaleStats. iOS treats this\n+// as \"feature off\" without distinguishing a missing endpoint from\n+// a disabled feature.\n+func TestUpscaleStatsNoProviderReturnsZero(t *testing.T) {\n+\turl, tok := upscaleStatsFixture(t, false, UpscaleStats{})\n+\tgot := getUpscaleStats(t, url, tok)\n+\tif got.Enabled {\n+\t\tt.Errorf(\"Enabled: got true, want false (no provider wired)\")\n+\t}\n+\tif got.Pool != nil {\n+\t\tt.Errorf(\"Pool: got %+v, want nil\", got.Pool)\n+\t}\n+\tif got.SoxAvailable != nil {\n+\t\tt.Errorf(\"SoxAvailable: got %+v, want nil\", got.SoxAvailable)\n+\t}\n+\tif got.CachedVariants != 0 || got.CachedBytes != 0 {\n+\t\tt.Errorf(\"cached counters: got (%d, %d), want (0, 0)\", got.CachedVariants, got.CachedBytes)\n+\t}\n+}\n+\n+// TestUpscaleStatsHappyPathWireShape — golden-shape test for the\n+// fully-populated payload iOS decodes against. The JSON field\n+// names are the contract — renaming any of them is a wire-breaking\n+// change even though they live behind an authed endpoint.\n+func TestUpscaleStatsHappyPathWireShape(t *testing.T) {\n+\ttru := true\n+\twant := UpscaleStats{\n+\t\tEnabled: true,\n+\t\tSoxAvailable: &tru,\n+\t\tPool: &UpscalePoolStats{\n+\t\t\tWorkers: 4,\n+\t\t\tQueueCap: 5000,\n+\t\t\tQueueLen: 12,\n+\t\t\tInflight: 4,\n+\t\t\tEnqueued: 142,\n+\t\t\tDone: 126,\n+\t\t\tFailed: 0,\n+\t\t},\n+\t\tCachedVariants: 138,\n+\t\tCachedBytes: 4823917568,\n+\t}\n+\turl, tok := upscaleStatsFixture(t, true, want)\n+\tgot := getUpscaleStats(t, url, tok)\n+\tif got.Enabled != want.Enabled {\n+\t\tt.Errorf(\"Enabled: got %v, want %v\", got.Enabled, want.Enabled)\n+\t}\n+\tif got.SoxAvailable == nil || *got.SoxAvailable != true {\n+\t\tt.Errorf(\"SoxAvailable: got %v, want true\", got.SoxAvailable)\n+\t}\n+\tif got.Pool == nil {\n+\t\tt.Fatalf(\"Pool: got nil, want non-nil\")\n+\t}\n+\tif *got.Pool != *want.Pool {\n+\t\tt.Errorf(\"Pool: got %+v, want %+v\", *got.Pool, *want.Pool)\n+\t}\n+\tif got.CachedVariants != want.CachedVariants || got.CachedBytes != want.CachedBytes {\n+\t\tt.Errorf(\"cached: got (%d, %d), want (%d, %d)\",\n+\t\t\tgot.CachedVariants, got.CachedBytes, want.CachedVariants, want.CachedBytes)\n+\t}\n+}\n+\n+// TestUpscaleStatsDisabledPoolOmitted — when the snapshot reports\n+// disabled, the `pool` and `soxAvailable` fields are documented as\n+// `omitempty`. Verify the wire JSON actually drops the keys (not\n+// just emits null) so the iOS decoder's lenient default path\n+// stays correct.\n+func TestUpscaleStatsDisabledPoolOmitted(t *testing.T) {\n+\turl, tok := upscaleStatsFixture(t, true, UpscaleStats{Enabled: false, CachedVariants: 5, CachedBytes: 1024})\n+\treq, _ := http.NewRequest(\"GET\", url+\"/v1/upscale/stats\", nil)\n+\treq.Header.Set(\"Authorization\", \"Bearer \"+tok)\n+\tresp, err := http.DefaultClient.Do(req)\n+\tif err != nil {\n+\t\tt.Fatalf(\"GET: %v\", err)\n+\t}\n+\tdefer resp.Body.Close()\n+\tbody, _ := io.ReadAll(resp.Body)\n+\tbs := string(body)\n+\tif strings.Contains(bs, `\"pool\"`) {\n+\t\tt.Errorf(\"pool field should be omitted when nil; got body: %s\", bs)\n+\t}\n+\tif strings.Contains(bs, `\"soxAvailable\"`) {\n+\t\tt.Errorf(\"soxAvailable field should be omitted when nil; got body: %s\", bs)\n+\t}\n+\t// The numeric fields are NOT omitempty (they always appear) —\n+\t// document that contract by asserting they're present even\n+\t// when zero would otherwise be omitted. writeJSON pretty-\n+\t// prints with `: ` separators, so match the field name and\n+\t// the value via `Contains` on each side rather than asserting\n+\t// the literal `\"cachedVariants\":5` form.\n+\tif !strings.Contains(bs, `\"cachedVariants\"`) || !strings.Contains(bs, `5`) {\n+\t\tt.Errorf(\"cachedVariants must always be present; got body: %s\", bs)\n+\t}\n+}\n+\n+func getUpscaleStats(t *testing.T, baseURL, token string) UpscaleStats {\n+\tt.Helper()\n+\treq, _ := http.NewRequest(\"GET\", baseURL+\"/v1/upscale/stats\", nil)\n+\treq.Header.Set(\"Authorization\", \"Bearer \"+token)\n+\tresp, err := http.DefaultClient.Do(req)\n+\tif err != nil {\n+\t\tt.Fatalf(\"GET: %v\", err)\n+\t}\n+\tdefer resp.Body.Close()\n+\tif resp.StatusCode != http.StatusOK {\n+\t\tbody, _ := io.ReadAll(resp.Body)\n+\t\tt.Fatalf(\"status: got %d, want 200 (body: %s)\", resp.StatusCode, string(body))\n+\t}\n+\tvar got UpscaleStats\n+\tif err := json.NewDecoder(resp.Body).Decode(&got); err != nil {\n+\t\tt.Fatalf(\"decode: %v\", err)\n+\t}\n+\treturn got\n+}", "status": "added"}], "message": "feat(api): public GET /v1/upscale/stats — paired-client view of pool + cache\n\nMirrors the admin /api/upscale/stats tile field-for-field, but\nexposes it on the public protocol so paired iOS clients can render\nan \"Upscaling\" management section without admin auth.\n\nWire shape additive — no protocol version bump. Pre-v1.2 bridges\nreturn 404, which iOS treats identically to {enabled: false}: clean\n\"feature off\" state without distinguishing missing-endpoint from\ndisabled-feature.\n\n* `enabled` matches /v1/health.upscaleEnabled (live runtime, not the\n persisted cfg flag — handles startup-demoted / mid-flight-PATCHed\n states the same way the admin handler does).\n* `pool` is omitempty when feature is off (no zero-padded clutter).\n* `cachedVariants`/`cachedBytes` survive across restarts and the\n feature-off→on round trip.\n\ncmd/bridge wiring uses the same pool snapshot the admin closure\nalready consumes, so the operator's Settings tile and the iOS\nclient see the same numbers — no drift between the two surfaces.\n\nAuthenticated (bearer token), same as POST /v1/upscale and every\nother /v1/* except /v1/health and the pairing routes.\n\nMirror-PR partner: iOS-side BridgeUpscaleService consumes this\nendpoint to render server-side queueLen / inflight / failed\ncounters in the per-share management section.\n\nCo-Authored-By: Claude Opus 4.7 (1M context) ", "sha": "af451fd941fccf58a6a0ef123e14527aae538701"}], "post_review_commits": ["868481f2b67224333c6c76c8ec98acccb46debd8"], "pr_author": "acoseac", "pr_title": "feat(api): public GET /v1/upscale/stats endpoint (additive, mirror of admin tile)", "repo_name": "acoseac/1-bit-bridge"}, "repo": "acoseac/1-bit-bridge", "snapshot": "snapshots/8c7a4fb5c81010d80d2ffc6dd4450f269f4179f5528d257323c8f451b236ad35.pack", "split": "rl", "task_id": "426ade36be371c54adb749a291b260c069156f510293e920f781746b868a1ff2"} {"base_sha": "fd3f591f0bdb1f5e128076861d77612265b4dc28", "cohort": null, "context": {"canonical_pr_url": "https://github.com/LeavittSoftware/titanium-elements/pull/732", "id": "430a1c72a83def92d1b49d1ba9dc23d0e428c0d95e42ead0a51c5b001d9a97c0", "preparation_mode": "source-only", "snapshot": {"base_ref": "fd3f591f0bdb1f5e128076861d77612265b4dc28", "base_sha": "fd3f591f0bdb1f5e128076861d77612265b4dc28", "body": "", "head_ref": "b125dbd18ade0da111229edf9ee6487f5f54b5c8", "head_sha": "b125dbd18ade0da111229edf9ee6487f5f54b5c8", "name": "titanium-elements", "number": 732, "owner": "LeavittSoftware", "pr_url": "https://github.com/LeavittSoftware/titanium-elements/pull/732", "title": ""}}, "head_sha": "b125dbd18ade0da111229edf9ee6487f5f54b5c8", "metadata": {"group_id": "66e054c99199a63be4db6d5bf7397dd5a692fd8b7e3edbc10ec7f3147d6a6ed2", "snapshot": {"base_sha": "fd3f591f0bdb1f5e128076861d77612265b4dc28", "external_requirements": [], "head_sha": "b125dbd18ade0da111229edf9ee6487f5f54b5c8", "objects": 369, "objects_sha256": "526c475d2562dea8f7424ff026e4b578094f4b4715c540e87c226caa0f6ec974", "patch_sha256": "3423581446d809edbe73024b0580beecffef3d9f91dbd4b5d953afe5fdff98a8"}}, "pr_number": 732, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "c33339f23d91", "description": "The email history viewer demo unconditionally reset the shared X-LGAppName header on disconnect, potentially overwriting the value set by a newly connected demo during Lit's lifecycle processing.", "file_path": "packages/leavittbook/src/demos/leavitt-email-history-viewer-demo.ts"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "c33339f23d91", "description": "The file explorer demo unconditionally reset the shared X-LGAppName header on disconnect, potentially overwriting the value set by a newly connected demo during Lit's lifecycle processing.", "file_path": "packages/leavittbook/src/demos/leavitt-file-explorer-demo.ts"}], "commits_under_review": [{"author": "kaseyhinton", "date": "2026-05-08T17:24:21Z", "files": [{"additions": 11, "deletions": 11, "filename": "packages/leavittbook/src/demos/leavitt-email-history-viewer-demo.ts", "patch": "@@ -9,29 +9,29 @@ import '@leavittsoftware/web/leavitt/email-history-viewer/email-history-viewer';\n import '@leavittsoftware/web/leavitt/email-history-viewer/email-history-viewer-filled';\n \n import { css, html, LitElement } from 'lit';\n-import { customElement, query, state } from 'lit/decorators.js';\n+import { customElement, query } from 'lit/decorators.js';\n import { ThemePreference } from '@leavittsoftware/web/leavitt/theme/theme-preference';\n \n-import ApiService from '@leavittsoftware/web/leavitt/api-service/api-service';\n import LeavittEmailHistoryViewer from '@leavittsoftware/web/leavitt/email-history-viewer/email-history-viewer';\n import LeavittEmailHistoryViewerFilled from '@leavittsoftware/web/leavitt/email-history-viewer/email-history-viewer-filled';\n-import UserManager from '../services/user-manager-service';\n import StoryStyles from '../styles/story-styles';\n import { siteSearchTextFieldContext } from '../contexts/site-search-text-field-context';\n+import api3UserService from '../services/api3-user-service';\n \n @customElement('leavitt-email-history-viewer-demo')\n export class LeavittEmailHistoryViewerDemo extends ThemePreference(LitElement) {\n- @state() private accessor apiService: ApiService;\n @query('leavitt-email-history-viewer') protected accessor demo1!: LeavittEmailHistoryViewer;\n @query('leavitt-email-history-viewer-filled') protected accessor demo2!: LeavittEmailHistoryViewerFilled;\n \n- constructor() {\n- super();\n- this.apiService = new ApiService(UserManager);\n- this.apiService.baseUrl = 'https://devapi3.leavitt.com/';\n- this.apiService.addHeader('X-LGAppName', 'EducationAdminV2');\n+ connectedCallback() {\n+ super.connectedCallback();\n+ api3UserService.addHeader('X-LGAppName', 'EducationAdminV2');\n }\n \n+ disconnectedCallback() {\n+ super.disconnectedCallback();\n+ api3UserService.addHeader('X-LGAppName', 'Testing');\n+ }\n static styles = [\n StoryStyles,\n css`\n@@ -58,7 +58,7 @@ export class LeavittEmailHistoryViewerDemo extends ThemePreference(LitElement) {\n \n \n@@ -72,7 +72,7 @@ export class LeavittEmailHistoryViewerDemo extends ThemePreference(LitElement) {\n
\n

Outlined

\n
\n- \n+ \n
\n
\n ", "status": "modified"}, {"additions": 10, "deletions": 10, "filename": "packages/leavittbook/src/demos/leavitt-file-explorer-demo.ts", "patch": "@@ -8,21 +8,21 @@ import '@leavittsoftware/web/titanium/snackbar/snackbar-stack';\n import '@leavittsoftware/web/leavitt/file-explorer/file-explorer';\n \n import { html, LitElement } from 'lit';\n-import { customElement, state } from 'lit/decorators.js';\n-import ApiService from '@leavittsoftware/web/leavitt/api-service/api-service';\n-import UserManager from '../services/user-manager-service';\n+import { customElement } from 'lit/decorators.js';\n \n import StoryStyles from '../styles/story-styles';\n+import api3UserService from '../services/api3-user-service';\n \n @customElement('leavitt-file-explorer-demo')\n export class LeavittFileExplorerDemo extends LitElement {\n- @state() private accessor fileExplorerApiService: ApiService;\n+ connectedCallback() {\n+ super.connectedCallback();\n+ api3UserService.addHeader('X-LGAppName', 'FileExplorer');\n+ }\n \n- constructor() {\n- super();\n- this.fileExplorerApiService = new ApiService(UserManager);\n- this.fileExplorerApiService.baseUrl = 'https://devapi3.leavitt.com/';\n- this.fileExplorerApiService.addHeader('X-LGAppName', 'FileExplorer');\n+ disconnectedCallback() {\n+ super.disconnectedCallback();\n+ api3UserService.addHeader('X-LGAppName', 'Testing');\n }\n \n static styles = [StoryStyles];\n@@ -39,7 +39,7 @@ export class LeavittFileExplorerDemo extends LitElement {\n
\n

File Explorer

\n

File explorer component with API integration

\n- \n+ \n
\n \n ", "status": "modified"}, {"additions": 9, "deletions": 18, "filename": "packages/leavittbook/src/demos/leavitt-person-company-select-demo.ts", "patch": "@@ -9,25 +9,16 @@ import '@leavittsoftware/web/leavitt/person-company-select/person-company-select\n import '@leavittsoftware/web/titanium/snackbar/snackbar-stack';\n \n import { html, LitElement } from 'lit';\n-import { customElement, query, state } from 'lit/decorators.js';\n+import { customElement, query } from 'lit/decorators.js';\n import { LeavittPersonCompanySelect } from '@leavittsoftware/web/leavitt/person-company-select/person-company-select';\n \n-import ApiService from '@leavittsoftware/web/leavitt/api-service/api-service';\n-import UserManager from '../services/user-manager-service';\n import StoryStyles from '../styles/story-styles';\n+import api3UserService from '../services/api3-user-service';\n \n @customElement('leavitt-person-company-select-demo')\n export class LeavittPersonCompanySelectDemo extends LitElement {\n- @state() private accessor apiService: ApiService;\n @query('leavitt-person-company-select[methods-demo]') protected accessor methodsSelect!: LeavittPersonCompanySelect;\n \n- constructor() {\n- super();\n- this.apiService = new ApiService(UserManager);\n- this.apiService.baseUrl = 'https://devapi3.leavitt.com/';\n- this.apiService.addHeader('X-LGAppName', 'Testing');\n- }\n-\n static styles = [StoryStyles];\n \n render() {\n@@ -43,7 +34,7 @@ export class LeavittPersonCompanySelectDemo extends LitElement {\n
\n

Methods

\n \n- \n+ \n \n
\n this.methodsSelect.reset()}>reset()\n@@ -55,15 +46,15 @@ export class LeavittPersonCompanySelectDemo extends LitElement {\n
\n

Attributes

\n \n- \n- \n+ \n+ \n \n \n \n \n \n
", "status": "modified"}, {"additions": 9, "deletions": 18, "filename": "packages/leavittbook/src/demos/leavitt-person-group-select-demo.ts", "patch": "@@ -8,25 +8,16 @@ import '@material/web/button/filled-tonal-button';\n import '@leavittsoftware/web/leavitt/person-group-select/person-group-select';\n \n import { html, LitElement } from 'lit';\n-import { customElement, query, state } from 'lit/decorators.js';\n+import { customElement, query } from 'lit/decorators.js';\n import { LeavittPersonGroupSelect } from '@leavittsoftware/web/leavitt/person-group-select/person-group-select';\n \n-import ApiService from '@leavittsoftware/web/leavitt/api-service/api-service';\n-import UserManager from '../services/user-manager-service';\n import StoryStyles from '../styles/story-styles';\n+import api3UserService from '../services/api3-user-service';\n \n @customElement('leavitt-person-group-select-demo')\n export class LeavittPersonGroupSelectDemo extends LitElement {\n- @state() private accessor apiService: ApiService;\n @query('leavitt-person-group-select[methods-demo]') protected accessor methodsSelect!: LeavittPersonGroupSelect;\n \n- constructor() {\n- super();\n- this.apiService = new ApiService(UserManager);\n- this.apiService.baseUrl = 'https://devapi3.leavitt.com/';\n- this.apiService.addHeader('X-LGAppName', 'Testing');\n- }\n-\n static styles = [StoryStyles];\n \n render() {\n@@ -42,16 +33,16 @@ export class LeavittPersonGroupSelectDemo extends LitElement {\n
\n

Default

\n \n- \n- \n+ \n+ \n \n \n- \n+ \n \n \n
\n \n
\n

Methods

\n \n- \n+ \n \n
\n this.methodsSelect.reset()}>reset()", "status": "modified"}, {"additions": 12, "deletions": 21, "filename": "packages/leavittbook/src/demos/leavitt-person-select-demo.ts", "patch": "@@ -9,26 +9,17 @@ import '@leavittsoftware/web/leavitt/profile-picture/profile-picture';\n import '@leavittsoftware/web/leavitt/person-select/person-select';\n \n import { html, LitElement } from 'lit';\n-import { customElement, query, state } from 'lit/decorators.js';\n+import { customElement, query } from 'lit/decorators.js';\n import { LeavittPersonSelect } from '@leavittsoftware/web/leavitt/person-select/person-select';\n import { Person } from '@leavittsoftware/lg-core-typescript';\n \n-import ApiService from '@leavittsoftware/web/leavitt/api-service/api-service';\n-import UserManager from '../services/user-manager-service';\n import StoryStyles from '../styles/story-styles';\n+import api3UserService from '../services/api3-user-service';\n \n @customElement('leavitt-person-select-demo')\n export class LeavittPersonSelectDemo extends LitElement {\n- @state() private accessor apiService: ApiService;\n @query('leavitt-person-select[methods-demo]') protected accessor methodsSelect!: LeavittPersonSelect;\n \n- constructor() {\n- super();\n- this.apiService = new ApiService(UserManager);\n- this.apiService.baseUrl = 'https://devapi3.leavitt.com/';\n- this.apiService.addHeader('X-LGAppName', 'Testing');\n- }\n-\n static styles = [StoryStyles];\n \n render() {\n@@ -42,7 +33,7 @@ export class LeavittPersonSelectDemo extends LitElement {\n \n
\n

Methods

\n- \n+ \n
\n this.methodsSelect.reset()}>reset()\n this.methodsSelect.focus()}>focus()\n@@ -66,7 +57,7 @@ export class LeavittPersonSelectDemo extends LitElement {\n 'count=true',\n ]}\n enable-people-preloading\n- .apiService=${this.apiService}\n+ .apiService=${api3UserService}\n >\n
\n \n@@ -127,7 +118,7 @@ export class LeavittPersonSelectDemo extends LitElement {\n
\n

Attributes

\n \n- \n+ \n \n \n \n- \n- \n- \n- \n- \n- \n+ \n+ \n+ \n+ \n+ \n+ \n \n
\n ", "status": "modified"}], "message": "chore: update demos to use shared api service", "sha": "b125dbd18ade0da111229edf9ee6487f5f54b5c8"}], "post_review_commits": ["c33339f23d91d8b5284214212804f8c5f921c86c"], "pr_author": "kaseyhinton", "pr_title": "chore: update demos to use shared api service", "repo_name": "LeavittSoftware/titanium-elements"}, "repo": "LeavittSoftware/titanium-elements", "snapshot": "snapshots/66e054c99199a63be4db6d5bf7397dd5a692fd8b7e3edbc10ec7f3147d6a6ed2.pack", "split": "rl", "task_id": "430a1c72a83def92d1b49d1ba9dc23d0e428c0d95e42ead0a51c5b001d9a97c0"} {"base_sha": "71a424833174dcc01f810b4d0672fa0044db1f6a", "cohort": null, "context": {"canonical_pr_url": "https://github.com/GainForest/hyperindex/pull/106", "id": "44745f6bd8aa77ac5dbd860d715428fd75f0581d469e603c7ee7c5ba28e1419c", "preparation_mode": "source-only", "snapshot": {"base_ref": "71a424833174dcc01f810b4d0672fa0044db1f6a", "base_sha": "71a424833174dcc01f810b4d0672fa0044db1f6a", "body": "", "head_ref": "ba2337ad25dd6bf53155f30eba3b60692748f9be", "head_sha": "ba2337ad25dd6bf53155f30eba3b60692748f9be", "name": "hyperindex", "number": 106, "owner": "GainForest", "pr_url": "https://github.com/GainForest/hyperindex/pull/106", "title": ""}}, "head_sha": "ba2337ad25dd6bf53155f30eba3b60692748f9be", "metadata": {"group_id": "8f3d17031d12fe7596bb3d41a243afe6636b4224d37640821c0a750a2c8d8d8f", "snapshot": {"base_sha": "71a424833174dcc01f810b4d0672fa0044db1f6a", "external_requirements": [], "head_sha": "ba2337ad25dd6bf53155f30eba3b60692748f9be", "objects": 508, "objects_sha256": "f58ffc19f3af136b4867d169349246dfd99a060b59fb0f60fb22752aa710fa80", "patch_sha256": "af6aac53f76fc82f85ed5d0eefcf5c6eefdcb50dbe5d57967fa24b9c95b0d5f7"}}, "pr_number": 106, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "performance", "commit_sha": "ac4d6a55da5e", "description": "The release-label check ran after Go setup, build/test, and Changie work, wasting CI time when the required label was missing.", "file_path": ".github/workflows/prepare-release-pr.yml"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "ac4d6a55da5e", "description": "The label check discarded GitHub CLI errors and reported every failure as a missing label, hiding authentication, API, and network failures.", "file_path": ".github/workflows/prepare-release-pr.yml"}], "commits_under_review": [{"author": "Kzoeps", "date": "2026-06-29T22:59:06Z", "files": [{"additions": 5, "deletions": 6, "filename": ".github/workflows/prepare-release-pr.yml", "patch": "@@ -79,16 +79,15 @@ jobs:\n exit 1\n fi\n \n- - name: Ensure release label exists\n+ - name: Verify release label exists\n env:\n GH_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN || secrets.GITHUB_TOKEN }}\n run: |\n- if gh label view release >/dev/null 2>&1; then\n- echo \"Release label already exists.\"\n- else\n- gh label create release --description \"Release PRs that publish automatically after merge\" --color \"0E8A16\"\n- echo \"Created release label.\"\n+ if ! gh label view release >/dev/null 2>&1; then\n+ echo \"::error::Required release label does not exist. Create a 'release' label before running this workflow.\"\n+ exit 1\n fi\n+ echo \"Release label exists.\"\n \n - name: Create or update release PR\n uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1", "status": "modified"}], "message": "ci: verify release label before release PR", "sha": "ba2337ad25dd6bf53155f30eba3b60692748f9be"}], "post_review_commits": ["ac4d6a55da5e2d3674608136d031342070a72fda"], "pr_author": "Kzoeps", "pr_title": "ci: verify release label before release PR", "repo_name": "GainForest/hyperindex"}, "repo": "GainForest/hyperindex", "snapshot": "snapshots/8f3d17031d12fe7596bb3d41a243afe6636b4224d37640821c0a750a2c8d8d8f.pack", "split": "rl", "task_id": "44745f6bd8aa77ac5dbd860d715428fd75f0581d469e603c7ee7c5ba28e1419c"} {"base_sha": "f9cc8c0098c5b94041a1567b26276c2f02221122", "cohort": null, "context": {"canonical_pr_url": "https://github.com/wave-av/wave-desktop/pull/5", "id": "44978d14809c64ff02662bc0f9c17cb210f5173129615641ff21088b5668c6d0", "preparation_mode": "source-only", "snapshot": {"base_ref": "f9cc8c0098c5b94041a1567b26276c2f02221122", "base_sha": "f9cc8c0098c5b94041a1567b26276c2f02221122", "body": "", "head_ref": "84786dc9cfd298458f06b74437e7f596f6c5d69d", "head_sha": "84786dc9cfd298458f06b74437e7f596f6c5d69d", "name": "wave-desktop", "number": 5, "owner": "wave-av", "pr_url": "https://github.com/wave-av/wave-desktop/pull/5", "title": ""}}, "head_sha": "84786dc9cfd298458f06b74437e7f596f6c5d69d", "metadata": {"group_id": "aca09a9cd9725bc2c2bf9fe6085a8a02b3ac668aac76ebf602b6efe666409d32", "snapshot": {"base_sha": "f9cc8c0098c5b94041a1567b26276c2f02221122", "external_requirements": [], "head_sha": "84786dc9cfd298458f06b74437e7f596f6c5d69d", "objects": 9, "objects_sha256": "7bcbd8f990dfd64cf0a536f6d3d224c49f61980db1433fad26b778329eeaa290", "patch_sha256": "19d9f9ac19b6230c7e22a0640bf95a8ecdf81348ea1cb2305d3ba6c20c985dcd"}}, "pr_number": 5, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "a35102b9bda5", "description": "The capability registry exposed Electron renderer-to-main IPC channels as HTTP APIs, falsely presenting intra-app implementation details as inter-product platform contracts and misleading consumers expecting HTTP endpoints.", "file_path": "capabilities.json"}], "commits_under_review": [{"author": "yakimoto", "date": "2026-06-01T19:47:13Z", "files": [{"additions": 33, "deletions": 0, "filename": "capabilities.json", "patch": "@@ -0,0 +1,33 @@\n+{\n+ \"schemaVersion\": \"1\",\n+ \"repo\": \"wave-av/wave-desktop\",\n+ \"version\": \"0.2.0\",\n+ \"lifecycle\": \"alpha\",\n+ \"planeLayer\": 0,\n+ \"foundationPin\": \"v1\",\n+ \"maintainers\": [{ \"team\": \"operator\" }],\n+ \"exposes\": {\n+ \"renderSurfaces\": [{ \"kind\": \"electron-app\", \"id\": \"online.wave.desktop\" }],\n+ \"apis\": [\n+ { \"protocol\": \"http\", \"endpoint\": \"ipc://wave:auth:state\", \"auth\": \"none\" },\n+ { \"protocol\": \"http\", \"endpoint\": \"ipc://wave:encoder:start\", \"auth\": \"bearer-jwt\" }\n+ ]\n+ },\n+ \"consumes\": {\n+ \"waveProducts\": [\n+ { \"repo\": \"wave-av/wave-gateway\", \"endpoint\": \"/oauth/device/code\" },\n+ { \"repo\": \"wave-av/wave-gateway\", \"endpoint\": \"/oauth/token\" }\n+ ],\n+ \"thirdParty\": [\n+ { \"service\": \"electron-safe-storage\", \"licenseGated\": false }\n+ ],\n+ \"foundationFrameworks\": [\"frameworks/protocol-plane\", \"frameworks/platform-registry\", \"frameworks/copywriting\"]\n+ },\n+ \"events\": {\n+ \"publishes\": [\n+ { \"topic\": \"auth.signed-in\", \"transport\": \"sentry\" },\n+ { \"topic\": \"auth.sign-in.failed\", \"transport\": \"sentry\" }\n+ ]\n+ },\n+ \"tags\": [\"operator\", \"public\", \"electron\", \"on-prem\", \"build-on-wave\", \"oauth-device-code\"]\n+}", "status": "added"}], "message": "feat: add capabilities.json (platform-registry Phase D)\n\nPublishes this repo to wave-foundation/frameworks/platform-registry.\n\nCo-Authored-By: Claude Opus 4.7 (1M context) ", "sha": "84786dc9cfd298458f06b74437e7f596f6c5d69d"}], "post_review_commits": ["a35102b9bda518b5459d31103a1ba1692c9fc37a"], "pr_author": "yakimoto", "pr_title": "feat: add capabilities.json (platform-registry Phase D)", "repo_name": "wave-av/wave-desktop"}, "repo": "wave-av/wave-desktop", "snapshot": "snapshots/aca09a9cd9725bc2c2bf9fe6085a8a02b3ac668aac76ebf602b6efe666409d32.pack", "split": "rl", "task_id": "44978d14809c64ff02662bc0f9c17cb210f5173129615641ff21088b5668c6d0"} {"base_sha": "a45e32a37a746f495e28d720122627082e03298d", "cohort": null, "context": {"canonical_pr_url": "https://github.com/Robbie-Palmer/hq/pull/1133", "id": "4950ed42263bec199f3960b491205f51dcf2bdc6a7c3f55219d0a07c072148f2", "preparation_mode": "source-only", "snapshot": {"base_ref": "a45e32a37a746f495e28d720122627082e03298d", "base_sha": "a45e32a37a746f495e28d720122627082e03298d", "body": "", "head_ref": "78357a0dcc1debf196b3843fa543ee744cc8a03a", "head_sha": "78357a0dcc1debf196b3843fa543ee744cc8a03a", "name": "hq", "number": 1133, "owner": "Robbie-Palmer", "pr_url": "https://github.com/Robbie-Palmer/hq/pull/1133", "title": ""}}, "head_sha": "78357a0dcc1debf196b3843fa543ee744cc8a03a", "metadata": {"group_id": "596f441bb2e34216ad7e785a23fc44e6b49db7db48c1b80e8d91e223501cf37e", "snapshot": {"base_sha": "a45e32a37a746f495e28d720122627082e03298d", "external_requirements": [], "head_sha": "78357a0dcc1debf196b3843fa543ee744cc8a03a", "objects": 1682, "objects_sha256": "8c6343fb85732e4b9feb49fd7cb06d8ee92676436875dd7548f51f056cea9fc1", "patch_sha256": "066b08b5af6914d8660796d39a21ca80347d25b2a86a861b5ca276e86db47733"}}, "pr_number": 1133, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "b30563822413", "description": "The public recipe aggregate was cached for 15 minutes, and rendered assets could receive a fresh cache lifetime from an already-aged aggregate. The two cache layers could therefore extend exposure of recipes after their public visibility was revoked.", "file_path": "functions/lib/recipe-asset.ts"}, {"action_id": "A2", "action_type": "improvement", "category": "performance", "commit_sha": "2c6210425e10", "description": "A five-minute pantry refetch interval introduced recurring database reads despite realtime updates and existing focus, online, and reconnect recovery paths. The owner chose to remove that fallback polling to preserve the request-load reduction.", "file_path": "ui/lib/query/pantry-queries.ts"}], "commits_under_review": [{"author": "Robbie-Palmer", "date": "2026-08-30T12:04:59Z", "files": [{"additions": 1, "deletions": 1, "filename": "functions/lib/public-recipes.ts", "patch": "@@ -42,7 +42,7 @@ function isRecipeVisibility(\n return value === \"public\" || value === \"private\" || value === \"household\";\n }\n \n-function isStoredRecipe(value: unknown): value is StoredRecipe {\n+export function isStoredRecipe(value: unknown): value is StoredRecipe {\n return (\n isRecord(value) &&\n typeof value.slug === \"string\" &&", "status": "modified"}, {"additions": 94, "deletions": 2, "filename": "functions/lib/recipe-asset.ts", "patch": "@@ -1,9 +1,101 @@\n import type { PublicRecipeEnv, StoredRecipe } from \"./public-recipes\";\n-import { listPublicRecipes } from \"./public-recipes\";\n+import { isStoredRecipe, listPublicRecipes } from \"./public-recipes\";\n+\n+const PUBLIC_RECIPE_CACHE_NAME = \"recipe-assets-v1\";\n+const PUBLIC_RECIPE_CACHE_PATH = \"/__recipe-assets/public-recipes.json\";\n+const PUBLIC_RECIPE_CACHE_TTL_SECONDS = 15 * 60;\n+const pendingRecipeLists = new Map<\n+ string,\n+ Promise\n+>();\n \n export interface RecipeAssetContext {\n request: Request;\n env: PublicRecipeEnv & { ASSETS: { fetch: typeof fetch } };\n+ waitUntil?: (promise: Promise) => void;\n+}\n+\n+function publicRecipeCacheKey(request: Request): Request {\n+ const url = new URL(PUBLIC_RECIPE_CACHE_PATH, request.url);\n+ return new Request(url, { method: \"GET\" });\n+}\n+\n+async function openPublicRecipeCache(): Promise {\n+ const storage = Reflect.get(globalThis, \"caches\") as\n+ | CacheStorage\n+ | undefined;\n+ if (!storage || typeof storage.open !== \"function\") return null;\n+ try {\n+ return await storage.open(PUBLIC_RECIPE_CACHE_NAME);\n+ } catch {\n+ return null;\n+ }\n+}\n+\n+async function readCachedPublicRecipes(\n+ cache: Cache,\n+ cacheKey: Request,\n+): Promise {\n+ try {\n+ const response = await cache.match(cacheKey);\n+ if (!response) return null;\n+ const value: unknown = await response.json();\n+ return Array.isArray(value) &&\n+ value.every(\n+ (item) => isStoredRecipe(item) && item.visibility === \"public\",\n+ )\n+ ? value\n+ : null;\n+ } catch {\n+ return null;\n+ }\n+}\n+\n+function cachePublicRecipes(\n+ cache: Cache | null,\n+ cacheKey: Request,\n+ recipes: Promise,\n+): Promise {\n+ return recipes\n+ .then(async (records) => {\n+ if (!cache || !records) return;\n+ const response = Response.json(records, {\n+ headers: {\n+ \"cache-control\": `public, s-maxage=${PUBLIC_RECIPE_CACHE_TTL_SECONDS}`,\n+ },\n+ });\n+ await cache.put(cacheKey, response);\n+ })\n+ .catch(() => undefined)\n+ .finally(() => {\n+ if (pendingRecipeLists.get(cacheKey.url) === recipes) {\n+ pendingRecipeLists.delete(cacheKey.url);\n+ }\n+ });\n+}\n+\n+async function publicRecipesForAsset(\n+ context: RecipeAssetContext,\n+): Promise {\n+ const cacheKey = publicRecipeCacheKey(context.request);\n+ const cache = await openPublicRecipeCache();\n+ if (cache) {\n+ const cached = await readCachedPublicRecipes(cache, cacheKey);\n+ if (cached) return cached;\n+ }\n+\n+ const pending = pendingRecipeLists.get(cacheKey.url);\n+ if (pending) return pending;\n+\n+ const recipes = listPublicRecipes(context.env);\n+ pendingRecipeLists.set(cacheKey.url, recipes);\n+ const cacheWrite = cachePublicRecipes(cache, cacheKey, recipes);\n+ if (context.waitUntil) {\n+ context.waitUntil(cacheWrite);\n+ } else {\n+ await cacheWrite;\n+ }\n+ return recipes;\n }\n \n export function rewrittenRecipeAssetHeaders(\n@@ -26,7 +118,7 @@ export async function augmentRecipeAsset(\n const asset = await context.env.ASSETS.fetch(context.request);\n if (!asset.ok || context.request.method === \"HEAD\") return asset;\n \n- const recipes = await listPublicRecipes(context.env);\n+ const recipes = await publicRecipesForAsset(context);\n if (!recipes) return asset;\n \n const body = render(await asset.text(), recipes, new URL(context.request.url));", "status": "modified"}, {"additions": 0, "deletions": 1, "filename": "ui/lib/query/pantry-queries.ts", "patch": "@@ -13,6 +13,5 @@ export const pantryQuery = (userId: string) =>\n structuralSharing: (current, incoming) =>\n installPantrySnapshot(current as Pantry | undefined, incoming as Pantry),\n staleTime: 15_000,\n- refetchInterval: 30_000,\n refetchOnWindowFocus: true,\n });", "status": "modified"}, {"additions": 188, "deletions": 0, "filename": "ui/tests/functions/recipe-assets.test.ts", "patch": "@@ -0,0 +1,188 @@\n+import { afterEach, describe, expect, it, vi } from \"vitest\";\n+import type { StoredRecipe } from \"../../../functions/lib/public-recipes\";\n+import {\n+ augmentRecipeAsset,\n+ type RecipeAssetContext,\n+} from \"../../../functions/lib/recipe-asset\";\n+\n+const CACHE_PATH = \"/__recipe-assets/public-recipes.json\";\n+\n+function recipe(slug: string, title: string): StoredRecipe {\n+ return {\n+ slug,\n+ title,\n+ description: null,\n+ body: null,\n+ visibility: \"public\",\n+ };\n+}\n+\n+function cacheDouble(initial?: Record) {\n+ const entries = new Map(\n+ Object.entries(initial ?? {}).map(([key, response]) => [\n+ key,\n+ response.clone(),\n+ ]),\n+ );\n+ const cache = {\n+ match: vi.fn(async (request: RequestInfo | URL) => {\n+ const key = request instanceof Request ? request.url : request.toString();\n+ return entries.get(key)?.clone();\n+ }),\n+ put: vi.fn(async (request: RequestInfo | URL, response: Response) => {\n+ const key = request instanceof Request ? request.url : request.toString();\n+ entries.set(key, response.clone());\n+ }),\n+ } as unknown as Cache;\n+ return { cache, entries };\n+}\n+\n+function context(url: string, pending: Promise[]): RecipeAssetContext {\n+ return {\n+ request: new Request(url),\n+ env: {\n+ RECIPE_API_URL: \"https://recipe-api.example.test\",\n+ ASSETS: {\n+ fetch: vi.fn(async () => new Response(\"static asset\")) as typeof fetch,\n+ },\n+ },\n+ waitUntil: (promise) => pending.push(promise),\n+ };\n+}\n+\n+function render(asset: string, records: StoredRecipe[]): string {\n+ return `${asset}: ${records.map((record) => record.title).join(\", \")}`;\n+}\n+\n+afterEach(() => {\n+ vi.restoreAllMocks();\n+ vi.unstubAllGlobals();\n+});\n+\n+describe(\"recipe asset aggregation cache\", () => {\n+ it(\"uses a host-scoped cached recipe list without calling the API\", async () => {\n+ const cacheUrl = `https://pr-123.example.test${CACHE_PATH}`;\n+ const { cache } = cacheDouble({\n+ [cacheUrl]: Response.json([recipe(\"cached\", \"Cached recipe\")]),\n+ });\n+ const open = vi.fn(async () => cache);\n+ const apiFetch = vi.fn();\n+ vi.stubGlobal(\"caches\", { open });\n+ vi.stubGlobal(\"fetch\", apiFetch);\n+\n+ const response = await augmentRecipeAsset(\n+ context(\"https://pr-123.example.test/llms.txt\", []),\n+ render,\n+ );\n+\n+ expect(await response.text()).toBe(\"static asset: Cached recipe\");\n+ expect(open).toHaveBeenCalledWith(\"recipe-assets-v1\");\n+ expect(cache.match).toHaveBeenCalledWith(\n+ expect.objectContaining({ url: cacheUrl }),\n+ );\n+ expect(apiFetch).not.toHaveBeenCalled();\n+ });\n+\n+ it(\"stores a cache miss for 15 minutes and reuses it across assets\", async () => {\n+ const { cache } = cacheDouble();\n+ const open = vi.fn(async () => cache);\n+ const apiFetch = vi.fn(async () =>\n+ Response.json({\n+ items: [recipe(\"fresh\", \"Fresh recipe\")],\n+ nextCursor: null,\n+ }),\n+ );\n+ vi.stubGlobal(\"caches\", { open });\n+ vi.stubGlobal(\"fetch\", apiFetch);\n+ const pending: Promise[] = [];\n+\n+ const first = await augmentRecipeAsset(\n+ context(\"https://robbiepalmer.me/sitemap.xml\", pending),\n+ render,\n+ );\n+ await Promise.all(pending);\n+ const second = await augmentRecipeAsset(\n+ context(\"https://robbiepalmer.me/llms-full.txt\", []),\n+ render,\n+ );\n+\n+ expect(await first.text()).toBe(\"static asset: Fresh recipe\");\n+ expect(await second.text()).toBe(\"static asset: Fresh recipe\");\n+ expect(apiFetch).toHaveBeenCalledTimes(1);\n+ expect(cache.put).toHaveBeenCalledTimes(1);\n+ const [cacheKey, cachedResponse] = vi.mocked(cache.put).mock.calls[0] ?? [];\n+ expect(cacheKey).toEqual(\n+ expect.objectContaining({\n+ url: `https://robbiepalmer.me${CACHE_PATH}`,\n+ }),\n+ );\n+ expect(cachedResponse?.headers.get(\"cache-control\")).toBe(\n+ \"public, s-maxage=900\",\n+ );\n+ });\n+\n+ it(\"coalesces concurrent cache misses from different recipe assets\", async () => {\n+ const { cache } = cacheDouble();\n+ vi.stubGlobal(\"caches\", { open: vi.fn(async () => cache) });\n+ let resolveApi: ((response: Response) => void) | undefined;\n+ const apiResponse = new Promise((resolve) => {\n+ resolveApi = resolve;\n+ });\n+ const apiFetch = vi.fn(() => apiResponse);\n+ vi.stubGlobal(\"fetch\", apiFetch);\n+ const firstPending: Promise[] = [];\n+ const secondPending: Promise[] = [];\n+\n+ const first = augmentRecipeAsset(\n+ context(\"https://robbiepalmer.me/sitemap.xml\", firstPending),\n+ render,\n+ );\n+ const second = augmentRecipeAsset(\n+ context(\"https://robbiepalmer.me/llms.txt\", secondPending),\n+ render,\n+ );\n+ await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(1));\n+ resolveApi?.(\n+ Response.json({\n+ items: [recipe(\"shared\", \"Shared recipe\")],\n+ nextCursor: null,\n+ }),\n+ );\n+\n+ const responses = await Promise.all([first, second]);\n+ await Promise.all([...firstPending, ...secondPending]);\n+ expect(await responses[0].text()).toContain(\"Shared recipe\");\n+ expect(await responses[1].text()).toContain(\"Shared recipe\");\n+ expect(cache.put).toHaveBeenCalledTimes(1);\n+ });\n+\n+ it(\"serves the asset when cache reads and writes fail\", async () => {\n+ const cache = {\n+ match: vi.fn(async () => {\n+ throw new Error(\"cache read failed\");\n+ }),\n+ put: vi.fn(async () => {\n+ throw new Error(\"cache write failed\");\n+ }),\n+ } as unknown as Cache;\n+ vi.stubGlobal(\"caches\", { open: vi.fn(async () => cache) });\n+ vi.stubGlobal(\n+ \"fetch\",\n+ vi.fn(async () =>\n+ Response.json({\n+ items: [recipe(\"fallback\", \"Fallback recipe\")],\n+ nextCursor: null,\n+ }),\n+ ),\n+ );\n+ const pending: Promise[] = [];\n+\n+ const response = await augmentRecipeAsset(\n+ context(\"https://robbiepalmer.me/llms.txt\", pending),\n+ render,\n+ );\n+ await Promise.all(pending);\n+\n+ expect(await response.text()).toBe(\"static asset: Fallback recipe\");\n+ });\n+});", "status": "added"}, {"additions": 11, "deletions": 0, "filename": "ui/tests/lib/query/pantry-queries.test.ts", "patch": "@@ -0,0 +1,11 @@\n+import { describe, expect, it } from \"vitest\";\n+import { pantryQuery } from \"@/lib/query/pantry-queries\";\n+\n+describe(\"pantryQuery\", () => {\n+ it(\"relies on realtime updates and window-focus recovery instead of polling\", () => {\n+ const options = pantryQuery(\"user-1\");\n+\n+ expect(options.refetchInterval).toBeUndefined();\n+ expect(options.refetchOnWindowFocus).toBe(true);\n+ });\n+});", "status": "added"}], "message": "Reduce pantry and recipe asset request load", "sha": "78357a0dcc1debf196b3843fa543ee744cc8a03a"}], "post_review_commits": ["b305638224137515014549a7d1c533881f903612", "2c6210425e10ff8ff59e5c50fdbc9536aa6c7929"], "pr_author": "Robbie-Palmer", "pr_title": "Reduce pantry and recipe asset request load", "repo_name": "Robbie-Palmer/hq"}, "repo": "Robbie-Palmer/hq", "snapshot": "snapshots/596f441bb2e34216ad7e785a23fc44e6b49db7db48c1b80e8d91e223501cf37e.pack", "split": "rl", "task_id": "4950ed42263bec199f3960b491205f51dcf2bdc6a7c3f55219d0a07c072148f2"} {"base_sha": "a776b20575a94dab94613cf01e5d96f032f7163d", "cohort": null, "context": {"canonical_pr_url": "https://github.com/JagritGumber/sqlcx/pull/50", "id": "4a82567986b8074475b939742790bc296be1614a08c9c15db04ac7796ccca82b", "preparation_mode": "source-only", "snapshot": {"base_ref": "a776b20575a94dab94613cf01e5d96f032f7163d", "base_sha": "a776b20575a94dab94613cf01e5d96f032f7163d", "body": "", "head_ref": "3fb54a0309fa0e2f945748d556e815cac3521c79", "head_sha": "3fb54a0309fa0e2f945748d556e815cac3521c79", "name": "sqlcx", "number": 50, "owner": "JagritGumber", "pr_url": "https://github.com/JagritGumber/sqlcx/pull/50", "title": ""}}, "head_sha": "3fb54a0309fa0e2f945748d556e815cac3521c79", "metadata": {"group_id": "8983a095914c72ba524a47fc77feef03ea6289168c1b9d8d89471f3af6490d8f", "snapshot": {"base_sha": "a776b20575a94dab94613cf01e5d96f032f7163d", "external_requirements": [], "head_sha": "3fb54a0309fa0e2f945748d556e815cac3521c79", "objects": 214, "objects_sha256": "1c2cc7b59d73793e07ca4c26f3f63cf0a4c3b9d02f6c9f70350d243baab118f8", "patch_sha256": "afdbcdf2b0872fd03df5e9930dd89b8f2f6e96d377d7eacc14cefe119809fd40"}}, "pr_number": 50, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "other", "commit_sha": "e06c2f5106f0", "description": "The workspace still targeted Rust edition 2021 rather than the intended 2024 edition, leaving 2024 language features unavailable.", "file_path": "Cargo.toml"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "e06c2f5106f0", "description": "Generator tests used `gen` as a binding name, which is reserved in Rust edition 2024 and would prevent the tests from compiling after the edition upgrade.", "file_path": "crates/sqlcx-core/src/generator"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "9c71a1467f44", "description": "The macOS Apple Silicon binary package still declared version 1.0.0 while the parent npm package required 0.1.3, preventing its optional dependency from resolving.", "file_path": "packages/js/darwin-arm64/package.json"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "9c71a1467f44", "description": "The macOS Intel binary package still declared version 1.0.0 while the parent npm package required 0.1.3, preventing its optional dependency from resolving.", "file_path": "packages/js/darwin-x64/package.json"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "9c71a1467f44", "description": "The Linux ARM64 binary package still declared version 1.0.0 while the parent npm package required 0.1.3, preventing its optional dependency from resolving.", "file_path": "packages/js/linux-arm64-gnu/package.json"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "9c71a1467f44", "description": "The Linux x64 binary package still declared version 1.0.0 while the parent npm package required 0.1.3, preventing its optional dependency from resolving.", "file_path": "packages/js/linux-x64-gnu/package.json"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "9c71a1467f44", "description": "The Windows x64 binary package still declared version 1.0.0 while the parent npm package required 0.1.3, preventing its optional dependency from resolving.", "file_path": "packages/js/win32-x64-msvc/package.json"}], "commits_under_review": [{"author": "JagritGumber", "date": "2026-04-20T01:40:07Z", "files": [{"additions": 2, "deletions": 2, "filename": "Cargo.lock", "patch": "@@ -965,7 +965,7 @@ dependencies = [\n \n [[package]]\n name = \"sqlcx\"\n-version = \"1.0.0\"\n+version = \"0.1.3\"\n dependencies = [\n \"clap\",\n \"glob\",\n@@ -978,7 +978,7 @@ dependencies = [\n \n [[package]]\n name = \"sqlcx-core\"\n-version = \"1.0.0\"\n+version = \"0.1.3\"\n dependencies = [\n \"glob\",\n \"insta\",", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "Cargo.toml", "patch": "@@ -3,7 +3,7 @@ members = [\"crates/sqlcx-core\", \"crates/sqlcx\"]\n resolver = \"2\"\n \n [workspace.package]\n-version = \"1.0.0\"\n+version = \"0.1.3\"\n edition = \"2021\"\n license = \"MIT\"\n repository = \"https://github.com/JagritGumber/sqlcx\"", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "LICENSE", "patch": "@@ -1,6 +1,6 @@\n MIT License\n \n-Copyright (c) 2025 Jagrit Gumber\n+Copyright (c) 2025-2026 Jagrit Gumber\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal", "status": "modified"}, {"additions": 6, "deletions": 6, "filename": "package.json", "patch": "@@ -1,14 +1,14 @@\n {\n \"name\": \"sqlcx-orm\",\n- \"version\": \"1.0.0\",\n+ \"version\": \"0.1.3\",\n \"description\": \"SQL-first cross-language type-safe code generator\",\n \"bin\": { \"sqlcx\": \"packages/js/bin/sqlcx\" },\n \"optionalDependencies\": {\n- \"@sqlcx/darwin-arm64\": \"1.0.0\",\n- \"@sqlcx/darwin-x64\": \"1.0.0\",\n- \"@sqlcx/linux-x64-gnu\": \"1.0.0\",\n- \"@sqlcx/linux-arm64-gnu\": \"1.0.0\",\n- \"@sqlcx/win32-x64-msvc\": \"1.0.0\"\n+ \"@sqlcx/darwin-arm64\": \"0.1.3\",\n+ \"@sqlcx/darwin-x64\": \"0.1.3\",\n+ \"@sqlcx/linux-x64-gnu\": \"0.1.3\",\n+ \"@sqlcx/linux-arm64-gnu\": \"0.1.3\",\n+ \"@sqlcx/win32-x64-msvc\": \"0.1.3\"\n },\n \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/JagritGumber/sqlcx\" },\n \"license\": \"MIT\",", "status": "modified"}, {"additions": 6, "deletions": 6, "filename": "packages/js/package.json", "patch": "@@ -1,14 +1,14 @@\n {\n \"name\": \"sqlcx-orm\",\n- \"version\": \"1.0.0\",\n+ \"version\": \"0.1.3\",\n \"description\": \"SQL-first cross-language type-safe code generator\",\n \"bin\": { \"sqlcx\": \"bin/sqlcx\" },\n \"optionalDependencies\": {\n- \"@sqlcx/darwin-arm64\": \"1.0.0\",\n- \"@sqlcx/darwin-x64\": \"1.0.0\",\n- \"@sqlcx/linux-x64-gnu\": \"1.0.0\",\n- \"@sqlcx/linux-arm64-gnu\": \"1.0.0\",\n- \"@sqlcx/win32-x64-msvc\": \"1.0.0\"\n+ \"@sqlcx/darwin-arm64\": \"0.1.3\",\n+ \"@sqlcx/darwin-x64\": \"0.1.3\",\n+ \"@sqlcx/linux-x64-gnu\": \"0.1.3\",\n+ \"@sqlcx/linux-arm64-gnu\": \"0.1.3\",\n+ \"@sqlcx/win32-x64-msvc\": \"0.1.3\"\n },\n \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/JagritGumber/sqlcx\" },\n \"license\": \"MIT\",", "status": "modified"}], "message": "chore: correct version to 0.1.3 and LICENSE year to 2026\n\nThe Cargo.toml and package.json files had been labeled 1.0.0\naspirationally — nothing with that version has ever been published\n(crates.io: no such crate; npm sqlcx-orm latest is 0.1.2 from the\nold TS codebase). Bumping to 0.1.3 for the next publish off the\nRust rewrite reflects reality.\n\nAlso update LICENSE copyright line from \"2025\" to \"2025-2026\" to\ncover the current calendar year.", "sha": "3fb54a0309fa0e2f945748d556e815cac3521c79"}], "post_review_commits": ["e06c2f5106f03a041c86989fc9d5904fcdbe2823", "9c71a1467f4461dcc2d04e4630c70dcd230f110c"], "pr_author": "JagritGumber", "pr_title": "chore: correct version to 0.1.3 and LICENSE year", "repo_name": "JagritGumber/sqlcx"}, "repo": "JagritGumber/sqlcx", "snapshot": "snapshots/8983a095914c72ba524a47fc77feef03ea6289168c1b9d8d89471f3af6490d8f.pack", "split": "rl", "task_id": "4a82567986b8074475b939742790bc296be1614a08c9c15db04ac7796ccca82b"} {"base_sha": "b2474bfa7e73fcf83e96d1fdd244b79492fa69c3", "cohort": null, "context": {"canonical_pr_url": "https://github.com/orchidautomation/sendlens-plugin/pull/54", "id": "4ab6f7c746b697bf6504821f25e0d4aa21a99a9eab91fc4399c000bb2f6cc5d7", "preparation_mode": "source-only", "snapshot": {"base_ref": "b2474bfa7e73fcf83e96d1fdd244b79492fa69c3", "base_sha": "b2474bfa7e73fcf83e96d1fdd244b79492fa69c3", "body": "", "head_ref": "122cfd4fd25506aae11d9db03870fb7d59d61b31", "head_sha": "122cfd4fd25506aae11d9db03870fb7d59d61b31", "name": "sendlens-plugin", "number": 54, "owner": "orchidautomation", "pr_url": "https://github.com/orchidautomation/sendlens-plugin/pull/54", "title": ""}}, "head_sha": "122cfd4fd25506aae11d9db03870fb7d59d61b31", "metadata": {"group_id": "04b0e580cb9980626226c71703b578a52f387912bf1a28a7cf786ccd66bbbc5f", "snapshot": {"base_sha": "b2474bfa7e73fcf83e96d1fdd244b79492fa69c3", "external_requirements": [], "head_sha": "122cfd4fd25506aae11d9db03870fb7d59d61b31", "objects": 272, "objects_sha256": "6d26629719057a062a0cd949ea3b3dd4d4e5897de2ee4ee5b4a572849f3810ee", "patch_sha256": "9f150aea5491a58b36989d90999b5ab5c4e562aecbbf6740fff4ec921b7946b5"}}, "pr_number": 54, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "00d510394b1c", "description": "The coverage summary presented `latest_of_thread=true` as the basis for hydrated stored-context counts, although `reply_email_context` does not record the fetch request’s thread mode. This could make stored counts and the aggregate-to-hydrated gap appear to prove latest-thread-only coverage.", "file_path": "plugin/campaign-analysis-response.ts"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "79099e9feb3d", "description": "The hydration-state lookup fell back to a row for the same status but a different `latest_of_thread` mode, potentially marking the requested surface exhausted when only the other mode was exhausted.", "file_path": "plugin/campaign-analysis-response.ts"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "79099e9feb3d", "description": "When the aggregate reply count was unavailable, the coverage explanation still discussed recovering or closing an aggregate-to-hydrated gap that could not be calculated.", "file_path": "plugin/campaign-analysis-response.ts"}, {"action_id": "A4", "action_type": "fix", "category": "documentation", "commit_sha": "79099e9feb3d", "description": "The reply-auditor instructions required `reply_coverage_summary` gap fields even when the analyst used `fetch_reply_text`, which returns fetch counts but not the full coverage summary.", "file_path": "agents/reply-auditor.md"}, {"action_id": "A5", "action_type": "fix", "category": "documentation", "commit_sha": "79099e9feb3d", "description": "The reply-patterns guidance likewise applied full aggregate-to-hydrated gap reporting to `fetch_reply_text` workflows, where those summary semantics are unavailable.", "file_path": "docs/skills/reply-patterns.md"}, {"action_id": "A6", "action_type": "improvement", "category": "documentation", "commit_sha": "79099e9feb3d", "description": "The campaign-analyst protocol did not explicitly require preserving the tool’s neutral possible-cause explanation for an aggregate-to-hydrated gap, leaving room to assert an unsupported cause.", "file_path": "agents/campaign-analyst.md"}], "commits_under_review": [{"author": "orchidautomation", "date": "2026-07-12T01:28:20Z", "files": [{"additions": 1, "deletions": 0, "filename": "INSTRUCTIONS.md", "patch": "@@ -88,6 +88,7 @@ If the host degrades command routing to guidance, invoke the relevant specialist\n - Broad workspace and tag-scoped reads should default to active campaigns only. Only include inactive, paused, completed, or purely historical campaigns when the user explicitly asks for them.\n - For deep analysis, prefer one campaign at a time. Use workspace-level views only to rank or choose campaigns, then move to `load_campaign_data(campaign_id=...)` before doing detailed copy, reply, or ICP analysis. Use `prepare_campaign_analysis` before one-campaign working/not-working, reply-quality, winner, scale, or kill claims.\n - Prefer `reply_context` for positive/negative cohort analysis and \"what copy got responses?\" because it joins replied leads back to template context and locally reconstructed copy. Prefer `reply_email_context` after `prepare_campaign_analysis` because it is anchored on fetched reply emails and preserves bodies even when lead context is missing.\n+- After `prepare_campaign_analysis`, always distinguish `campaign_overview.reply_count_unique` from the selected List Email/latest-thread body surface. Report statuses, OOO exclusion, `latest_of_thread`, fetched/hydrated counts by status, exhaustion, and the aggregate-to-hydrated gap from `reply_coverage_summary`. Exhausted selected buckets do not prove every aggregate reply was hydrated, and maximum depth does not guarantee recovery of a remaining gap.\n - Prefer `rendered_outbound_context` when the user wants to inspect reconstructed lead-level copy or personalization QA. It is not exact delivered email text.\n - Prefer `lead_evidence` for lead-level ICP context and `lead_payload_kv` for campaign payload key/value analysis.\n - Prefer `campaign_tags` and `account_tags` over raw tag joins when the user wants client/tag scoping.", "status": "modified"}, {"additions": 5, "deletions": 3, "filename": "agents/campaign-analyst.md", "patch": "@@ -33,9 +33,10 @@ Use only SendLens MCP tools for SendLens analysis.\n 3. Pull `analysis_starters(topic=\"campaign-performance\")` before writing custom analysis.\n 4. Use exact aggregate surfaces for headline performance, reply rate, bounce rate, sequence/step metrics, sender/campaign settings, and template structure.\n 5. Before calling the campaign working, a winner, or ready to scale, call `prepare_campaign_analysis` for reply hydration, then inspect `reply_email_context`, context gaps, `reply_context`, and `campaign_variants` to verify reply quality and intended copy path.\n-6. If reply coverage is partial after balanced hydration, say that maximum-depth continuation is needed instead of treating aggregate reply rate as proof.\n-7. Use sampled lead/payload/reconstructed evidence only for hypotheses, examples, and next-test direction.\n-8. Treat campaign-specific variables through `lead_payload_kv` unless Instantly exposes them as stable lead columns.\n+6. After hydration, report the aggregate unique human reply count separately from the selected List Email body surface: selected statuses, OOO exclusion, `latest_of_thread`, fetched/hydrated counts by status, exhaustion, and the aggregate-to-hydrated gap from `reply_coverage_summary`.\n+7. If selected buckets are not exhausted, maximum depth may expose more selected-bucket rows but does not guarantee closing the aggregate gap. If selected buckets are exhausted, do not recommend maximum depth as a recovery guarantee and do not claim every aggregate reply was hydrated.\n+8. Use sampled lead/payload/reconstructed evidence only for hypotheses, examples, and next-test direction.\n+9. Treat campaign-specific variables through `lead_payload_kv` unless Instantly exposes them as stable lead columns.\n \n ## Suppression Rules\n \n@@ -54,6 +55,7 @@ campaign_diagnosis:\n \n evidence_basis:\n - -- ; ; \n+- \n \n working:\n - ", "status": "modified"}, {"additions": 7, "deletions": 4, "filename": "agents/reply-auditor.md", "patch": "@@ -34,10 +34,12 @@ Use only SendLens MCP tools for SendLens analysis.\n 4. When enough actual wording is needed for working/not-working or reply-quality analysis, call `prepare_campaign_analysis`, then query `reply_email_context`.\n 5. Use `fetch_reply_text` for a low-level manual fetch only when balanced premium depth is not needed.\n 6. Include out-of-office status `0` only when the user explicitly asks for OOO handling.\n-7. Use raw-detail recipes only for local diagnosis; do not paste raw reply bodies, reply-from fields, lead emails, or contact fields into external artifacts.\n-8. When segmenting by uploaded lead metadata or custom fields, query `lead_payload_kv` only after the campaign is fixed.\n-9. If title, role, or segment metadata is missing, describe it as thin uploaded lead metadata and recommend adding richer fields to future lead uploads.\n-10. If hydrated replies complain about irrelevant copy, wrong industry, wrong compliance domain, or a template that does not match the intended campaign, report setup/template-resolution risk before normal sentiment themes.\n+7. After hydration, report the aggregate unique human reply count separately from the selected List Email body surface: selected statuses, OOO exclusion, `latest_of_thread`, fetched/hydrated counts by status, exhaustion, and the aggregate-to-hydrated gap from `reply_coverage_summary`.\n+8. Treat exhausted selected buckets as exhausted only for that queried surface. Do not claim every aggregate reply was hydrated or imply maximum depth will recover a remaining gap; preserve the neutral possible-cause language from the tool response.\n+9. Use raw-detail recipes only for local diagnosis; do not paste raw reply bodies, reply-from fields, lead emails, or contact fields into external artifacts.\n+10. When segmenting by uploaded lead metadata or custom fields, query `lead_payload_kv` only after the campaign is fixed.\n+11. If title, role, or segment metadata is missing, describe it as thin uploaded lead metadata and recommend adding richer fields to future lead uploads.\n+12. If hydrated replies complain about irrelevant copy, wrong industry, wrong compliance domain, or a template that does not match the intended campaign, report setup/template-resolution risk before normal sentiment themes.\n \n ## Fallback And Suppression\n \n@@ -56,6 +58,7 @@ reply_verdict:\n \n evidence_basis:\n - -- ; ; \n+- \n \n positive_themes:\n - ", "status": "modified"}, {"additions": 5, "deletions": 2, "filename": "docs/MCP_RESPONSE_CONTRACT.md", "patch": "@@ -109,7 +109,10 @@ Where relevant, SendLens responses should include:\n - default `analysis_depth` is balanced: statuses `1`, `-1`, and `-2`, up to 3 email pages/status, and target 30 stored non-auto reply bodies/status\n - calls the same rate-conscious email lane as `fetch_reply_text`; it is not part of session-start refresh\n - backfills lead context through `/leads/list` contacts/ids after reply bodies are stored\n-- returns `fetch_result`, `lead_context_backfill`, `hydration_coverage`, `context_gap_counts`, exact `campaign_overview`, bounded `reply_email_context_sample`, recommended next recipes, warnings, and output limits\n+- returns `fetch_result`, `lead_context_backfill`, `hydration_coverage`, `reply_coverage_summary`, `context_gap_counts`, exact `campaign_overview`, bounded `reply_email_context_sample`, recommended next recipes, warnings, and output limits\n+- `reply_coverage_summary` reports `aggregate_reply_count`, `hydrated_reply_count`, `fetched_reply_count`, `coverage_gap_count`, `coverage_scope`, per-status counts, and selected-bucket exhaustion; the scope records selected statuses, OOO exclusion, and `latest_of_thread=true`\n+- `coverage_gap_count` is a cross-surface numeric comparison, not proof of missing bodies. Exhausted selected List Email buckets do not prove every reply represented by the campaign aggregate was hydrated, and maximum depth does not guarantee recovery of a remaining gap\n+- the neutral explanation lists possible semantic causes without selecting one: unselected or unclassified statuses, latest-of-thread behavior, historical/provider-retention differences, or campaign-aggregate versus List Email semantics\n - `reply_email_context_sample` is redacted by default: full `reply_body_text`, raw email address fields, and long quoted bodies are omitted while short redacted `reply_body_preview` values preserve diagnostic signal\n - `reply_evidence_detail` defaults to `redacted_preview`; full reply bodies and raw email addresses require explicit opt-in with `full_reply_bodies`\n - default recommended next recipes do not include raw reply-body feed recipes; `reply-email-context-feed` is recommended only when `reply_evidence_detail=\"full_reply_bodies\"`\n@@ -127,7 +130,7 @@ Run `npm run test:mcp-response-contract` when changing MCP tools, response field\n - `search_catalog` partial matches, narrower search terms, and workflow concept starter suggestions\n - `analyze_data` rationale, row caps, truncation state, warnings, and rows\n - `fetch_reply_text` hydration result metadata, sample caps, and bounded reply samples\n-- `prepare_campaign_analysis` premium-depth coverage, context gaps, backfill metadata, warnings, output limits, and bounded redacted reply-email samples unless full evidence is explicitly requested\n+- `prepare_campaign_analysis` premium-depth coverage, aggregate-to-hydrated gap semantics, selected statuses/OOO/latest-thread scope, per-status exhaustion, context gaps, backfill metadata, warnings, output limits, and bounded redacted reply-email samples unless full evidence is explicitly requested\n \n ## Exactness Rules\n ", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "docs/skills/campaign-performance.md", "patch": "@@ -25,6 +25,7 @@ Related: [catalog](../CATALOG.md), [trust and privacy](../TRUST_AND_PRIVACY.md),\n 4. Use exact campaign and account aggregate tables for headline comparisons.\n 5. If the user narrows to one campaign and needs fresher evidence, run `load_campaign_data`.\n 6. Before one-campaign working/not-working, winner, scale, or kill claims, run `prepare_campaign_analysis`.\n+7. Report aggregate unique human replies separately from the selected List Email body surface: statuses, OOO exclusion, `latest_of_thread`, per-status fetched/hydrated counts, exhaustion, and the aggregate-to-hydrated gap from `reply_coverage_summary`.\n \n ## Output Shape\n \n@@ -34,6 +35,7 @@ Related: [catalog](../CATALOG.md), [trust and privacy](../TRUST_AND_PRIVACY.md),\n - Runway/capacity read when relevant.\n - Next campaign or test to inspect.\n - Caveats about exact aggregate metrics versus sampled evidence.\n+- Neutral coverage language when selected hydration buckets and the campaign aggregate differ; exhausted selected buckets do not prove every aggregate reply was hydrated, and maximum depth does not guarantee gap recovery.\n \n ## Evidence Boundaries\n ", "status": "modified"}, {"additions": 4, "deletions": 0, "filename": "docs/skills/reply-patterns.md", "patch": "@@ -26,6 +26,7 @@ Related: [catalog](../CATALOG.md), [trust and privacy](../TRUST_AND_PRIVACY.md),\n 5. Run `fetch_reply_text` for exactly one campaign only when a low-level manual fetch is enough.\n 6. Separate positive, negative, and neutral outcomes from Instantly lead status before grouping by step or variant.\n 7. Use raw-detail recipes only for local diagnosis; do not paste raw reply bodies, reply-from fields, lead emails, or contact fields into external artifacts.\n+8. After hydration, report aggregate unique human replies separately from selected List Email body coverage: statuses, OOO exclusion, `latest_of_thread`, per-status fetched/hydrated counts, exhaustion, and the explicit numeric gap.\n \n ## Output Shape\n \n@@ -35,7 +36,10 @@ Related: [catalog](../CATALOG.md), [trust and privacy](../TRUST_AND_PRIVACY.md),\n - Step, variant, or segment concentrations.\n - Fetched reply-body themes when available.\n - Caveat on whether exact reply body text was fetched.\n+- Neutral aggregate-to-hydrated gap explanation; exhausted selected buckets do not prove every aggregate reply was hydrated, and maximum depth does not guarantee recovery.\n \n ## Evidence Boundaries\n \n By default, reply labels come from Instantly lead state. Only quote or characterize actual reply-body language from `reply_body_text` after `prepare_campaign_analysis` or `fetch_reply_text` has written exact reply rows into local DuckDB. Prefer `reply_email_context` after premium hydration because it preserves fetched bodies even when lead context is missing. Out-of-office status `0` is excluded by default unless the user asks for OOO replies.\n+\n+Do not collapse `campaign_overview.reply_count_unique` and hydrated reply-email rows into an unqualified “X of Y.” They are different evidence surfaces. A gap can reflect unselected or unclassified statuses, latest-of-thread behavior, historical/provider-retention differences, or aggregate-versus-List Email semantics; do not assert a cause without evidence.", "status": "modified"}, {"additions": 125, "deletions": 0, "filename": "plugin/campaign-analysis-response.ts", "patch": "@@ -2,6 +2,15 @@ export const CAMPAIGN_ANALYSIS_REPLY_PREVIEW_MAX_CHARS = 240;\n \n type ReplyContextRow = Record;\n \n+type CampaignReplyCoverageSummaryInput = {\n+ aggregateReplyCount: number | null;\n+ selectedStatuses: number[];\n+ latestOfThread: boolean;\n+ fetchByStatus: ReplyContextRow[];\n+ storedContextByStatus: ReplyContextRow[];\n+ hydrationState: ReplyContextRow[];\n+};\n+\n const SENSITIVE_REPLY_DETAIL_FIELDS = [\n \"lead_email\",\n \"normalized_email\",\n@@ -16,6 +25,122 @@ function stringValue(value: unknown) {\n return typeof value === \"string\" ? value : \"\";\n }\n \n+function numberValue(value: unknown) {\n+ const parsed = Number(value ?? 0);\n+ return Number.isFinite(parsed) ? parsed : 0;\n+}\n+\n+function statusValue(row: ReplyContextRow, key: string) {\n+ return Number(row[key]);\n+}\n+\n+function findStatusRow(\n+ rows: ReplyContextRow[],\n+ key: string,\n+ status: number,\n+) {\n+ return rows.find((row) => statusValue(row, key) === status);\n+}\n+\n+export function buildCampaignReplyCoverageSummary({\n+ aggregateReplyCount,\n+ selectedStatuses,\n+ latestOfThread,\n+ fetchByStatus,\n+ storedContextByStatus,\n+ hydrationState,\n+}: CampaignReplyCoverageSummaryInput) {\n+ const byStatus = selectedStatuses.map((status) => {\n+ const fetchRow = findStatusRow(fetchByStatus, \"i_status\", status) ?? {};\n+ const contextRow = findStatusRow(\n+ storedContextByStatus,\n+ \"reply_email_i_status\",\n+ status,\n+ ) ?? {};\n+ const stateRow = hydrationState.find((row) =>\n+ statusValue(row, \"i_status\") === status\n+ && row.latest_of_thread === latestOfThread\n+ ) ?? findStatusRow(hydrationState, \"i_status\", status) ?? {};\n+ const exhausted = stateRow.exhausted === true || fetchRow.exhausted === true;\n+\n+ return {\n+ i_status: status,\n+ i_status_label: stringValue(contextRow.reply_email_i_status_label) || null,\n+ fetched_reply_count: numberValue(fetchRow.rows_fetched),\n+ stored_reply_count: numberValue(contextRow.fetched_reply_rows),\n+ hydrated_reply_count: numberValue(contextRow.hydrated_reply_body_rows),\n+ coverage_status: stringValue(fetchRow.coverage_status) || null,\n+ exhausted,\n+ };\n+ });\n+\n+ const fetchedReplyCount = byStatus.reduce(\n+ (sum, row) => sum + row.fetched_reply_count,\n+ 0,\n+ );\n+ const storedReplyCount = byStatus.reduce(\n+ (sum, row) => sum + row.stored_reply_count,\n+ 0,\n+ );\n+ const hydratedReplyCount = byStatus.reduce(\n+ (sum, row) => sum + row.hydrated_reply_count,\n+ 0,\n+ );\n+ const normalizedAggregateReplyCount = aggregateReplyCount == null\n+ ? null\n+ : Math.max(0, numberValue(aggregateReplyCount));\n+ const coverageGapCount = normalizedAggregateReplyCount == null\n+ ? null\n+ : Math.max(normalizedAggregateReplyCount - hydratedReplyCount, 0);\n+ const allSelectedStatusBucketsExhausted = byStatus.length > 0\n+ && byStatus.every((row) => row.exhausted);\n+ const hasAggregateGap = coverageGapCount != null && coverageGapCount > 0;\n+ const coverageState = normalizedAggregateReplyCount == null\n+ ? allSelectedStatusBucketsExhausted\n+ ? \"selected_status_buckets_exhausted_aggregate_unavailable\"\n+ : \"selected_status_buckets_partial_aggregate_unavailable\"\n+ : allSelectedStatusBucketsExhausted\n+ ? hasAggregateGap\n+ ? \"selected_status_buckets_exhausted_with_aggregate_gap\"\n+ : \"selected_status_buckets_exhausted_without_numeric_gap\"\n+ : hasAggregateGap\n+ ? \"selected_status_buckets_partial_with_aggregate_gap\"\n+ : \"selected_status_buckets_partial_without_numeric_gap\";\n+\n+ const comparison = normalizedAggregateReplyCount == null\n+ ? `The campaign aggregate reply count is unavailable; ${hydratedReplyCount} stored reply-email rows have hydrated bodies within the selected List Email surface.`\n+ : `The campaign aggregate reports ${normalizedAggregateReplyCount} unique human replies; ${hydratedReplyCount} stored reply-email rows have hydrated bodies within the selected List Email surface, leaving an aggregate-to-hydrated numeric gap of ${coverageGapCount}.`;\n+ const exhaustionExplanation = allSelectedStatusBucketsExhausted\n+ ? \"The selected status buckets are exhausted. Increasing to maximum depth does not guarantee recovery of this gap once those buckets are exhausted.\"\n+ : \"One or more selected status buckets are not exhausted. Additional depth may expose more rows within those buckets, but it does not guarantee that the aggregate-to-hydrated gap will close.\";\n+ const semanticsExplanation =\n+ \"The campaign aggregate and selected List Email surface are different evidence scopes. A numeric gap can reflect unselected or unclassified provider statuses, latest-of-thread behavior, historical or provider-retention differences, or campaign-aggregate versus List Email semantics; this response does not establish which cause applies.\";\n+\n+ return {\n+ aggregate_reply_count: normalizedAggregateReplyCount,\n+ aggregate_reply_count_basis: \"campaign_overview.reply_count_unique\",\n+ fetched_reply_count: fetchedReplyCount,\n+ stored_reply_count: storedReplyCount,\n+ hydrated_reply_count: hydratedReplyCount,\n+ hydrated_reply_count_basis:\n+ \"stored reply_email_context rows with hydrated_reply_body=true for the selected statuses\",\n+ coverage_gap_count: coverageGapCount,\n+ coverage_gap_count_basis:\n+ \"max(aggregate_reply_count - hydrated_reply_count, 0); this is a cross-surface numeric comparison, not proof of missing reply bodies\",\n+ coverage_scope: {\n+ surface: \"provider_list_email_selected_statuses\",\n+ selected_statuses: selectedStatuses,\n+ ooo_status_excluded: !selectedStatuses.includes(0),\n+ latest_of_thread: latestOfThread,\n+ },\n+ by_status: byStatus,\n+ all_selected_status_buckets_exhausted: allSelectedStatusBucketsExhausted,\n+ coverage_state: coverageState,\n+ coverage_explanation:\n+ `${comparison} ${exhaustionExplanation} ${semanticsExplanation}`,\n+ };\n+}\n+\n function compactWhitespace(value: string) {\n return value.replace(/\\s+/g, \" \").trim();\n }", "status": "modified"}, {"additions": 2, "deletions": 1, "filename": "plugin/query-recipes.ts", "patch": "@@ -2574,7 +2574,8 @@ WHERE COALESCE(fc.campaign_id, hs.campaign_id) = '{{campaign_id}}'\n ORDER BY i_status DESC;`,\n notes: [\n \"Run prepare_campaign_analysis first for premium analysis; this recipe audits what is now hydrated locally.\",\n- \"Exact coverage is limited to fetched/stored email rows, not all campaign replies unless the status pagination was exhausted.\",\n+ \"Exact coverage is limited to the selected List Email status/latest-thread surface. Exhausted selected buckets do not prove complete coverage of the separate campaign aggregate.\",\n+ \"Report the aggregate unique human reply count, selected statuses, OOO exclusion, latest_of_thread, per-status fetched/hydrated counts, exhaustion, and the aggregate-to-hydrated gap. Maximum depth does not guarantee recovery once selected buckets are exhausted.\",\n \"Status 0 out-of-office is intentionally excluded unless explicitly requested.\",\n ],\n },", "status": "modified"}, {"additions": 24, "deletions": 2, "filename": "plugin/server.ts", "patch": "@@ -30,6 +30,7 @@ import {\n type CampaignAnalysisDepth,\n } from \"./campaign-analysis-depth\";\n import {\n+ buildCampaignReplyCoverageSummary,\n CAMPAIGN_ANALYSIS_REPLY_PREVIEW_MAX_CHARS,\n redactCampaignAnalysisReplySample,\n } from \"./campaign-analysis-response\";\n@@ -845,6 +846,7 @@ server.registerTool(\n \"Use this for questions like why a campaign is performing, what is working, what is not working, or how reply quality breaks down for one selected campaign.\",\n \"Default balanced depth fetches interested, not interested, and wrong-person replies with up to 3 List email pages per status, through the 3-second email lane, stopping when each status has enough stored non-auto reply bodies or pagination is exhausted.\",\n \"After reply fetch, it backfills lead context through Instantly /leads/list contacts/ids so reply bodies stay visible even when the bounded lead scan missed those leads.\",\n+ \"The reply_coverage_summary keeps campaign aggregate unique replies separate from hydrated List Email rows and reports selected statuses, OOO exclusion, latest_of_thread=true, per-status fetched/hydrated counts, exhaustion, the numeric gap, and a neutral explanation. Exhausted selected buckets do not prove complete aggregate reply hydration, and maximum depth does not guarantee recovery of a gap.\",\n ].join(\" \"),\n inputSchema: {\n campaign_id: z\n@@ -911,6 +913,7 @@ server.registerTool(\n const depth = resolveCampaignAnalysisDepth(\n analysis_depth as CampaignAnalysisDepth | undefined,\n );\n+ const latestOfThread = true;\n const resolvedStatuses = normalizeCampaignAnalysisStatuses(\n statuses,\n include_ooo,\n@@ -957,7 +960,7 @@ server.registerTool(\n campaignId: resolved.campaign_id,\n statuses: resolvedStatuses,\n maxPagesPerStatus: depth.maxPagesPerStatus,\n- latestOfThread: true,\n+ latestOfThread,\n mode: \"restart\",\n targetStoredRowsPerStatus: depth.targetStoredRowsPerStatus,\n db,\n@@ -1092,12 +1095,30 @@ server.registerTool(\n fetchResult,\n depth.targetStoredRowsPerStatus,\n );\n+ const replyCoverageSummary = buildCampaignReplyCoverageSummary({\n+ aggregateReplyCount: overviewRows.length > 0\n+ ? numberFromRow(overviewRows[0], \"reply_count_unique\")\n+ : null,\n+ selectedStatuses: resolvedStatuses,\n+ latestOfThread,\n+ fetchByStatus: fetchCoverage,\n+ storedContextByStatus: contextCoverageRows,\n+ hydrationState: hydrationStateRows,\n+ });\n const partialCoverage = fetchCoverage.filter((row) =>\n row.coverage_status === \"partial_cap_reached\"\n );\n if (partialCoverage.length > 0) {\n warnings.push(\n- \"At least one reply status hit the page cap before meeting the target. Treat status themes as partial coverage and continue at maximum depth before making strong claims.\",\n+ \"At least one selected reply status hit the page cap before meeting the target. Maximum depth may expose more rows within non-exhausted selected buckets, but it does not guarantee closing an aggregate-to-hydrated gap.\",\n+ );\n+ }\n+ if (\n+ replyCoverageSummary.all_selected_status_buckets_exhausted\n+ && Number(replyCoverageSummary.coverage_gap_count ?? 0) > 0\n+ ) {\n+ warnings.push(\n+ \"Selected reply status buckets are exhausted with a remaining aggregate-to-hydrated numeric gap. Do not describe this as complete aggregate reply hydration; maximum depth does not guarantee recovery. See reply_coverage_summary for scope and neutral causes.\",\n );\n }\n const replyEmailContextSample =\n@@ -1146,6 +1167,7 @@ server.registerTool(\n stored_context_by_status: contextCoverageRows,\n hydration_state: hydrationStateRows,\n },\n+ reply_coverage_summary: replyCoverageSummary,\n context_gap_counts: contextGapCounts,\n campaign_overview: overviewRows[0] ?? null,\n reply_email_context_sample: replyEmailContextSample,", "status": "modified"}, {"additions": 105, "deletions": 0, "filename": "scripts/test-campaign-analysis-response.mjs", "patch": "@@ -6,6 +6,7 @@ import { createRequire } from \"node:module\";\n const require = createRequire(import.meta.url);\n const {\n CAMPAIGN_ANALYSIS_REPLY_PREVIEW_MAX_CHARS,\n+ buildCampaignReplyCoverageSummary,\n buildSafeReplyPreview,\n redactCampaignAnalysisReplySample,\n } = require(\"../build/plugin/campaign-analysis-response.js\");\n@@ -68,4 +69,108 @@ const longPreview = buildSafeReplyPreview({\n assert.equal(longPreview.length, CAMPAIGN_ANALYSIS_REPLY_PREVIEW_MAX_CHARS);\n assert.ok(longPreview.endsWith(\"...\"));\n \n+const coverageSummary = buildCampaignReplyCoverageSummary({\n+ aggregateReplyCount: 33,\n+ selectedStatuses: [1, -1, -2],\n+ latestOfThread: true,\n+ fetchByStatus: [\n+ {\n+ i_status: 1,\n+ rows_fetched: 5,\n+ stored_rows_after: 5,\n+ exhausted: true,\n+ coverage_status: \"exhausted_below_target\",\n+ },\n+ {\n+ i_status: -1,\n+ rows_fetched: 16,\n+ stored_rows_after: 16,\n+ exhausted: true,\n+ coverage_status: \"exhausted_below_target\",\n+ },\n+ {\n+ i_status: -2,\n+ rows_fetched: 6,\n+ stored_rows_after: 6,\n+ exhausted: true,\n+ coverage_status: \"exhausted_below_target\",\n+ },\n+ ],\n+ storedContextByStatus: [\n+ {\n+ reply_email_i_status: 1,\n+ reply_email_i_status_label: \"interested\",\n+ fetched_reply_rows: 5,\n+ hydrated_reply_body_rows: 5,\n+ },\n+ {\n+ reply_email_i_status: -1,\n+ reply_email_i_status_label: \"not_interested\",\n+ fetched_reply_rows: 16,\n+ hydrated_reply_body_rows: 16,\n+ },\n+ {\n+ reply_email_i_status: -2,\n+ reply_email_i_status_label: \"wrong_person\",\n+ fetched_reply_rows: 6,\n+ hydrated_reply_body_rows: 6,\n+ },\n+ ],\n+ hydrationState: [\n+ { i_status: 1, latest_of_thread: true, exhausted: true },\n+ { i_status: -1, latest_of_thread: true, exhausted: true },\n+ { i_status: -2, latest_of_thread: true, exhausted: true },\n+ ],\n+});\n+\n+assert.equal(coverageSummary.aggregate_reply_count, 33);\n+assert.equal(coverageSummary.hydrated_reply_count, 27);\n+assert.equal(coverageSummary.fetched_reply_count, 27);\n+assert.equal(coverageSummary.coverage_gap_count, 6);\n+assert.deepEqual(coverageSummary.coverage_scope.selected_statuses, [1, -1, -2]);\n+assert.equal(coverageSummary.coverage_scope.ooo_status_excluded, true);\n+assert.equal(coverageSummary.coverage_scope.latest_of_thread, true);\n+assert.equal(coverageSummary.all_selected_status_buckets_exhausted, true);\n+assert.equal(\n+ coverageSummary.coverage_state,\n+ \"selected_status_buckets_exhausted_with_aggregate_gap\",\n+);\n+assert.deepEqual(\n+ coverageSummary.by_status.map((row) => ({\n+ status: row.i_status,\n+ fetched: row.fetched_reply_count,\n+ hydrated: row.hydrated_reply_count,\n+ exhausted: row.exhausted,\n+ })),\n+ [\n+ { status: 1, fetched: 5, hydrated: 5, exhausted: true },\n+ { status: -1, fetched: 16, hydrated: 16, exhausted: true },\n+ { status: -2, fetched: 6, hydrated: 6, exhausted: true },\n+ ],\n+);\n+assert.match(\n+ coverageSummary.coverage_explanation,\n+ /campaign aggregate reports 33 unique human replies/i,\n+);\n+assert.match(\n+ coverageSummary.coverage_explanation,\n+ /27 stored reply-email rows have hydrated bodies/i,\n+);\n+assert.match(\n+ coverageSummary.coverage_explanation,\n+ /maximum depth does not guarantee recovery/i,\n+);\n+assert.match(\n+ coverageSummary.coverage_explanation,\n+ /does not establish which cause applies/i,\n+);\n+assert.doesNotMatch(\n+ coverageSummary.coverage_explanation,\n+ /(?:hydrated|fetched) all replies/i,\n+);\n+assert.doesNotMatch(\n+ coverageSummary.coverage_explanation,\n+ /maximum depth (?:will|can) recover/i,\n+);\n+\n console.log(\"campaign analysis response tests passed\");", "status": "modified"}, {"additions": 14, "deletions": 0, "filename": "scripts/test-mcp-response-contract.mjs", "patch": "@@ -353,7 +353,14 @@ for (const term of [\n \"default `analysis_depth` is balanced\",\n \"`lead_context_backfill`\",\n \"`hydration_coverage`\",\n+ \"`reply_coverage_summary`\",\n \"`context_gap_counts`\",\n+ \"`aggregate_reply_count`\",\n+ \"`hydrated_reply_count`\",\n+ \"`coverage_gap_count`\",\n+ \"`coverage_scope`\",\n+ \"latest_of_thread=true\",\n+ \"maximum depth does not guarantee recovery\",\n \"`reply_email_context_sample`\",\n \"`reply_evidence_detail`\",\n \"redacted by default\",\n@@ -371,6 +378,13 @@ for (const term of [\n \"fetch_result\",\n \"lead_context_backfill\",\n \"hydration_coverage\",\n+ \"reply_coverage_summary\",\n+ \"aggregate_reply_count\",\n+ \"hydrated_reply_count\",\n+ \"coverage_gap_count\",\n+ \"coverage_scope\",\n+ \"all_selected_status_buckets_exhausted\",\n+ \"coverage_explanation\",\n \"context_gap_counts\",\n \"reply_email_context_sample\",\n \"reply_evidence_detail\",", "status": "modified"}, {"additions": 24, "deletions": 0, "filename": "scripts/test-prompt-contracts.mjs", "patch": "@@ -164,6 +164,11 @@ const PROMOTION_GUARD_CONTRACTS = [\n patterns: [\n /low-volume leaders as candidates for validation/i,\n /campaign_variants/i,\n+ /aggregate unique human reply count/i,\n+ /selected statuses/i,\n+ /latest_of_thread/i,\n+ /aggregate-to-hydrated numeric gap/i,\n+ /maximum depth does not guarantee recovery/i,\n ],\n },\n {\n@@ -172,6 +177,22 @@ const PROMOTION_GUARD_CONTRACTS = [\n /reply_email_context/i,\n /different product, industry, compliance domain, or topic/i,\n /Do not generate generic rewrites/i,\n+ /aggregate unique human reply count/i,\n+ /OOO status `0` was excluded/i,\n+ /latest_of_thread/i,\n+ /aggregate-to-hydrated numeric gap/i,\n+ /maximum depth does not guarantee recovery/i,\n+ /Do not assert which cause applies without evidence/i,\n+ ],\n+ },\n+ {\n+ path: \"skills/sendlens-analyst/SKILL.md\",\n+ patterns: [\n+ /reply_coverage_summary/i,\n+ /aggregate unique human reply count/i,\n+ /OOO exclusion/i,\n+ /latest_of_thread/i,\n+ /per-status fetched\\/hydrated counts/i,\n ],\n },\n {\n@@ -214,6 +235,9 @@ const PROMOTION_GUARD_CONTRACTS = [\n /irrelevant copy, wrong industry, wrong compliance domain/i,\n /setup\\/template-resolution risk/i,\n /wrong-template or wrong-topic complaint replies/i,\n+ /aggregate unique human reply count/i,\n+ /aggregate-to-hydrated gap/i,\n+ /maximum depth/i,\n ],\n },\n {", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "skills/sendlens-analyst/SKILL.md", "patch": "@@ -22,7 +22,7 @@ Diagnose the workspace or campaign, establish what the evidence supports, and or\n 2. **Start with exact evidence.** Use `workspace_snapshot` for broad or ambiguous requests. Use `refresh_status` only for readiness or freshness questions, and call `refresh_data` only when the user explicitly requests fresh data or changes workspace context.\n 3. **Choose the narrowest evidence lane.** Use `analysis_starters` before custom `analyze_data`. Use `search_catalog` or `list_columns` when the schema is uncertain. Read [references/schema-and-joins.md](references/schema-and-joins.md) before custom SQL or cross-surface joins.\n 4. **Diagnose constraints in order.** Check evidence readiness, volume and runway, sender and deliverability health, reply quality, ICP/lead quality, and copy or sequence mechanics. Read [references/workspace-and-performance.md](references/workspace-and-performance.md) for workspace, campaign, step, variant, runway, or deliverability work.\n-5. **Load one campaign for depth.** Call `load_campaign_data` before deep copy, reply, ICP, launch, or campaign work. Call `prepare_campaign_analysis` when fetched reply wording could change working/not-working, scale/kill, copy, ICP, or client-safe recommendations.\n+5. **Load one campaign for depth.** Call `load_campaign_data` before deep copy, reply, ICP, launch, or campaign work. Call `prepare_campaign_analysis` when fetched reply wording could change working/not-working, scale/kill, copy, ICP, or client-safe recommendations. After every preparation call, use `reply_coverage_summary` to report the aggregate unique human reply count separately from selected-status hydration, including OOO exclusion, `latest_of_thread`, per-status fetched/hydrated counts, exhaustion, the numeric gap, and the neutral scope explanation.\n 6. **Connect evidence to message and audience.** Read [references/replies-icp-and-copy.md](references/replies-icp-and-copy.md) before interpreting reply language, payload fields, intended templates, reconstructed outbound, or personalization.\n \n Read [references/evidence-and-metrics.md](references/evidence-and-metrics.md) before making diagnostic, winner, scale, ICP, copy, campaign, or client-safe claims.", "status": "modified"}, {"additions": 16, "deletions": 0, "filename": "skills/sendlens-analyst/references/replies-icp-and-copy.md", "patch": "@@ -10,6 +10,22 @@\n \n Quote or characterize wording only from hydrated `reply_body_text` or `reply_content_preview`. If bodies are not hydrated, describe outcomes rather than inventing sentiment.\n \n+### Required Hydration Coverage Report\n+\n+After `prepare_campaign_analysis`, always use `reply_coverage_summary` and report:\n+\n+1. the aggregate unique human reply count from `campaign_overview.reply_count_unique`;\n+2. the selected List Email statuses and whether OOO status `0` was excluded;\n+3. the `latest_of_thread` setting;\n+4. fetched and hydrated reply-body counts by status;\n+5. per-status and overall selected-bucket exhaustion state;\n+6. the explicit aggregate-to-hydrated numeric gap; and\n+7. the neutral coverage explanation.\n+\n+Do not collapse the two surfaces into an unqualified “hydrated X of Y.” Hydrated rows are exact body evidence for the selected List Email status/latest-thread surface. The campaign aggregate is a separate exact aggregate and may not describe the same row population.\n+\n+Exhausted selected status buckets mean the queried buckets exposed no further rows at that time. They do not prove every reply represented by the campaign aggregate has a hydrated body. A remaining gap can reflect unselected or unclassified provider statuses, `latest_of_thread` behavior, historical/provider-retention differences, or campaign-aggregate versus List Email semantics. Do not assert which cause applies without evidence. Once selected buckets are exhausted, maximum depth does not guarantee recovery of the gap.\n+\n ## ICP And Payload Evidence\n \n - Use exact campaign aggregates for the baseline and sampled lead/payload evidence for hypotheses.", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "skills/sendlens-analyst/references/workspace-and-performance.md", "patch": "@@ -28,6 +28,8 @@ Do not blame copy before checking available sender and deliverability evidence.\n - Use `campaign_variants` to connect a metric back to the intended subject and body.\n - State whether the ranking basis is unique reply rate, opportunity rate, exact reply outcomes, or sampled evidence.\n - Treat low-volume leaders as candidates for validation, not winners.\n+- Before working/not-working, winner, scale, or kill claims, keep the aggregate unique human reply count from `campaign_overview.reply_count_unique` separate from selected List Email hydration. Report selected statuses, OOO exclusion, `latest_of_thread`, fetched/hydrated counts by status, exhaustion, and the aggregate-to-hydrated numeric gap from `reply_coverage_summary`.\n+- Exhausted selected status buckets do not prove complete aggregate reply hydration. Maximum depth does not guarantee recovery of a remaining gap; preserve the tool's neutral possible-cause explanation instead of choosing a cause without evidence.\n \n ## Runway And Capacity\n ", "status": "modified"}], "message": "fix(reply-coverage): separate aggregate and hydrated counts", "sha": "122cfd4fd25506aae11d9db03870fb7d59d61b31"}], "post_review_commits": ["00d510394b1c48221551c233ffcce1e1cf169d36", "79099e9feb3de5c9b0457617e70c57ffe6460c43"], "pr_author": "orchidautomation", "pr_title": "fix(reply-coverage): separate aggregate and hydrated counts", "repo_name": "orchidautomation/sendlens-plugin"}, "repo": "orchidautomation/sendlens-plugin", "snapshot": "snapshots/04b0e580cb9980626226c71703b578a52f387912bf1a28a7cf786ccd66bbbc5f.pack", "split": "rl", "task_id": "4ab6f7c746b697bf6504821f25e0d4aa21a99a9eab91fc4399c000bb2f6cc5d7"} {"base_sha": "ab5a6173255b7da0060c8b9926b06c533118982d", "cohort": null, "context": {"canonical_pr_url": "https://github.com/komi-store/komi-store/pull/584", "id": "4c617d7d6ea05c2c1adc5ab1ac2a3e9d23022a74a64a53c86c3e545eec3302c7", "preparation_mode": "source-only", "snapshot": {"base_ref": "ab5a6173255b7da0060c8b9926b06c533118982d", "base_sha": "ab5a6173255b7da0060c8b9926b06c533118982d", "body": "", "head_ref": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89", "head_sha": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89", "name": "komi-store", "number": 584, "owner": "komi-store", "pr_url": "https://github.com/komi-store/komi-store/pull/584", "title": ""}}, "head_sha": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89", "metadata": {"group_id": "5399060ac05b2b5919487531c5f3fd146d87bfac32a5f20104bb33b0b05d4d28", "snapshot": {"base_sha": "ab5a6173255b7da0060c8b9926b06c533118982d", "external_requirements": [], "head_sha": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89", "objects": 1577, "objects_sha256": "d710e00b5c8e252674eeb20578be35c47aa51561cb5395d2b48e8b3439b17dec", "patch_sha256": "e4b19b33f181a28bbbf1af3a67f59cf1a91dc63221b2db53b096440d92bd3d37"}}, "pr_number": 584, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "performance", "commit_sha": "10e2204b85c9", "description": "Home repository mapping repeatedly fetched the current profile through a suspending cache/DataStore lookup, adding unnecessary work on each load or pagination; ownership badges on already-loaded cards also did not update after login, logout, or account switching.", "file_path": "feature/home/presentation/src/commonMain/kotlin/zed/rainxch/home/presentation/HomeViewModel.kt"}, {"action_id": "A2", "action_type": "fix", "category": "performance", "commit_sha": "10e2204b85c9", "description": "Search and explore result mapping repeatedly fetched the current profile for ownership checks, and badges on existing results did not react to login, logout, or account switching.", "file_path": "feature/search/presentation/src/commonMain/kotlin/zed/rainxch/search/presentation/SearchViewModel.kt"}, {"action_id": "A3", "action_type": "new_feature", "category": "other", "commit_sha": "2546d942de40", "description": "Repository details did not identify when the signed-in user owned the displayed repository or show the ownership badge beside its author; ownership also needed to react when the repository or signed-in user changed.", "file_path": "feature/details/presentation/src/commonMain/kotlin/zed/rainxch/details/presentation/DetailsViewModel.kt"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "bd84f0854a86", "description": "The DetailsViewModel dependency-injection factory did not supply its newly required ProfileRepository argument, preventing the updated view model from being constructed.", "file_path": "composeApp/src/commonMain/kotlin/zed/rainxch/githubstore/app/di/ViewModelsModule.kt"}, {"action_id": "A5", "action_type": "new_feature", "category": "other", "commit_sha": "af794e19486e", "description": "Starred repository items did not show an ownership badge for repositories owned by the signed-in user, including when the signed-in account changed.", "file_path": "feature/starred/presentation/src/commonMain/kotlin/zed/rainxch/starred/presentation/StarredReposViewModel.kt"}, {"action_id": "A6", "action_type": "new_feature", "category": "other", "commit_sha": "3903cf9ce9b8", "description": "Favourite repository items did not show an ownership badge for repositories owned by the signed-in user, including when the signed-in account changed.", "file_path": "feature/favourites/presentation/src/commonMain/kotlin/zed/rainxch/favourites/presentation/FavouritesViewModel.kt"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "3a02b7bec8c4", "description": "A long owner login could consume the repository card row's width and leave no room for the ownership badge.", "file_path": "core/presentation/src/commonMain/kotlin/zed/rainxch/core/presentation/components/RepositoryCard.kt"}], "commits_under_review": [{"author": "rainxchzed", "date": "2026-05-12T13:40:54Z", "files": [{"additions": 16, "deletions": 0, "filename": "core/presentation/src/commonMain/kotlin/zed/rainxch/core/presentation/components/RepositoryCard.kt", "patch": "@@ -18,6 +18,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape\n import androidx.compose.material.icons.Icons\n import androidx.compose.material.icons.automirrored.outlined.CallSplit\n import androidx.compose.material.icons.filled.CheckCircle\n+import androidx.compose.material.icons.filled.Verified\n import androidx.compose.material.icons.filled.Favorite\n import androidx.compose.material.icons.filled.OpenInBrowser\n import androidx.compose.material.icons.filled.Share\n@@ -63,6 +64,7 @@ import zed.rainxch.githubstore.core.presentation.res.home_view_details\n import zed.rainxch.githubstore.core.presentation.res.installed\n import zed.rainxch.githubstore.core.presentation.res.open_in_browser\n import zed.rainxch.githubstore.core.presentation.res.seen_badge\n+import zed.rainxch.githubstore.core.presentation.res.self_owned_badge\n import zed.rainxch.githubstore.core.presentation.res.share_repository\n import zed.rainxch.githubstore.core.presentation.res.update_available\n \n@@ -151,6 +153,10 @@ fun RepositoryCard(\n softWrap = false,\n overflow = TextOverflow.Ellipsis,\n )\n+\n+ if (discoveryRepositoryUi.isCurrentUserOwner) {\n+ OfficialBadge()\n+ }\n }\n \n Text(\n@@ -455,6 +461,16 @@ fun InstallStatusBadge(\n }\n }\n \n+@Composable\n+fun OfficialBadge(modifier: Modifier = Modifier) {\n+ Icon(\n+ imageVector = Icons.Filled.Verified,\n+ contentDescription = stringResource(Res.string.self_owned_badge),\n+ modifier = modifier.size(16.dp),\n+ tint = MaterialTheme.colorScheme.primary,\n+ )\n+}\n+\n @Composable\n fun SeenBadge(modifier: Modifier = Modifier) {\n Surface(", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/kotlin/zed/rainxch/core/presentation/model/DiscoveryRepositoryUi.kt", "patch": "@@ -6,5 +6,6 @@ data class DiscoveryRepositoryUi(\n val isFavourite: Boolean,\n val isStarred: Boolean,\n val isSeen: Boolean = false,\n+ val isCurrentUserOwner: Boolean = false,\n val repository: GithubRepoSummaryUi,\n )", "status": "modified"}], "message": "feat(presentation): OfficialBadge composable for self-owned repos", "sha": "1d75a4ffd73ce88737ab8387e89fd38205825187"}, {"author": "rainxchzed", "date": "2026-05-12T13:41:01Z", "files": [{"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-ar/strings-ar.xml", "patch": "@@ -644,6 +644,7 @@\n إعادة تعيين جميع المستودعات المشاهَدة لتظهر مجدداً في الخلاصات\n تم مسح سجل المشاهدة\n تمت المشاهدة\n+ هذا المستودع لك\n الخصوصية\n ساعد في تحسين البحث\n مشاركة بيانات الاستخدام (عمليات البحث والتثبيتات والتفاعلات) المرتبطة بمعرّف تحليلي قابل لإعادة التعيين. لا تتم مشاركة تفاصيل الحساب.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-bn/strings-bn.xml", "patch": "@@ -643,6 +643,7 @@\n সমস্ত দেখা রিপোজিটরি রিসেট করুন যাতে সেগুলো ফিডে আবার দেখা যায়\n দেখার ইতিহাস মুছে ফেলা হয়েছে\n দেখা হয়েছে\n+ এই রিপো আপনার\n গোপনীয়তা\n অনুসন্ধান উন্নত করতে সহায়তা করুন\n পুনরায় সেট করা যায় এমন একটি বিশ্লেষণ আইডির সাথে যুক্ত ব্যবহার ডেটা (অনুসন্ধান, ইনস্টল, ইন্টারঅ্যাকশন) শেয়ার করুন। অ্যাকাউন্ট বিবরণ শেয়ার করা হয় না।", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-es/strings-es.xml", "patch": "@@ -604,6 +604,7 @@\n Restablecer todos los repositorios vistos para que aparezcan de nuevo en las fuentes\n Historial de vistos borrado\n Visto\n+ Eres dueño de este repo\n Privacidad\n Ayudar a mejorar la búsqueda\n Compartir datos de uso (búsquedas, instalaciones, interacciones) asociados a un ID de análisis restablecible. No se comparten detalles de la cuenta.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-fr/strings-fr.xml", "patch": "@@ -605,6 +605,7 @@\n Réinitialiser tous les dépôts consultés pour qu'ils réapparaissent dans les flux\n Historique des consultations effacé\n Consulté\n+ Vous possédez ce dépôt\n Confidentialité\n Aider à améliorer la recherche\n Partager des données d'utilisation (recherches, installations, interactions) associées à un identifiant d'analyse réinitialisable. Aucun détail de compte n'est partagé.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-hi/strings-hi.xml", "patch": "@@ -642,6 +642,7 @@\n सभी देखे गए रिपॉजिटरी रीसेट करें ताकि वे फ़ीड में फिर से दिखें\n देखने का इतिहास साफ़ किया गया\n देखा गया\n+ यह रेपो आपका है\n गोपनीयता\n खोज को बेहतर बनाने में मदद करें\n रीसेट करने योग्य एनालिटिक्स आईडी से जुड़े उपयोग डेटा (खोज, इंस्टॉल, इंटरैक्शन) साझा करें। खाता विवरण साझा नहीं किए जाते।", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-it/strings-it.xml", "patch": "@@ -643,6 +643,7 @@\n Reimposta tutti i repository visualizzati in modo che ricompaiano nei feed\n Cronologia visualizzazioni cancellata\n Visualizzato\n+ Sei il proprietario di questo repo\n Privacy\n Aiuta a migliorare la ricerca\n Condividi dati di utilizzo (ricerche, installazioni, interazioni) associati a un ID analitico ripristinabile. Nessun dettaglio dell'account viene condiviso.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-ja/strings-ja.xml", "patch": "@@ -606,6 +606,7 @@\n すべての閲覧済みリポジトリをリセットしてフィードに再表示します\n 閲覧履歴をクリアしました\n 閲覧済み\n+ あなたが所有するリポジトリ\n プライバシー\n 検索の改善に協力\n リセット可能な分析 ID に関連付けられた使用データ(検索、インストール、操作)を共有します。アカウント情報は共有されません。", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-ko/strings-ko.xml", "patch": "@@ -641,6 +641,7 @@\n 모든 조회 기록을 초기화하여 피드에 다시 표시합니다\n 조회 기록이 삭제되었습니다\n 확인함\n+ 내가 소유한 저장소\n 개인 정보 보호\n 검색 개선에 도움 주기\n 재설정 가능한 분석 ID에 연결된 사용 데이터(검색, 설치, 상호작용)를 공유합니다. 계정 정보는 공유되지 않습니다.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-pl/strings-pl.xml", "patch": "@@ -607,6 +607,7 @@\n Zresetuj wszystkie przeglądane repozytoria, aby ponownie pojawiły się w kanałach\n Historia przeglądania wyczyszczona\n Przeglądane\n+ Jesteś właścicielem tego repo\n Prywatność\n Pomóż ulepszyć wyszukiwanie\n Udostępniaj dane o użyciu (wyszukiwania, instalacje, interakcje) powiązane z resetowalnym identyfikatorem analitycznym. Żadne dane konta nie są udostępniane.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-ru/strings-ru.xml", "patch": "@@ -607,6 +607,7 @@\n Сбросить все просмотренные репозитории, чтобы они снова появились в лентах\n История просмотров очищена\n Просмотрено\n+ Ваш репозиторий\n Конфиденциальность\n Помочь улучшить поиск\n Отправлять данные об использовании (поиски, установки, взаимодействия), связанные со сбрасываемым идентификатором аналитики. Данные учётной записи не передаются.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-tr/strings-tr.xml", "patch": "@@ -641,6 +641,7 @@\n Tüm görüntülenen depoları sıfırlayarak akışlarda tekrar görünmelerini sağlayın\n Görüntüleme geçmişi temizlendi\n Görüntülendi\n+ Bu deponun sahibisin\n Gizlilik\n Aramayı iyileştirmeye yardım et\n Sıfırlanabilir bir analiz kimliğiyle ilişkilendirilmiş kullanım verilerini (aramalar, yüklemeler, etkileşimler) paylaş. Hesap ayrıntıları paylaşılmaz.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-zh-rCN/strings-zh-rCN.xml", "patch": "@@ -607,6 +607,7 @@\n 重置所有已浏览的仓库,使其重新出现在信息流中\n 浏览记录已清除\n 已浏览\n+ 你拥有此仓库\n 隐私\n 帮助改进搜索\n 分享与可重置分析 ID 关联的使用数据(搜索、安装、交互)。不分享账户详情。", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values/strings.xml", "patch": "@@ -767,6 +767,7 @@\n Reset all seen repositories so they appear again in feeds\n Seen history cleared\n Viewed\n+ You own this repo\n \n \n Privacy", "status": "modified"}], "message": "chore(strings): self_owned_badge across 13 locales", "sha": "be4cf5644c05971df55c7266619ab18ecef5898e"}, {"author": "rainxchzed", "date": "2026-05-12T13:41:07Z", "files": [{"additions": 1, "deletions": 0, "filename": "feature/home/presentation/build.gradle.kts", "patch": "@@ -11,6 +11,7 @@ kotlin {\n implementation(projects.core.domain)\n implementation(projects.core.presentation)\n implementation(projects.feature.home.domain)\n+ implementation(projects.feature.profile.domain)\n \n implementation(libs.kotlinx.collections.immutable)\n ", "status": "modified"}, {"additions": 6, "deletions": 0, "filename": "feature/home/presentation/src/commonMain/kotlin/zed/rainxch/home/presentation/HomeViewModel.kt", "patch": "@@ -39,6 +39,7 @@ import zed.rainxch.home.domain.model.HomeCategory\n import zed.rainxch.home.domain.model.TopicCategory\n import zed.rainxch.home.domain.repository.HomeRepository\n import zed.rainxch.home.presentation.HomeEvent.*\n+import zed.rainxch.profile.domain.repository.ProfileRepository\n \n class HomeViewModel(\n private val homeRepository: HomeRepository,\n@@ -51,6 +52,7 @@ class HomeViewModel(\n private val shareManager: ShareManager,\n private val tweaksRepository: TweaksRepository,\n private val seenReposRepository: SeenReposRepository,\n+ private val profileRepository: ProfileRepository,\n ) : ViewModel() {\n private var hasLoadedInitialData = false\n private var currentJob: Job? = null\n@@ -366,6 +368,7 @@ class HomeViewModel(\n .associateBy { it.repoId }\n \n val seenIds = _state.value.seenRepoIds\n+ val currentLogin = profileRepository.getUser().first()?.username\n \n return repos.map { repo ->\n val apps = installedAppsMap[repo.id].orEmpty()\n@@ -377,6 +380,9 @@ class HomeViewModel(\n isFavourite = favourite != null,\n isStarred = starred != null,\n isSeen = repo.id in seenIds,\n+ isCurrentUserOwner =\n+ currentLogin != null &&\n+ repo.owner.login.equals(currentLogin, ignoreCase = true),\n isUpdateAvailable = apps.any { it.hasActualUpdate() },\n repository = repo.toUi(),\n )", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "feature/search/presentation/build.gradle.kts", "patch": "@@ -11,6 +11,7 @@ kotlin {\n implementation(projects.core.domain)\n implementation(projects.core.presentation)\n implementation(projects.feature.search.domain)\n+ implementation(projects.feature.profile.domain)\n \n \n implementation(libs.androidx.compose.ui.tooling.preview)", "status": "modified"}, {"additions": 10, "deletions": 0, "filename": "feature/search/presentation/src/commonMain/kotlin/zed/rainxch/search/presentation/SearchViewModel.kt", "patch": "@@ -36,6 +36,7 @@ import zed.rainxch.core.domain.utils.ShareManager\n import zed.rainxch.core.presentation.model.DiscoveryRepositoryUi\n import zed.rainxch.core.presentation.utils.toUi\n import zed.rainxch.domain.repository.SearchRepository\n+import zed.rainxch.profile.domain.repository.ProfileRepository\n import zed.rainxch.githubstore.core.presentation.res.Res\n import zed.rainxch.githubstore.core.presentation.res.failed_to_share_link\n import zed.rainxch.githubstore.core.presentation.res.link_copied_to_clipboard\n@@ -63,6 +64,7 @@ class SearchViewModel(\n private val seenReposRepository: SeenReposRepository,\n private val searchHistoryRepository: SearchHistoryRepository,\n private val telemetryRepository: TelemetryRepository,\n+ private val profileRepository: ProfileRepository,\n ) : ViewModel() {\n private var hasLoadedInitialData = false\n private var currentSearchJob: Job? = null\n@@ -349,6 +351,7 @@ class SearchViewModel(\n currentPage = paginatedRepos.nextPageIndex\n \n val seenIds = _state.value.seenRepoIds\n+ val currentLogin = profileRepository.getUser().first()?.username\n \n val newReposWithStatus =\n paginatedRepos.repos.map { repo ->\n@@ -361,6 +364,9 @@ class SearchViewModel(\n isFavourite = favourite != null,\n isStarred = starred != null,\n isSeen = repo.id in seenIds,\n+ isCurrentUserOwner =\n+ currentLogin != null &&\n+ repo.owner.login.equals(currentLogin, ignoreCase = true),\n isUpdateAvailable = apps.any { it.hasActualUpdate() },\n repository = repo.toUi(),\n )\n@@ -772,6 +778,7 @@ class SearchViewModel(\n val favoritesMap = favouritesRepository.getAllFavorites().first().associateBy { it.repoId }\n val starredMap = starredRepository.getAllStarred().first().associateBy { it.repoId }\n val seenIds = _state.value.seenRepoIds\n+ val currentLogin = profileRepository.getUser().first()?.username\n \n val existingIds = _state.value.repositories.map { it.repository.id }.toSet()\n \n@@ -784,6 +791,9 @@ class SearchViewModel(\n isFavourite = favoritesMap[repo.id] != null,\n isStarred = starredMap[repo.id] != null,\n isSeen = repo.id in seenIds,\n+ isCurrentUserOwner =\n+ currentLogin != null &&\n+ repo.owner.login.equals(currentLogin, ignoreCase = true),\n isUpdateAvailable = apps.any { it.hasActualUpdate() },\n repository = repo.toUi(),\n )", "status": "modified"}], "message": "feat(home,search): compute isCurrentUserOwner via ProfileRepository", "sha": "a8b57037a215d8768745aebeda74598e2f78ea7b"}, {"author": "rainxchzed", "date": "2026-05-12T13:41:20Z", "files": [{"additions": 2, "deletions": 1, "filename": "core/presentation/src/commonMain/composeResources/files/whatsnew/17.json", "patch": "@@ -10,7 +10,8 @@\n \"Ignore updates per app — silence the update badge for any app you don't want to update.\",\n \"Skip a specific update — dismiss a single release if it's a false-positive prompt; you'll be re-notified when a newer one lands.\",\n \"Silent install via root — Magisk, KernelSU, and APatch users can now install without Shizuku or Dhizuku.\",\n- \"Search in Starred and Favourites — quickly filter long lists by repo name, owner, description, or language.\"\n+ \"Search in Starred and Favourites — quickly filter long lists by repo name, owner, description, or language.\",\n+ \"Self-owned ✓ badge — when you're signed in, repos you own get a verified checkmark on Home and Search cards.\"\n ]\n },\n {", "status": "modified"}], "message": "chore(whatsnew): note self-owned ✓ badge", "sha": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89"}], "post_review_commits": ["10e2204b85c9274622c04df54a6a6ca19eefa7f3", "2546d942de40790963ee6166db116769557fd850", "bd84f0854a867461762f752a5e2967443ccf3ab1", "af794e19486eec2bf47e1756f6ec379b6b7cd6e3", "3903cf9ce9b89778fd67e656d35a847e69e6733b", "3a02b7bec8c4ea4037bf678094b4f975e69855e9"], "pr_author": "rainxchzed", "pr_title": "feat(e20): self-owned ✓ badge on Home + Search cards", "repo_name": "komi-store/komi-store"}, "repo": "komi-store/komi-store", "snapshot": "snapshots/5399060ac05b2b5919487531c5f3fd146d87bfac32a5f20104bb33b0b05d4d28.pack", "split": "rl", "task_id": "4c617d7d6ea05c2c1adc5ab1ac2a3e9d23022a74a64a53c86c3e545eec3302c7"} {"base_sha": "b3655bcebf233d2de986d4f1f51ac0261ea3ea7a", "cohort": null, "context": {"canonical_pr_url": "https://github.com/assistant-ui/assistant-ui/pull/4209", "id": "4d32af3446a6ec2932e55373a1d98948d704cf43a53d0c80fe97d894c9eaaec3", "preparation_mode": "source-only", "snapshot": {"base_ref": "b3655bcebf233d2de986d4f1f51ac0261ea3ea7a", "base_sha": "b3655bcebf233d2de986d4f1f51ac0261ea3ea7a", "body": "", "head_ref": "d1426fd60f134a794efc36868759d3376410818c", "head_sha": "d1426fd60f134a794efc36868759d3376410818c", "name": "assistant-ui", "number": 4209, "owner": "assistant-ui", "pr_url": "https://github.com/assistant-ui/assistant-ui/pull/4209", "title": ""}}, "head_sha": "d1426fd60f134a794efc36868759d3376410818c", "metadata": {"group_id": "182e326ff833285cedd564012b69ee289efa0d9e34abd1afa7ed433af36a2417", "snapshot": {"base_sha": "b3655bcebf233d2de986d4f1f51ac0261ea3ea7a", "external_requirements": [], "head_sha": "d1426fd60f134a794efc36868759d3376410818c", "objects": 3676, "objects_sha256": "8f4950072304dca83f2d582f7a6cce6c2265f96d2a290e761851ca79a49cd62b", "patch_sha256": "c05ddec7a19edc343ac518e0e21ed629ab80099460aba43b3a52faf7dc7be534"}}, "pr_number": 4209, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "897013ee8061", "description": "The disabled playground-chat endpoint returned a plain-text 404, inconsistent with the JSON error response used by the other gated routes.", "file_path": "apps/docs/app/api/playground-chat/route.ts"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "897013ee8061", "description": "The disabled Xulux chat endpoint returned a plain-text 404 instead of the JSON error response used by the other gated routes.", "file_path": "apps/docs/app/api/xulux/chat/route.ts"}, {"action_id": "A3", "action_type": "improvement", "category": "performance", "commit_sha": "dd150113d539", "description": "The XuluxApp dynamic import was registered even when the AI playground flag was off, creating an unnecessary chunk boundary in disabled builds.", "file_path": "apps/docs/app/(demos)/playground/page.tsx"}, {"action_id": "A4", "action_type": "fix", "category": "documentation", "commit_sha": "2fbd0d3adf11", "description": "The new AI playground environment variable was missing from .env.example, leaving its enablement value and disabled behavior undocumented.", "file_path": "apps/docs/.env.example"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "2fbd0d3adf11", "description": "When the AI flag was off, the UI Builder rendered without PlaygroundChatProvider, so its chat preview lacked a runtime context and clicking New Thread could throw an AuiProvider error.", "file_path": "apps/docs/app/(demos)/playground/page.tsx"}], "commits_under_review": [{"author": "Yonom", "date": "2026-06-02T05:05:34Z", "files": [{"additions": 204, "deletions": 180, "filename": "apps/docs/app/(demos)/playground/page.tsx", "patch": "@@ -8,6 +8,7 @@ import {\n type ReactNode,\n } from \"react\";\n import { createPortal } from \"react-dom\";\n+import dynamic from \"next/dynamic\";\n import {\n CodeIcon,\n XIcon,\n@@ -42,7 +43,11 @@ import {\n usePlaygroundState,\n type ViewportPreset,\n } from \"@/lib/playground-url-state\";\n-import { XuluxApp } from \"@/components/xulux/XuluxApp\";\n+import { isAiPlaygroundEnabled } from \"@/lib/feature-flags\";\n+\n+const XuluxApp = dynamic(() =>\n+ import(\"@/components/xulux/XuluxApp\").then((mod) => mod.XuluxApp),\n+);\n \n const VIEWPORT_PRESETS = {\n desktop: { width: \"100%\" as const, label: \"Desktop\", icon: Monitor },\n@@ -127,81 +132,79 @@ function BuilderPlayground() {\n [viewportWidth, setViewportWidth],\n );\n \n- return (\n- \n-
\n-
\n- \n-
\n-\n- \n-
\n-
\n- {(Object.keys(VIEWPORT_PRESETS) as ViewportPreset[]).map(\n- (key) => {\n- const preset = VIEWPORT_PRESETS[key];\n- const Icon = preset.icon;\n- return (\n- handlePresetChange(key)}\n- className={cn(\n- \"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors\",\n- viewportPreset === key\n- ? \"bg-foreground/10 text-foreground\"\n- : \"text-muted-foreground hover:text-foreground\",\n- )}\n- >\n- \n- {preset.label}\n- \n- );\n- },\n- )}\n- \n- {viewportWidth === \"100%\" ? \"100%\" : `${viewportWidth}px`}\n- \n-
\n+ const content = (\n+
\n+
\n+ \n+
\n \n- \n- \n+ \n+
\n+
\n+ {(Object.keys(VIEWPORT_PRESETS) as ViewportPreset[]).map((key) => {\n+ const preset = VIEWPORT_PRESETS[key];\n+ const Icon = preset.icon;\n+ return (\n handlePresetChange(key)}\n+ className={cn(\n+ \"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors\",\n+ viewportPreset === key\n+ ? \"bg-foreground/10 text-foreground\"\n+ : \"text-muted-foreground hover:text-foreground\",\n+ )}\n >\n- \n- Customize\n+ \n+ {preset.label}\n \n- \n- \n- \n- Customize\n- \n-
\n- \n-
\n- \n- \n+ );\n+ })}\n+ \n+ {viewportWidth === \"100%\" ? \"100%\" : `${viewportWidth}px`}\n+ \n+
\n \n-
\n- \n+ \n+ \n- \n- New Thread\n- \n+ \n+ Customize\n+ \n+ \n+ \n+ \n+ Customize\n+ \n+
\n+ \n+
\n+ \n+ \n \n- \n+
\n+ \n+ \n+ New Thread\n+ \n \n+ \n+\n+ {isAiPlaygroundEnabled && (\n setShowChat(!showChat)}\n@@ -215,7 +218,9 @@ function BuilderPlayground() {\n \n AI\n \n+ )}\n \n+ {isAiPlaygroundEnabled && (\n \n \n \n \n \n+ )}\n \n+ setShowCode(!showCode)}\n+ className={cn(\n+ \"flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors\",\n+ showCode\n+ ? \"bg-foreground/10 text-foreground\"\n+ : \"text-muted-foreground hover:text-foreground\",\n+ )}\n+ >\n+ {showCode ? (\n+ <>\n+ \n+ Close\n+ \n+ ) : (\n+ <>\n+ \n+ Code\n+ \n+ )}\n+ \n+\n+ setShowCode(true)}\n+ >\n setShowCode(!showCode)}\n- className={cn(\n- \"flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors\",\n- showCode\n- ? \"bg-foreground/10 text-foreground\"\n- : \"text-muted-foreground hover:text-foreground\",\n- )}\n+ className=\"bg-foreground text-background hover:bg-foreground/90 flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors\"\n >\n- {showCode ? (\n- <>\n- \n- Close\n- \n- ) : (\n- <>\n- \n- Code\n- \n- )}\n+ \n+ Create Project\n \n-\n- setShowCode(true)}\n- >\n- \n- \n- Create Project\n- \n- \n-
\n+ \n
\n+
\n \n- \n-
\n- {viewportWidth !== \"100%\" && (\n- handleResizeStart(e, \"left\")}\n- className=\"group hidden w-4 shrink-0 cursor-ew-resize items-center justify-center md:flex\"\n- >\n-
\n-
\n- )}\n-\n+ \n+
\n+ {viewportWidth !== \"100%\" && (\n handleResizeStart(e, \"left\")}\n+ className=\"group hidden w-4 shrink-0 cursor-ew-resize items-center justify-center md:flex\"\n >\n- \n+
\n+
\n+ )}\n \n- {aiRunning && !showCode && !mobileSheetOpen && (\n+ \n+ \n+\n+ {isAiPlaygroundEnabled &&\n+ aiRunning &&\n+ !showCode &&\n+ !mobileSheetOpen && (\n
\n
\n \n@@ -310,43 +319,50 @@ function BuilderPlayground() {\n
\n )}\n \n- {showCode && (\n-
\n- \n-
\n- )}\n-
\n-\n- {viewportWidth !== \"100%\" && (\n- handleResizeStart(e, \"right\")}\n- className=\"group hidden w-4 shrink-0 cursor-ew-resize items-center justify-center md:flex\"\n- >\n-
\n+ {showCode && (\n+
\n+ \n
\n )}\n
\n-
\n-
\n \n- {showChat && (\n- \n- )}\n+
\n
\n+\n+ {isAiPlaygroundEnabled && showChat && (\n+ \n+ )}\n+
\n+ );\n+\n+ return isAiPlaygroundEnabled ? (\n+ \n+ {content}\n \n+ ) : (\n+ content\n );\n }\n \n@@ -364,41 +380,49 @@ function HeaderPortal({ children }: { children: ReactNode }) {\n }\n \n export default function PlaygroundPage() {\n- const [mode, setMode] = useState<\"agent\" | \"builder\">(\"agent\");\n+ const [mode, setMode] = useState<\"agent\" | \"builder\">(\n+ isAiPlaygroundEnabled ? \"agent\" : \"builder\",\n+ );\n \n return (\n <>\n- \n-
\n- setMode(\"agent\")}\n- className={cn(\n- \"rounded px-2.5 py-1 font-medium transition-colors\",\n- mode === \"agent\"\n- ? \"bg-background text-foreground shadow-sm\"\n- : \"text-muted-foreground hover:text-foreground\",\n- )}\n- >\n- AI Builder\n- \n- setMode(\"builder\")}\n- className={cn(\n- \"rounded px-2.5 py-1 font-medium transition-colors\",\n- mode === \"builder\"\n- ? \"bg-background text-foreground shadow-sm\"\n- : \"text-muted-foreground hover:text-foreground\",\n- )}\n- >\n- UI Builder\n- \n-
\n-
\n+ {isAiPlaygroundEnabled && (\n+ \n+
\n+ setMode(\"agent\")}\n+ className={cn(\n+ \"rounded px-2.5 py-1 font-medium transition-colors\",\n+ mode === \"agent\"\n+ ? \"bg-background text-foreground shadow-sm\"\n+ : \"text-muted-foreground hover:text-foreground\",\n+ )}\n+ >\n+ AI Builder\n+ \n+ setMode(\"builder\")}\n+ className={cn(\n+ \"rounded px-2.5 py-1 font-medium transition-colors\",\n+ mode === \"builder\"\n+ ? \"bg-background text-foreground shadow-sm\"\n+ : \"text-muted-foreground hover:text-foreground\",\n+ )}\n+ >\n+ UI Builder\n+ \n+
\n+
\n+ )}\n \n
\n- {mode === \"agent\" ? : }\n+ {isAiPlaygroundEnabled && mode === \"agent\" ? (\n+ \n+ ) : (\n+ \n+ )}\n
\n \n );", "status": "modified"}, {"additions": 5, "deletions": 0, "filename": "apps/docs/app/api/playground-chat/route.ts", "patch": "@@ -1,6 +1,7 @@\n import { checkRateLimit } from \"@/lib/rate-limit\";\n import { validateGeneralChatInput } from \"@/lib/validate-input\";\n import { getModel } from \"@/lib/ai/provider\";\n+import { isAiPlaygroundEnabled } from \"@/lib/feature-flags\";\n import { frontendTools } from \"@assistant-ui/react-ai-sdk\";\n import {\n convertToModelMessages,\n@@ -135,6 +136,10 @@ When using customCSS, APPEND to any existing customCSS (from current config) rat\n `;\n \n export async function POST(req: Request) {\n+ if (!isAiPlaygroundEnabled) {\n+ return new Response(\"Not found\", { status: 404 });\n+ }\n+\n try {\n const rateLimitResponse = await checkRateLimit(req);\n if (rateLimitResponse) return rateLimitResponse;", "status": "modified"}, {"additions": 5, "deletions": 0, "filename": "apps/docs/app/api/xulux/chat/route.ts", "patch": "@@ -4,6 +4,7 @@ import { injectQuoteContext } from \"@assistant-ui/react-ai-sdk\";\n import { checkRateLimit } from \"@/lib/rate-limit\";\n import { validateDocChatInput } from \"@/lib/validate-input\";\n import { getModel, openai } from \"@/lib/ai/provider\";\n+import { isAiPlaygroundEnabled } from \"@/lib/feature-flags\";\n import { prismAISDK } from \"@aui-x/prism\";\n import { withTracing } from \"@posthog/ai\";\n import {\n@@ -244,6 +245,10 @@ Use inline code (\\`backticks\\`) for:\n `;\n \n export async function POST(req: Request): Promise {\n+ if (!isAiPlaygroundEnabled) {\n+ return new Response(\"Not found\", { status: 404 });\n+ }\n+\n try {\n const rateLimitResponse = await checkRateLimit(req);\n if (rateLimitResponse) return rateLimitResponse;", "status": "modified"}, {"additions": 5, "deletions": 0, "filename": "apps/docs/app/api/xulux/download/route.ts", "patch": "@@ -1,11 +1,16 @@\n import { Readable } from \"node:stream\";\n import { NextResponse } from \"next/server\";\n import { checkRateLimit } from \"@/lib/rate-limit\";\n+import { isAiPlaygroundEnabled } from \"@/lib/feature-flags\";\n import { exportWorkspaceArchive } from \"../blaxel-sandbox\";\n \n export const maxDuration = 120;\n \n export async function POST(request: Request) {\n+ if (!isAiPlaygroundEnabled) {\n+ return NextResponse.json({ error: \"Not found.\" }, { status: 404 });\n+ }\n+\n let cleanup: (() => Promise) | undefined;\n const runCleanup = () => {\n const current = cleanup;", "status": "modified"}, {"additions": 5, "deletions": 0, "filename": "apps/docs/app/api/xulux/examples/route.ts", "patch": "@@ -1,6 +1,11 @@\n import { NextResponse } from \"next/server\";\n+import { isAiPlaygroundEnabled } from \"@/lib/feature-flags\";\n import { getXuluxExamplesCatalog } from \"@/lib/xulux/examples-catalog\";\n \n export function GET() {\n+ if (!isAiPlaygroundEnabled) {\n+ return NextResponse.json({ error: \"Not found.\" }, { status: 404 });\n+ }\n+\n return NextResponse.json(getXuluxExamplesCatalog());\n }", "status": "modified"}, {"additions": 3, "deletions": 0, "filename": "apps/docs/app/xulux-preview/[slug]/page.tsx", "patch": "@@ -1,12 +1,15 @@\n import { notFound } from \"next/navigation\";\n import { ExamplePreview } from \"@/components/xulux/examples/ExamplePreview\";\n+import { isAiPlaygroundEnabled } from \"@/lib/feature-flags\";\n import { getXuluxExamplePreview } from \"@/lib/xulux/examples-catalog\";\n \n export default async function Page({\n params,\n }: {\n params: Promise<{ slug: string }>;\n }) {\n+ if (!isAiPlaygroundEnabled) notFound();\n+\n const { slug } = await params;\n const preview = getXuluxExamplePreview(slug);\n if (!preview) notFound();", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "apps/docs/lib/feature-flags.ts", "patch": "@@ -0,0 +1,2 @@\n+export const isAiPlaygroundEnabled =\n+ process.env.NEXT_PUBLIC_AUI_AI_PLAYGROUND_ENABLED === \"1\";", "status": "added"}], "message": "docs: gate AI playground behind feature flag", "sha": "d1426fd60f134a794efc36868759d3376410818c"}], "post_review_commits": ["897013ee8061296bac1d50cdadc660fb0d75ae69", "dd150113d539fb25577fb04505bf162e933f4258", "2fbd0d3adf112cf71220e2139ec3ffa02be87e86"], "pr_author": "Yonom", "pr_title": "docs: gate AI playground behind feature flag", "repo_name": "assistant-ui/assistant-ui"}, "repo": "assistant-ui/assistant-ui", "snapshot": "snapshots/182e326ff833285cedd564012b69ee289efa0d9e34abd1afa7ed433af36a2417.pack", "split": "rl", "task_id": "4d32af3446a6ec2932e55373a1d98948d704cf43a53d0c80fe97d894c9eaaec3"} {"base_sha": "e59d312956f3b7da430942cada8b9b0535ec8760", "cohort": null, "context": {"canonical_pr_url": "https://github.com/Tixtac-Project/tixtac/pull/96", "id": "4d37ef53e293dfde351b752c1634ba21b23b11e7c4436f4029f4ca92acb0dab3", "preparation_mode": "source-only", "snapshot": {"base_ref": "e59d312956f3b7da430942cada8b9b0535ec8760", "base_sha": "e59d312956f3b7da430942cada8b9b0535ec8760", "body": "", "head_ref": "e099a809414250de49d808ad9f24c916e46cc4a2", "head_sha": "e099a809414250de49d808ad9f24c916e46cc4a2", "name": "tixtac", "number": 96, "owner": "Tixtac-Project", "pr_url": "https://github.com/Tixtac-Project/tixtac/pull/96", "title": ""}}, "head_sha": "e099a809414250de49d808ad9f24c916e46cc4a2", "metadata": {"group_id": "0a51a1eea200daab524a0d5592847a1e3ef89714131e97f9b2bc9f22aa9796d5", "snapshot": {"base_sha": "e59d312956f3b7da430942cada8b9b0535ec8760", "external_requirements": [], "head_sha": "e099a809414250de49d808ad9f24c916e46cc4a2", "objects": 501, "objects_sha256": "343f97459741c8203adb21fdba54841068bd66f7e77fcaf3d8281d8bbaa40b8b", "patch_sha256": "800a211c906fbc0c9adaed221cd9c2cd3e68e914a958bb9eca86721af947dcb9"}}, "pr_number": 96, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "51fbb5e78d43", "description": "When a user had already bought the maximum allowed tickets, the page passed a remaining limit of zero to the cart store, which interpreted zero as unlimited. The user could then add more tickets despite having reached the event limit.", "file_path": "src/lib/stores/cart-store.svelte.ts"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "51fbb5e78d43", "description": "The page recreated the cart store whenever ticket-limit data changed, discarding the user's existing seat and quantity selections. Updating the limits on the existing store preserves cart state.", "file_path": "src/routes/(customer)/events/[id]/shows/[showId]/seats/+page.svelte"}], "commits_under_review": [{"author": "dungxnd", "date": "2026-04-25T14:49:08Z", "files": [{"additions": 11, "deletions": 2, "filename": "src/lib/components/seat-map/SummaryBar.svelte", "patch": "@@ -19,6 +19,7 @@\n store: SeatSelectionStore;\n onCheckout: () => void;\n maxTickets: number;\n+ boughtCount?: number;\n /** Whether the event has multiple shows (always show per-show grouping) */\n multiShowEvent?: boolean;\n isLoading?: boolean;\n@@ -28,10 +29,14 @@\n store,\n onCheckout,\n maxTickets,\n+ boughtCount = 0,\n multiShowEvent = false,\n isLoading = false,\n }: Props = $props();\n \n+ /** Effective remaining = max - bought (non-negative) */\n+ let effectiveRemaining = $derived(maxTickets > 0 ? Math.max(0, maxTickets - boughtCount) : -1);\n+\n let expanded = $state(false);\n let hasSelection = $derived(store.totalCount > 0);\n \n@@ -322,7 +327,11 @@\n \n {store.totalCount} vé đã chọn\n {#if maxTickets > 0}\n- / tối đa {maxTickets}\n+ {#if boughtCount > 0}\n+ / còn {effectiveRemaining}\n+ {:else}\n+ / tối đa {maxTickets}\n+ {/if}\n {/if}\n \n

\n@@ -350,7 +359,7 @@\n type=\"button\"\n class=\"btn-primary-gradient flex shrink-0 items-center gap-2 px-6 py-3 text-sm font-bold disabled:cursor-not-allowed disabled:opacity-70\"\n onclick={onCheckout}\n- disabled={isLoading || (store.totalCount > maxTickets && maxTickets > 0)}\n+ disabled={isLoading || (effectiveRemaining >= 0 && store.totalCount > effectiveRemaining)}\n >\n {#if isLoading}\n ", "status": "modified"}, {"additions": 29, "deletions": 1, "filename": "src/lib/server/services/event.service.ts", "patch": "@@ -1,5 +1,13 @@\n import { db } from '$lib/server/db';\n-import { categories, events, eventShows, seats, seatSections } from '$lib/server/db/schema';\n+import {\n+ categories,\n+ events,\n+ eventShows,\n+ orderItems,\n+ orders,\n+ seats,\n+ seatSections,\n+} from '$lib/server/db/schema';\n import { Errors, throwError } from '$lib/server/errors';\n import {\n createBasicInfoSchema,\n@@ -119,6 +127,25 @@ export const eventService = {\n async getEventDetail(rawEventId: string | number, role?: string, userId?: number) {\n const eventId = validateInput(eventIdSchema, rawEventId);\n \n+ // 0. Count already-bought (paid) tickets for this user+event\n+ let boughtCount = 0;\n+ if (userId) {\n+ const [bought] = await db\n+ .select({ count: sql`count(*)` })\n+ .from(orders)\n+ .innerJoin(orderItems, eq(orders.id, orderItems.orderId))\n+ .innerJoin(seats, eq(seats.id, orderItems.seatId))\n+ .innerJoin(eventShows, eq(eventShows.id, seats.showId))\n+ .where(\n+ and(\n+ eq(orders.userId, userId),\n+ eq(orders.status, 'paid'),\n+ eq(eventShows.eventId, eventId),\n+ ),\n+ );\n+ boughtCount = Number(bought?.count ?? 0);\n+ }\n+\n // 1. Get event basic info with category\n const [eventRow] = await db\n .select({\n@@ -227,6 +254,7 @@ export const eventService = {\n \n return {\n id: event.id,\n+ bought_count: boughtCount,\n category_id: event.categoryId,\n category_name: event.categoryName,\n category_slug: event.categorySlug,", "status": "modified"}, {"additions": 2, "deletions": 1, "filename": "src/routes/(customer)/events/[id]/shows/[showId]/seats/+page.server.ts", "patch": "@@ -1,7 +1,7 @@\n import { eventService } from '$lib/server/services/event.service';\n import { seatService } from '$lib/server/services/seat.service';\n-import { error, redirect } from '@sveltejs/kit';\n import { handlePageError } from '$lib/server/utils/page-error';\n+import { error, redirect } from '@sveltejs/kit';\n import type { PageServerLoad } from './$types';\n \n export const load: PageServerLoad = async ({ params, locals }) => {\n@@ -45,6 +45,7 @@ export const load: PageServerLoad = async ({ params, locals }) => {\n title: event.title,\n venue: event.venue,\n max_tickets_per_user: event.max_tickets_per_user,\n+ bought_count: event.bought_count,\n map_config: event.map_config,\n stage_layout: event.stage_layout,\n },", "status": "modified"}, {"additions": 12, "deletions": 4, "filename": "src/routes/(customer)/events/[id]/shows/[showId]/seats/+page.svelte", "patch": "@@ -27,6 +27,7 @@\n title: string;\n venue: string;\n max_tickets_per_user: number;\n+ bought_count: number;\n map_config: MapConfig;\n stage_layout: StageElement[];\n };\n@@ -59,9 +60,15 @@\n allShows.find((s: ShowInfo) => s.id === currentShowId) ?? data.show,\n );\n \n- // ── Store ──\n- const getMaxTicketsPerUser = () => data.event.max_tickets_per_user;\n- let store = createSeatSelectionStore(getMaxTicketsPerUser());\n+ // ── Store: effective max = event limit minus already-bought tickets ──\n+ let store = $state(createSeatSelectionStore(0));\n+\n+ $effect(() => {\n+ const limit = data.event.max_tickets_per_user;\n+ const bought = data.event.bought_count;\n+ const max = limit > 0 ? Math.max(0, limit - bought) : 0;\n+ store = createSeatSelectionStore(max);\n+ });\n \n // Sync from server data whenever the route's event/show changes\n // (handles initial load AND SvelteKit reusing this page for a different route)\n@@ -426,7 +433,8 @@\n 1}\n isLoading={isSubmitting}\n />", "status": "modified"}], "message": "feat(cart): add bought ticket count to manage effective ticket limits", "sha": "c94b3edb97a5aa422e6bbb1afcd0683fe5361ad0"}, {"author": "dungxnd", "date": "2026-04-25T14:51:31Z", "files": [{"additions": 1, "deletions": 1, "filename": "src/lib/server/events/event-bus.ts", "patch": "@@ -5,5 +5,5 @@ export const eventBus = new EventEmitter();\n eventBus.setMaxListeners(1000);\n \n export const SSE_EVENTS = {\n- SEAT_UPDATE: (showId: number | string) => `show:${showId}:seats`\n+ SEAT_UPDATE: (showId: number | string) => `show:${showId}:seats`,\n };", "status": "modified"}, {"additions": 3, "deletions": 4, "filename": "src/routes/api/events/[id]/shows/[showId]/seats/stream/+server.ts", "patch": "@@ -71,7 +71,7 @@ export const GET = apiHandler(async (event) => {\n },\n cancel() {\n cleanup();\n- }\n+ },\n });\n \n function cleanup() {\n@@ -87,7 +87,6 @@ export const GET = apiHandler(async (event) => {\n } catch (error) {\n console.log(error);\n }\n-\n }\n \n request.signal.addEventListener('abort', cleanup, { once: true });\n@@ -96,7 +95,7 @@ export const GET = apiHandler(async (event) => {\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n- 'Connection': 'keep-alive'\n- }\n+ Connection: 'keep-alive',\n+ },\n });\n });", "status": "modified"}, {"additions": 4, "deletions": 4, "filename": "src/routes/api/test-sse/+server.ts", "patch": "@@ -3,11 +3,11 @@ import { json } from '@sveltejs/kit';\n \n export const GET = async () => {\n console.log('[Test API] Đang bắn sự kiện từ Server...');\n- \n- eventBus.emit(SSE_EVENTS.SEAT_UPDATE(10), { \n- seatId: 888, \n+\n+ eventBus.emit(SSE_EVENTS.SEAT_UPDATE(10), {\n+ seatId: 888,\n status: 'locked',\n- message: 'Chào bạn, mình bắn tin từ chính Server đây!' \n+ message: 'Chào bạn, mình bắn tin từ chính Server đây!',\n });\n \n return json({ message: 'Đã bắn tin nhắn thành công vào EventBus của Server!' });", "status": "modified"}], "message": "fix: format code correctly", "sha": "e099a809414250de49d808ad9f24c916e46cc4a2"}], "post_review_commits": ["51fbb5e78d43cc6b121e7d81fb538ba1cb8a69e3"], "pr_author": "dungxnd", "pr_title": "feat(cart): add bought ticket count to manage effective ticket limits", "repo_name": "Tixtac-Project/tixtac"}, "repo": "Tixtac-Project/tixtac", "snapshot": "snapshots/0a51a1eea200daab524a0d5592847a1e3ef89714131e97f9b2bc9f22aa9796d5.pack", "split": "rl", "task_id": "4d37ef53e293dfde351b752c1634ba21b23b11e7c4436f4029f4ca92acb0dab3"} {"base_sha": "a2260eb576e6c50389873f798aa9d121014e697a", "cohort": null, "context": {"canonical_pr_url": "https://github.com/Hiroki-org/Audicle/pull/626", "id": "4e2d13176f1cee9180f3c539456cefa732aca1649ab10e30684e90a7b8e3cca5", "preparation_mode": "source-only", "snapshot": {"base_ref": "a2260eb576e6c50389873f798aa9d121014e697a", "base_sha": "a2260eb576e6c50389873f798aa9d121014e697a", "body": "", "head_ref": "30d47d05ca8f10a761752b8a96ec11c6668c6e54", "head_sha": "30d47d05ca8f10a761752b8a96ec11c6668c6e54", "name": "Audicle", "number": 626, "owner": "Hiroki-org", "pr_url": "https://github.com/Hiroki-org/Audicle/pull/626", "title": ""}}, "head_sha": "30d47d05ca8f10a761752b8a96ec11c6668c6e54", "metadata": {"group_id": "a5c2873b144fca9bd53dab2f7217701f315a3f6d84ca85c8cc1002fbffff6670", "snapshot": {"base_sha": "a2260eb576e6c50389873f798aa9d121014e697a", "external_requirements": [], "head_sha": "30d47d05ca8f10a761752b8a96ec11c6668c6e54", "objects": 484, "objects_sha256": "7f29266b44507754661fe9cffda3881458615d8d0574daecbd47d09c3b85b216", "patch_sha256": "10cdd1c921a59c6d6612ef23e44f53d68b15292a9311632c1b73b827f7c43a00"}}, "pr_number": 626, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "other", "commit_sha": "5192f21d57cd", "description": "The recordArticleStats test asserted serialized JSON substrings, making it depend on property order rather than the request body's actual values. This was changed to parse the body and assert its fields, but the change was reverted in a later commit.", "file_path": "packages/web-app-vercel/lib/__tests__/articleStats.test.ts"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "5192f21d57cd", "description": "The retry test restored real timers only at the end of its body, so an earlier failure could leave fake timers active for subsequent tests. Cleanup was moved to afterEach, but that change was reverted in a later commit.", "file_path": "packages/web-app-vercel/lib/__tests__/articleStats.test.ts"}, {"action_id": "A3", "action_type": "fix", "category": "documentation", "commit_sha": "5192f21d57cd", "description": "The non-network-error test title incorrectly said the error was thrown; the behavior described in review context is that retries stop immediately and the failure is logged. The corrected title was reverted in a later commit.", "file_path": "packages/web-app-vercel/lib/__tests__/articleStats.test.ts"}], "commits_under_review": [{"author": "google-labs-jules[bot]", "date": "2026-03-31T05:41:49Z", "files": [{"additions": 467, "deletions": 186, "filename": "packages/web-app-vercel/lib/__tests__/articleStats.test.ts", "patch": "@@ -1,211 +1,492 @@\n-import { calculateCacheStats } from '../articleStats';\n-import { Chunk } from '@/types/api';\n-import { getArticleChunks } from '../indexedDB';\n+import { calculateCacheStats, recordArticleStats } from \"../articleStats\";\n+import { Chunk } from \"@/types/api\";\n+import { getArticleChunks } from \"../indexedDB\";\n+\n+import { logger } from \"../logger\";\n+jest.mock(\"../logger\", () => ({\n+ logger: {\n+ info: jest.fn(),\n+ warn: jest.fn(),\n+ error: jest.fn(),\n+ },\n+}));\n \n /**\n * articleStats.test.ts\n * calculateCacheStats 関数の単体テスト\n */\n \n // getArticleChunks をモック化\n-jest.mock('../indexedDB', () => ({\n- getArticleChunks: jest.fn(),\n+jest.mock(\"../indexedDB\", () => ({\n+ getArticleChunks: jest.fn(),\n }));\n \n-describe('calculateCacheStats', () => {\n- beforeEach(() => {\n- // 各テスト前にモックをリセット\n- jest.resetAllMocks();\n+describe(\"calculateCacheStats\", () => {\n+ beforeEach(() => {\n+ // 各テスト前にモックをリセット\n+ jest.resetAllMocks();\n+ });\n+\n+ /**\n+ * テストケース 1: 全ヒット\n+ * すべてのチャンクがキャッシュ済み → isFullyCached: true\n+ */\n+ it(\"should return isFullyCached: true when all chunks are cached\", async () => {\n+ const testUrl = \"https://example.com/article1\";\n+ const chunks: Chunk[] = [\n+ { id: \"1\", text: \"chunk1\", cleanedText: \"chunk1\", type: \"text\" },\n+ { id: \"2\", text: \"chunk2\", cleanedText: \"chunk2\", type: \"text\" },\n+ { id: \"3\", text: \"chunk3\", cleanedText: \"chunk3\", type: \"text\" },\n+ ];\n+\n+ // モック設定:全てのチャンクが存在\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([\n+ {\n+ chunkIndex: 0,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk1\",\n+ },\n+ {\n+ chunkIndex: 1,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk2\",\n+ },\n+ {\n+ chunkIndex: 2,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk3\",\n+ },\n+ ]);\n+\n+ const result = await calculateCacheStats(testUrl, chunks);\n+\n+ expect(result).toEqual({\n+ cacheHits: 3,\n+ cacheMisses: 0,\n+ isFullyCached: true,\n+ });\n+ });\n+\n+ /**\n+ * テストケース 2: 一部ヒット\n+ * 一部のチャンクのみキャッシュ済み → isFullyCached: false\n+ */\n+ it(\"should return isFullyCached: false when only some chunks are cached\", async () => {\n+ const testUrl = \"https://example.com/article2\";\n+ const chunks: Chunk[] = [\n+ { id: \"1\", text: \"chunk1\", cleanedText: \"chunk1\", type: \"text\" },\n+ { id: \"2\", text: \"chunk2\", cleanedText: \"chunk2\", type: \"text\" },\n+ { id: \"3\", text: \"chunk3\", cleanedText: \"chunk3\", type: \"text\" },\n+ { id: \"4\", text: \"chunk4\", cleanedText: \"chunk4\", type: \"text\" },\n+ ];\n+\n+ // モック設定:インデックス 0, 2 のみ存在\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([\n+ {\n+ chunkIndex: 0,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk1\",\n+ },\n+ {\n+ chunkIndex: 2,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk3\",\n+ },\n+ ]);\n+\n+ const result = await calculateCacheStats(testUrl, chunks);\n+\n+ expect(result).toEqual({\n+ cacheHits: 2,\n+ cacheMisses: 2,\n+ isFullyCached: false,\n });\n+ });\n+\n+ /**\n+ * テストケース 3: キャッシュなし\n+ * キャッシュが空 → cacheHits: 0\n+ */\n+ it(\"should return cacheHits: 0 when no chunks are cached\", async () => {\n+ const testUrl = \"https://example.com/article3\";\n+ const chunks: Chunk[] = [\n+ { id: \"1\", text: \"chunk1\", cleanedText: \"chunk1\", type: \"text\" },\n+ { id: \"2\", text: \"chunk2\", cleanedText: \"chunk2\", type: \"text\" },\n+ ];\n \n- /**\n- * テストケース 1: 全ヒット\n- * すべてのチャンクがキャッシュ済み → isFullyCached: true\n- */\n- it('should return isFullyCached: true when all chunks are cached', async () => {\n- const testUrl = 'https://example.com/article1';\n- const chunks: Chunk[] = [\n- { id: '1', text: 'chunk1', cleanedText: 'chunk1', type: 'text' },\n- { id: '2', text: 'chunk2', cleanedText: 'chunk2', type: 'text' },\n- { id: '3', text: 'chunk3', cleanedText: 'chunk3', type: 'text' },\n- ];\n-\n- // モック設定:全てのチャンクが存在\n- const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction;\n- mockedGetArticleChunks.mockResolvedValue([\n- { chunkIndex: 0, audioData: new ArrayBuffer(100), synthesizedText: 'chunk1' },\n- { chunkIndex: 1, audioData: new ArrayBuffer(100), synthesizedText: 'chunk2' },\n- { chunkIndex: 2, audioData: new ArrayBuffer(100), synthesizedText: 'chunk3' },\n- ]);\n-\n- const result = await calculateCacheStats(testUrl, chunks);\n-\n- expect(result).toEqual({\n- cacheHits: 3,\n- cacheMisses: 0,\n- isFullyCached: true,\n- });\n+ // モック設定:キャッシュなし\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([]);\n+\n+ const result = await calculateCacheStats(testUrl, chunks);\n+\n+ expect(result).toEqual({\n+ cacheHits: 0,\n+ cacheMisses: 2,\n+ isFullyCached: false,\n });\n+ });\n+\n+ /**\n+ * テストケース 4: エラーハンドリング\n+ * getArticleChunks がエラーを投げた場合 → フォールバック値を返す\n+ */\n+ it(\"should return fallback values when getArticleChunks throws an error\", async () => {\n+ const testUrl = \"https://example.com/article4\";\n+ const chunks: Chunk[] = [\n+ { id: \"1\", text: \"chunk1\", cleanedText: \"chunk1\", type: \"text\" },\n+ { id: \"2\", text: \"chunk2\", cleanedText: \"chunk2\", type: \"text\" },\n+ ];\n+\n+ // モック設定:エラーを投げる\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockRejectedValue(new Error(\"IndexedDB error\"));\n+\n+ const result = await calculateCacheStats(testUrl, chunks);\n+\n+ // エラー時はすべてキャッシュミスとして扱う\n+ expect(result).toEqual({\n+ cacheHits: 0,\n+ cacheMisses: 2,\n+ isFullyCached: false,\n+ });\n+ });\n+\n+ /**\n+ * テストケース 5: 範囲外インデックス\n+ * chunkIndex が負数または配列長超過 → 無視される\n+ */\n+ it(\"should ignore out-of-range chunkIndex values\", async () => {\n+ const testUrl = \"https://example.com/article5\";\n+ const chunks: Chunk[] = [\n+ { id: \"1\", text: \"chunk1\", cleanedText: \"chunk1\", type: \"text\" },\n+ { id: \"2\", text: \"chunk2\", cleanedText: \"chunk2\", type: \"text\" },\n+ ];\n+\n+ // モック設定:有効なインデックス(0)と無効なインデックス(-1, 2, 3)を混在\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([\n+ {\n+ chunkIndex: 0,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk1\",\n+ },\n+ {\n+ chunkIndex: -1,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"negative\",\n+ }, // 無視される\n+ {\n+ chunkIndex: 2,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"out-of-range\",\n+ }, // 無視される\n+ {\n+ chunkIndex: 3,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"also-out\",\n+ }, // 無視される\n+ ]);\n+\n+ const result = await calculateCacheStats(testUrl, chunks);\n+\n+ // 有効なのはインデックス 0 のみ\n+ expect(result).toEqual({\n+ cacheHits: 1,\n+ cacheMisses: 1,\n+ isFullyCached: false,\n+ });\n+ });\n+\n+ /**\n+ * テストケース 6: 重複するインデックス\n+ * 同じ chunkIndex が複数回存在 → Set により重複は自動排除\n+ */\n+ it(\"should handle duplicate chunkIndex values correctly\", async () => {\n+ const testUrl = \"https://example.com/article6\";\n+ const chunks: Chunk[] = [\n+ { id: \"1\", text: \"chunk1\", cleanedText: \"chunk1\", type: \"text\" },\n+ { id: \"2\", text: \"chunk2\", cleanedText: \"chunk2\", type: \"text\" },\n+ { id: \"3\", text: \"chunk3\", cleanedText: \"chunk3\", type: \"text\" },\n+ ];\n+\n+ // モック設定:インデックス 0, 1 が重複\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([\n+ {\n+ chunkIndex: 0,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk1\",\n+ },\n+ {\n+ chunkIndex: 0,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk1-dup\",\n+ }, // 重複\n+ {\n+ chunkIndex: 1,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk2\",\n+ },\n+ {\n+ chunkIndex: 1,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk2-dup\",\n+ }, // 重複\n+ ]);\n+\n+ const result = await calculateCacheStats(testUrl, chunks);\n+\n+ // Set により重複は自動排除されるため、ヒット数は 2\n+ expect(result).toEqual({\n+ cacheHits: 2,\n+ cacheMisses: 1,\n+ isFullyCached: false,\n+ });\n+ });\n+\n+ /**\n+ * テストケース 7: 空のチャンク配列\n+ * chunks が空 → cacheHits: 0, isFullyCached: false\n+ */\n+ it(\"should return correct values for empty chunks array\", async () => {\n+ const testUrl = \"https://example.com/article7\";\n+ const chunks: Chunk[] = [];\n+\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([\n+ {\n+ chunkIndex: 0,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk1\",\n+ },\n+ ]);\n \n- /**\n- * テストケース 2: 一部ヒット\n- * 一部のチャンクのみキャッシュ済み → isFullyCached: false\n- */\n- it('should return isFullyCached: false when only some chunks are cached', async () => {\n- const testUrl = 'https://example.com/article2';\n- const chunks: Chunk[] = [\n- { id: '1', text: 'chunk1', cleanedText: 'chunk1', type: 'text' },\n- { id: '2', text: 'chunk2', cleanedText: 'chunk2', type: 'text' },\n- { id: '3', text: 'chunk3', cleanedText: 'chunk3', type: 'text' },\n- { id: '4', text: 'chunk4', cleanedText: 'chunk4', type: 'text' },\n- ];\n-\n- // モック設定:インデックス 0, 2 のみ存在\n- const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction;\n- mockedGetArticleChunks.mockResolvedValue([\n- { chunkIndex: 0, audioData: new ArrayBuffer(100), synthesizedText: 'chunk1' },\n- { chunkIndex: 2, audioData: new ArrayBuffer(100), synthesizedText: 'chunk3' },\n- ]);\n-\n- const result = await calculateCacheStats(testUrl, chunks);\n-\n- expect(result).toEqual({\n- cacheHits: 2,\n- cacheMisses: 2,\n- isFullyCached: false,\n- });\n+ const result = await calculateCacheStats(testUrl, chunks);\n+\n+ // チャンクが空なので isFullyCached は false\n+ expect(result).toEqual({\n+ cacheHits: 0,\n+ cacheMisses: 0,\n+ isFullyCached: false,\n });\n+ });\n+});\n \n- /**\n- * テストケース 3: キャッシュなし\n- * キャッシュが空 → cacheHits: 0\n- */\n- it('should return cacheHits: 0 when no chunks are cached', async () => {\n- const testUrl = 'https://example.com/article3';\n- const chunks: Chunk[] = [\n- { id: '1', text: 'chunk1', cleanedText: 'chunk1', type: 'text' },\n- { id: '2', text: 'chunk2', cleanedText: 'chunk2', type: 'text' },\n- ];\n-\n- // モック設定:キャッシュなし\n- const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction;\n- mockedGetArticleChunks.mockResolvedValue([]);\n-\n- const result = await calculateCacheStats(testUrl, chunks);\n-\n- expect(result).toEqual({\n- cacheHits: 0,\n- cacheMisses: 2,\n- isFullyCached: false,\n- });\n+describe(\"recordArticleStats\", () => {\n+ let originalFetch: typeof global.fetch;\n+\n+ beforeEach(() => {\n+ jest.resetAllMocks();\n+ // Setup crypto for SHA-256 mock\n+ Object.defineProperty(global, \"crypto\", {\n+ value: {\n+ subtle: {\n+ digest: jest.fn().mockResolvedValue(new ArrayBuffer(32)),\n+ },\n+ },\n+ writable: true,\n });\n \n- /**\n- * テストケース 4: エラーハンドリング\n- * getArticleChunks がエラーを投げた場合 → フォールバック値を返す\n- */\n- it('should return fallback values when getArticleChunks throws an error', async () => {\n- const testUrl = 'https://example.com/article4';\n- const chunks: Chunk[] = [\n- { id: '1', text: 'chunk1', cleanedText: 'chunk1', type: 'text' },\n- { id: '2', text: 'chunk2', cleanedText: 'chunk2', type: 'text' },\n- ];\n-\n- // モック設定:エラーを投げる\n- const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction;\n- mockedGetArticleChunks.mockRejectedValue(new Error('IndexedDB error'));\n-\n- const result = await calculateCacheStats(testUrl, chunks);\n-\n- // エラー時はすべてキャッシュミスとして扱う\n- expect(result).toEqual({\n- cacheHits: 0,\n- cacheMisses: 2,\n- isFullyCached: false,\n- });\n+ // Mock fetch\n+ originalFetch = global.fetch;\n+ global.fetch = jest.fn();\n+ });\n+\n+ afterEach(() => {\n+ global.fetch = originalFetch;\n+ });\n+\n+ const mockParams = {\n+ url: \"https://example.com/test-article\",\n+ title: \"Test Article\",\n+ content: \"Test content for hashing\",\n+ chunks: [\n+ { id: \"1\", text: \"chunk1\", cleanedText: \"chunk1\", type: \"text\" as const },\n+ ],\n+ };\n+\n+ it(\"should record stats successfully when fetch succeeds\", async () => {\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([\n+ {\n+ chunkIndex: 0,\n+ audioData: new ArrayBuffer(100),\n+ synthesizedText: \"chunk1\",\n+ },\n+ ]);\n+\n+ (global.fetch as jest.Mock).mockResolvedValue({\n+ ok: true,\n+ json: jest.fn().mockResolvedValue({ accessCount: 1, cacheHitRate: 100 }),\n });\n \n- /**\n- * テストケース 5: 範囲外インデックス\n- * chunkIndex が負数または配列長超過 → 無視される\n- */\n- it('should ignore out-of-range chunkIndex values', async () => {\n- const testUrl = 'https://example.com/article5';\n- const chunks: Chunk[] = [\n- { id: '1', text: 'chunk1', cleanedText: 'chunk1', type: 'text' },\n- { id: '2', text: 'chunk2', cleanedText: 'chunk2', type: 'text' },\n- ];\n-\n- // モック設定:有効なインデックス(0)と無効なインデックス(-1, 2, 3)を混在\n- const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction;\n- mockedGetArticleChunks.mockResolvedValue([\n- { chunkIndex: 0, audioData: new ArrayBuffer(100), synthesizedText: 'chunk1' },\n- { chunkIndex: -1, audioData: new ArrayBuffer(100), synthesizedText: 'negative' }, // 無視される\n- { chunkIndex: 2, audioData: new ArrayBuffer(100), synthesizedText: 'out-of-range' }, // 無視される\n- { chunkIndex: 3, audioData: new ArrayBuffer(100), synthesizedText: 'also-out' }, // 無視される\n- ]);\n-\n- const result = await calculateCacheStats(testUrl, chunks);\n-\n- // 有効なのはインデックス 0 のみ\n- expect(result).toEqual({\n- cacheHits: 1,\n- cacheMisses: 1,\n- isFullyCached: false,\n- });\n+ await recordArticleStats(mockParams);\n+\n+ expect(global.fetch).toHaveBeenCalledTimes(1);\n+ expect(global.fetch).toHaveBeenCalledWith(\n+ \"/api/stats/article\",\n+ expect.objectContaining({\n+ method: \"POST\",\n+ headers: { \"Content-Type\": \"application/json\" },\n+ body: expect.stringContaining(\n+ '\"cacheHits\":1,\"cacheMisses\":0,\"isFullyCached\":true',\n+ ),\n+ }),\n+ );\n+ expect(global.fetch).toHaveBeenCalledWith(\n+ \"/api/stats/article\",\n+ expect.objectContaining({\n+ body: expect.stringContaining('\"domain\":\"example.com\"'),\n+ }),\n+ );\n+\n+ expect(logger.info).toHaveBeenCalledWith(\n+ \"記事統計を記録\",\n+ expect.objectContaining({\n+ url: mockParams.url,\n+ accessCount: 1,\n+ cacheHitRate: 100,\n+ }),\n+ );\n+ });\n+\n+ it(\"should log a warning when fetch fails with non-ok status\", async () => {\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([]);\n+\n+ (global.fetch as jest.Mock).mockResolvedValue({\n+ ok: false,\n+ status: 500,\n });\n \n- /**\n- * テストケース 6: 重複するインデックス\n- * 同じ chunkIndex が複数回存在 → Set により重複は自動排除\n- */\n- it('should handle duplicate chunkIndex values correctly', async () => {\n- const testUrl = 'https://example.com/article6';\n- const chunks: Chunk[] = [\n- { id: '1', text: 'chunk1', cleanedText: 'chunk1', type: 'text' },\n- { id: '2', text: 'chunk2', cleanedText: 'chunk2', type: 'text' },\n- { id: '3', text: 'chunk3', cleanedText: 'chunk3', type: 'text' },\n- ];\n-\n- // モック設定:インデックス 0, 1 が重複\n- const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction;\n- mockedGetArticleChunks.mockResolvedValue([\n- { chunkIndex: 0, audioData: new ArrayBuffer(100), synthesizedText: 'chunk1' },\n- { chunkIndex: 0, audioData: new ArrayBuffer(100), synthesizedText: 'chunk1-dup' }, // 重複\n- { chunkIndex: 1, audioData: new ArrayBuffer(100), synthesizedText: 'chunk2' },\n- { chunkIndex: 1, audioData: new ArrayBuffer(100), synthesizedText: 'chunk2-dup' }, // 重複\n- ]);\n-\n- const result = await calculateCacheStats(testUrl, chunks);\n-\n- // Set により重複は自動排除されるため、ヒット数は 2\n- expect(result).toEqual({\n- cacheHits: 2,\n- cacheMisses: 1,\n- isFullyCached: false,\n- });\n+ await recordArticleStats(mockParams);\n+\n+ expect(global.fetch).toHaveBeenCalledTimes(1);\n+ expect(logger.warn).toHaveBeenCalledWith(\n+ \"記事統計の記録に失敗\",\n+ expect.objectContaining({\n+ status: 500,\n+ url: mockParams.url,\n+ }),\n+ );\n+ });\n+\n+ it(\"should retry on network errors (ECONNRESET/aborted) and throw after max retries\", async () => {\n+ jest.useFakeTimers();\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([]);\n+\n+ const networkError = new Error(\"fetch failed with ECONNRESET\");\n+ (global.fetch as jest.Mock).mockRejectedValue(networkError);\n+\n+ // start the promise\n+ const promise = recordArticleStats(mockParams);\n+\n+ // Wait for all microtasks to drain (so fetch is called and setTimeout is queued)\n+ for (let i = 0; i < 5; i++) await Promise.resolve();\n+ jest.advanceTimersByTime(1000); // Trigger 1st retry\n+\n+ for (let i = 0; i < 5; i++) await Promise.resolve();\n+ jest.advanceTimersByTime(1000); // Trigger 2nd retry\n+\n+ for (let i = 0; i < 5; i++) await Promise.resolve();\n+\n+ await promise;\n+\n+ expect(global.fetch).toHaveBeenCalledTimes(3);\n+ expect(logger.warn).toHaveBeenCalledWith(\n+ expect.stringContaining(\"Fetch attempt 1 failed\"),\n+ expect.any(String),\n+ );\n+ expect(logger.warn).toHaveBeenCalledWith(\n+ \"記事統計記録エラー\",\n+ expect.any(Error),\n+ );\n+\n+ jest.useRealTimers();\n+ });\n+\n+ it(\"should throw error immediately for non-network errors\", async () => {\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([]);\n+\n+ const nonNetworkError = new Error(\"some other error\");\n+ (global.fetch as jest.Mock).mockRejectedValue(nonNetworkError);\n+\n+ await recordArticleStats(mockParams);\n+\n+ // Should only be called once, no retries\n+ expect(global.fetch).toHaveBeenCalledTimes(1);\n+ expect(logger.warn).toHaveBeenCalledWith(\n+ \"記事統計記録エラー\",\n+ nonNetworkError,\n+ );\n+ });\n+\n+ it(\"should extract domain as unknown if URL is invalid\", async () => {\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ mockedGetArticleChunks.mockResolvedValue([]);\n+\n+ (global.fetch as jest.Mock).mockResolvedValue({\n+ ok: true,\n+ json: jest.fn().mockResolvedValue({}),\n });\n \n- /**\n- * テストケース 7: 空のチャンク配列\n- * chunks が空 → cacheHits: 0, isFullyCached: false\n- */\n- it('should return correct values for empty chunks array', async () => {\n- const testUrl = 'https://example.com/article7';\n- const chunks: Chunk[] = [];\n-\n- const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction;\n- mockedGetArticleChunks.mockResolvedValue([\n- { chunkIndex: 0, audioData: new ArrayBuffer(100), synthesizedText: 'chunk1' },\n- ]);\n-\n- const result = await calculateCacheStats(testUrl, chunks);\n-\n- // チャンクが空なので isFullyCached は false\n- expect(result).toEqual({\n- cacheHits: 0,\n- cacheMisses: 0,\n- isFullyCached: false,\n- });\n+ await recordArticleStats({\n+ ...mockParams,\n+ url: \"invalid-url\", // Invalid URL to trigger extractDomain catch block\n });\n+\n+ expect(global.fetch).toHaveBeenCalledWith(\n+ \"/api/stats/article\",\n+ expect.objectContaining({\n+ body: expect.stringContaining('\"domain\":\"unknown\"'),\n+ }),\n+ );\n+ });\n+\n+ it(\"should not throw an exception on unexpected errors\", async () => {\n+ const mockedGetArticleChunks = getArticleChunks as jest.MockedFunction<\n+ typeof getArticleChunks\n+ >;\n+ // Cause an unexpected error in cache calculation or earlier that bypasses retry\n+ const unexpectedError = new TypeError(\"Some unexpected type error\");\n+ (global.fetch as jest.Mock).mockRejectedValue(unexpectedError);\n+\n+ // recordArticleStats catches all errors\n+ await recordArticleStats(mockParams);\n+\n+ expect(global.fetch).toHaveBeenCalledTimes(1);\n+ expect(logger.warn).toHaveBeenCalledWith(\n+ \"記事統計記録エラー\",\n+ unexpectedError,\n+ );\n+ });\n });", "status": "modified"}, {"additions": 0, "deletions": 43, "filename": "patch_web_app.js", "patch": "@@ -1,43 +0,0 @@\n-const fs = require('fs');\n-const file = 'packages/web-app/lib/audioCache.ts';\n-let code = fs.readFileSync(file, 'utf8');\n-\n-// Fix the timestamp issue in HIT block\n-code = code.replace(\n- ` // LRU戦略: アクセスされたアイテムを最後に移動して最新にする\n- this.cache.delete(key);\n- this.cache.set(key, cached);`,\n- ` // LRU戦略: アクセスされたアイテムを最後に移動して最新にする\n- this.cache.delete(key);\n- this.cache.set(key, { ...cached, timestamp: Date.now() });`\n-);\n-\n-// Fix the logic block in web-app as well for consistency\n-code = code.replace(\n- ` // キャッシュサイズ制限の確認 (LRU)\n- if (this.cache.size >= MAX_CACHE_SIZE) {\n- const oldestKey = this.cache.keys().next().value;\n- if (oldestKey) {\n- logger.cache(\"EVICT\", \\`LRU evicting \\${oldestKey}\\`);\n- this.revoke(oldestKey);\n- }\n- }`,\n- ` // Evict the oldest item only if the cache is full and we are adding a new item.\n- if (!this.cache.has(key) && this.cache.size >= MAX_CACHE_SIZE) {\n- const oldestKey = this.cache.keys().next().value;\n- if (oldestKey) {\n- logger.cache(\"EVICT\", \\`LRU evicting \\${oldestKey}\\`);\n- this.revoke(oldestKey);\n- }\n- }\n-\n- // If updating an existing entry, delete it first to move it to the end for LRU.\n- // This also ensures the old object URL is revoked.\n- const oldEntry = this.cache.get(key);\n- if (oldEntry) {\n- URL.revokeObjectURL(oldEntry.url);\n- this.cache.delete(key);\n- }`\n-);\n-\n-fs.writeFileSync(file, code);", "status": "removed"}, {"additions": 0, "deletions": 32, "filename": "patch_web_app_vercel.js", "patch": "@@ -1,32 +0,0 @@\n-const fs = require('fs');\n-const file = 'packages/web-app-vercel/lib/audioCache.ts';\n-let code = fs.readFileSync(file, 'utf8');\n-\n-code = code.replace(\n- ` // キャッシュサイズ制限の確認 (LRU)\n- if (this.cache.size >= MAX_CACHE_SIZE) {\n- const oldestKey = this.cache.keys().next().value;\n- if (oldestKey) {\n- logger.cache(\"EVICT\", \\`LRU evicting \\${oldestKey}\\`);\n- this.revoke(oldestKey);\n- }\n- }`,\n- ` // Evict the oldest item only if the cache is full and we are adding a new item.\n- if (!this.cache.has(key) && this.cache.size >= MAX_CACHE_SIZE) {\n- const oldestKey = this.cache.keys().next().value;\n- if (oldestKey) {\n- logger.cache(\"EVICT\", \\`LRU evicting \\${oldestKey}\\`);\n- this.revoke(oldestKey);\n- }\n- }\n-\n- // If updating an existing entry, delete it first to move it to the end for LRU.\n- // This also ensures the old object URL is revoked.\n- const oldEntry = this.cache.get(key);\n- if (oldEntry) {\n- URL.revokeObjectURL(oldEntry.url);\n- this.cache.delete(key);\n- }`\n-);\n-\n-fs.writeFileSync(file, code);", "status": "removed"}], "message": "🧪 Add tests for recordArticleStats in articleStats.ts\n\nCo-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>", "sha": "30d47d05ca8f10a761752b8a96ec11c6668c6e54"}], "post_review_commits": ["94d43a7ce4104436c3bc858ab6383be9eee55a79", "5192f21d57cd58201882165ce16f45e106c75a55", "45de90ca7c0973b844aa5a7107bf66eaae555d9d"], "pr_author": "is0692vs", "pr_title": "🧪 Test articleStats recordPlay start", "repo_name": "Hiroki-org/Audicle"}, "repo": "Hiroki-org/Audicle", "snapshot": "snapshots/a5c2873b144fca9bd53dab2f7217701f315a3f6d84ca85c8cc1002fbffff6670.pack", "split": "rl", "task_id": "4e2d13176f1cee9180f3c539456cefa732aca1649ab10e30684e90a7b8e3cca5"} {"base_sha": "9e94db167bd46698bc825988ad39727ccb243daf", "cohort": null, "context": {"canonical_pr_url": "https://github.com/recoupable/app/pull/1748", "id": "4fdc9271f1725ace72d865abcb79606ca27e4b7802267b956c57f1e41e861180", "preparation_mode": "source-only", "snapshot": {"base_ref": "9e94db167bd46698bc825988ad39727ccb243daf", "base_sha": "9e94db167bd46698bc825988ad39727ccb243daf", "body": "", "head_ref": "ca7faa7d9c1e239ce8302de8aad5e01f1c4d1d25", "head_sha": "ca7faa7d9c1e239ce8302de8aad5e01f1c4d1d25", "name": "app", "number": 1748, "owner": "recoupable", "pr_url": "https://github.com/recoupable/app/pull/1748", "title": ""}}, "head_sha": "ca7faa7d9c1e239ce8302de8aad5e01f1c4d1d25", "metadata": {"group_id": "178bd949ffb266d6052c22434a5f619e689c842a3a5bf9323746bc9e121bf51d", "snapshot": {"base_sha": "9e94db167bd46698bc825988ad39727ccb243daf", "external_requirements": [], "head_sha": "ca7faa7d9c1e239ce8302de8aad5e01f1c4d1d25", "objects": 1248, "objects_sha256": "093b64055c025a89179e3e03266eba3a18f801ba2d259238fdcc9fb42f39777f", "patch_sha256": "b57d06edfcf157df78cd5cc587e9e99d9efae1cb3ce21a2edd495a7630af2331"}}, "pr_number": 1748, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "ca76acdff542", "description": "New-chat bootstrap sent a client-built cloneUrl that the sessions API silently discarded, leaving the session without the intended repository URL; the personal URL builder also used an obsolete slug-based repository name. Bootstrap now uses the API-returned canonical cloneUrl.", "file_path": "components/VercelChat/NewChatBootstrap.tsx"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "ca76acdff542", "description": "Organization selection was not sent as organizationId when creating a session, so the API could not centrally validate org access or scope the session to the selected organization.", "file_path": "lib/sessions/createSession.ts"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "ca76acdff542", "description": "Bootstrap waited indefinitely for a locally constructed cloneUrl when organization or account identity fields were missing. Removing that prerequisite lets the API resolve the repository or return an error.", "file_path": "components/VercelChat/NewChatBootstrap.tsx"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "40707d6a6334", "description": "The chat page generated a UUID different from the chat.id persisted by the sessions API. Workflow requests used the nonexistent UUID and failed with 404 \"Chat not found\".", "file_path": "components/VercelChat/NewChatBootstrap.tsx"}, {"action_id": "A5", "action_type": "improvement", "category": "refactor", "commit_sha": "d00f8e63508e", "description": "NewChatBootstrap mixed provisioning effects and state management with rendering, making the component exceed the repository's 100-line readability limit. The state machine was extracted into a hook.", "file_path": "components/VercelChat/NewChatBootstrap.tsx"}, {"action_id": "A6", "action_type": "improvement", "category": "refactor", "commit_sha": "d00f8e63508e", "description": "createSandbox contained error-response parsing, string normalization, and fallback-message logic alongside the HTTP request, exceeding the repository's 100-line limit and mixing responsibilities. Those helpers were extracted into focused files.", "file_path": "lib/sandboxes/createSandbox.ts"}, {"action_id": "A7", "action_type": "improvement", "category": "documentation", "commit_sha": "d00f8e63508e", "description": "SandboxCreateRequestError documentation did not distinguish the chat-to-recoup-api HTTP error from server-side @vercel/sandbox SDK errors, obscuring why its actionable response fields are needed.", "file_path": "lib/sandboxes/SandboxCreateRequestError.ts"}], "commits_under_review": [{"author": "sweetmantech", "date": "2026-05-26T13:00:07Z", "files": [{"additions": 2, "deletions": 2, "filename": "app/chat/page.tsx", "patch": "@@ -1,4 +1,4 @@\n-import { Chat } from \"@/components/VercelChat/chat\";\n+import NewChatBootstrap from \"@/components/VercelChat/NewChatBootstrap\";\n import generateUUID from \"@/lib/generateUUID\";\n import { getMessages } from \"@/lib/messages/getMessages\";\n \n@@ -15,7 +15,7 @@ export default async function ChatPage({ searchParams }: ChatPageProps) {\n \n return (\n

\n- \n+ \n
\n );\n }", "status": "modified"}, {"additions": 129, "deletions": 0, "filename": "components/VercelChat/NewChatBootstrap.tsx", "patch": "@@ -0,0 +1,129 @@\n+\"use client\";\n+\n+import { useEffect, useMemo, useRef, useState } from \"react\";\n+import type { UIMessage } from \"ai\";\n+import { Loader } from \"lucide-react\";\n+import { usePrivy } from \"@privy-io/react-auth\";\n+import { useUserProvider } from \"@/providers/UserProvder\";\n+import { useOrganization } from \"@/providers/OrganizationProvider\";\n+import useAccountOrganizations from \"@/hooks/useAccountOrganizations\";\n+import { buildOrgRepoUrl } from \"@/lib/recoupable/buildOrgRepoUrl\";\n+import { buildPersonalRepoUrl } from \"@/lib/recoupable/buildPersonalRepoUrl\";\n+import { createSession } from \"@/lib/sessions/createSession\";\n+import { createSandbox } from \"@/lib/sandboxes/createSandbox\";\n+import { Chat } from \"@/components/VercelChat/chat\";\n+\n+interface NewChatBootstrapProps {\n+ /** Chat row id generated by the server page (`generateUUID`). */\n+ id: string;\n+ initialMessages?: UIMessage[];\n+}\n+\n+type BootstrapState =\n+ | { status: \"idle\" | \"bootstrapping\" }\n+ | { status: \"ready\"; sessionId: string }\n+ | { status: \"error\"; message: string };\n+\n+/**\n+ * Client-side bootstrap for new chats. Provisions a session +\n+ * sandbox on recoup-api before mounting `` so the workflow\n+ * transport (`/api/chat/workflow`) has the `sessionId` its validator\n+ * requires (recoupable/chat#1747 Phase 1 + 3).\n+ *\n+ * Mounted by `app/chat/page.tsx` (server) which generates the chat id\n+ * and forwards it here; this component owns everything that needs\n+ * Privy/the API base URL.\n+ *\n+ * `cloneUrl` resolution mirrors open-agents' rule: if the\n+ * `OrganizationProvider` has an active org, build the org repo URL;\n+ * otherwise fall back to the per-account \"personal\" repo URL.\n+ */\n+export default function NewChatBootstrap({\n+ id,\n+ initialMessages,\n+}: NewChatBootstrapProps) {\n+ const { authenticated, getAccessToken } = usePrivy();\n+ const { userData } = useUserProvider();\n+ const { selectedOrgId } = useOrganization();\n+ const { data: organizations } = useAccountOrganizations();\n+ const [state, setState] = useState({ status: \"idle\" });\n+\n+ // Guard against React StrictMode double-mount running the bootstrap\n+ // twice — the inner createSession/createSandbox calls are not\n+ // idempotent (each POST would mint a fresh row + sandbox).\n+ const startedRef = useRef(false);\n+\n+ const cloneUrl = useMemo(() => {\n+ if (selectedOrgId) {\n+ const org = organizations?.find(\n+ (o) => o.organization_id === selectedOrgId,\n+ );\n+ if (!org?.organization_name) return null;\n+ return buildOrgRepoUrl({\n+ organizationId: org.organization_id,\n+ organizationName: org.organization_name,\n+ });\n+ }\n+ if (userData?.account_id && userData?.name) {\n+ return buildPersonalRepoUrl({\n+ accountId: userData.account_id,\n+ accountName: userData.name,\n+ });\n+ }\n+ return null;\n+ }, [selectedOrgId, organizations, userData?.account_id, userData?.name]);\n+\n+ useEffect(() => {\n+ if (!authenticated || !cloneUrl) return;\n+ if (startedRef.current) return;\n+ if (state.status !== \"idle\") return;\n+\n+ startedRef.current = true;\n+ setState({ status: \"bootstrapping\" });\n+\n+ void (async () => {\n+ try {\n+ const accessToken = await getAccessToken();\n+ if (!accessToken) {\n+ throw new Error(\"Please sign in to start a chat\");\n+ }\n+\n+ const { session } = await createSession({ cloneUrl }, accessToken);\n+ await createSandbox(cloneUrl, session.id, accessToken);\n+\n+ setState({ status: \"ready\", sessionId: session.id });\n+ } catch (error) {\n+ startedRef.current = false;\n+ const message =\n+ error instanceof Error\n+ ? error.message\n+ : \"Failed to start a new chat. Please try again.\";\n+ setState({ status: \"error\", message });\n+ }\n+ })();\n+ }, [authenticated, cloneUrl, getAccessToken, state.status]);\n+\n+ if (state.status === \"ready\") {\n+ return (\n+ \n+ );\n+ }\n+\n+ if (state.status === \"error\") {\n+ return (\n+
\n+ {state.message}\n+
\n+ );\n+ }\n+\n+ return (\n+
\n+ \n+
\n+ );\n+}", "status": "added"}, {"additions": 15, "deletions": 2, "filename": "components/VercelChat/chat.tsx", "patch": "@@ -22,15 +22,28 @@ import { useOrganization } from \"@/providers/OrganizationProvider\";\n \n interface ChatProps {\n id: string;\n+ /**\n+ * Session id from the new-chat bootstrap. When present the chat\n+ * routes through recoup-api's `/api/chat/workflow`; when absent it\n+ * falls back to the legacy `/api/chat` (existing chats opened from\n+ * history — they'll cut over once Phase 2 backfills `session_id`\n+ * onto their rows, recoupable/chat#1747).\n+ */\n+ sessionId?: string;\n initialMessages?: UIMessage[];\n }\n \n-export function Chat({ id, initialMessages }: ChatProps) {\n+export function Chat({ id, sessionId, initialMessages }: ChatProps) {\n const { selectedOrgId } = useOrganization();\n const providerKey = `${id}-${selectedOrgId ?? \"personal\"}`;\n \n return (\n- \n+ \n \n \n );", "status": "modified"}, {"additions": 62, "deletions": 3, "filename": "hooks/useChatTransport.ts", "patch": "@@ -3,7 +3,46 @@ import { DefaultChatTransport } from \"ai\";\n import { getClientApiBaseUrl } from \"@/lib/api/getClientApiBaseUrl\";\n import { usePrivy } from \"@privy-io/react-auth\";\n \n-export function useChatTransport() {\n+interface UseChatTransportOptions {\n+ /** Chat row id (also the AI SDK `useChat({ id })` instance id). */\n+ chatId: string;\n+ /**\n+ * Session id from `createSession`. When provided, the transport\n+ * targets recoup-api's `POST /api/chat/workflow` (the workflow path\n+ * cutover tracked in recoupable/chat#1747) and injects\n+ * `sessionId` + `chatId` + `recoupAccessToken` at the transport\n+ * boundary.\n+ *\n+ * When absent, the transport targets the legacy `POST /api/chat`\n+ * route — used by `/chat/[roomId]` pages opened from history that\n+ * don't have a `session_id` on their chat row yet. Those rows will\n+ * be backfilled in Phase 2 (recoupable/chat#1747), at which point\n+ * this branch can be deleted.\n+ */\n+ sessionId?: string;\n+}\n+\n+/**\n+ * Chat transport for chat.recoupable.com. Branches on `sessionId`:\n+ * - **workflow path** (sessionId present) → recoup-api\n+ * `/api/chat/workflow`, with `sessionId` + `chatId` +\n+ * `recoupAccessToken` injected so per-`sendMessage` callers don't\n+ * need to know the workflow body shape.\n+ * - **legacy path** (no sessionId) → `/api/chat` on the same base,\n+ * same behavior chat.recoupable.com had before the workflow\n+ * cutover. Per-call body from `useVercelChat`'s\n+ * `sendMessage(payload, { body })` (`roomId`, `artistId`, `model`,\n+ * …) flows through unchanged.\n+ *\n+ * Both branches return the Privy JWT in the `Authorization: Bearer`\n+ * header via `getHeaders`; the workflow branch also adds it\n+ * transport-side so recoup-api's `validateAuthContext` accepts the\n+ * cross-origin POST.\n+ */\n+export function useChatTransport({\n+ chatId,\n+ sessionId,\n+}: UseChatTransportOptions) {\n const { getAccessToken } = usePrivy();\n const baseUrl = getClientApiBaseUrl();\n \n@@ -13,10 +52,30 @@ export function useChatTransport() {\n }, [getAccessToken]);\n \n const transport = useMemo(() => {\n+ if (!sessionId) {\n+ return new DefaultChatTransport({\n+ api: `${baseUrl}/api/chat`,\n+ });\n+ }\n+\n return new DefaultChatTransport({\n- api: `${baseUrl}/api/chat`,\n+ api: `${baseUrl}/api/chat/workflow`,\n+ headers: async (): Promise> => {\n+ const accessToken = await getAccessToken().catch(() => null);\n+ return accessToken ? { Authorization: `Bearer ${accessToken}` } : {};\n+ },\n+ body: async () => {\n+ const recoupAccessToken = await getAccessToken().catch(() => null);\n+ const body: {\n+ sessionId: string;\n+ chatId: string;\n+ recoupAccessToken?: string;\n+ } = { sessionId, chatId };\n+ if (recoupAccessToken) body.recoupAccessToken = recoupAccessToken;\n+ return body;\n+ },\n });\n- }, [baseUrl]);\n+ }, [baseUrl, chatId, sessionId, getAccessToken]);\n \n return { transport, getHeaders };\n }", "status": "modified"}, {"additions": 13, "deletions": 1, "filename": "hooks/useVercelChat.ts", "patch": "@@ -26,6 +26,14 @@ import getMimeFromPath from \"@/lib/files/getMimeFromPath\";\n \n interface UseVercelChatProps {\n id: string;\n+ /**\n+ * Session id from the chat-bootstrap (`createSession`). When present\n+ * the transport targets `/api/chat/workflow`; when absent it falls\n+ * back to the legacy `/api/chat` for chats opened from history that\n+ * haven't been backfilled to the workflow architecture yet\n+ * (recoupable/chat#1747 Phase 2).\n+ */\n+ sessionId?: string;\n initialMessages?: UIMessage[];\n attachments?: FileUIPart[];\n textAttachments?: TextAttachment[];\n@@ -38,6 +46,7 @@ interface UseVercelChatProps {\n */\n export function useVercelChat({\n id,\n+ sessionId,\n initialMessages,\n attachments = [],\n textAttachments = [],\n@@ -55,7 +64,10 @@ export function useVercelChat({\n const [input, setInput] = useState(\"\");\n const [model, setModel] = useLocalStorage(\"RECOUP_MODEL\", DEFAULT_MODEL);\n const { refetchCredits } = usePaymentProvider();\n- const { transport, getHeaders } = useChatTransport();\n+ const { transport, getHeaders } = useChatTransport({\n+ chatId: id,\n+ sessionId,\n+ });\n const { authenticated, getAccessToken } = usePrivy();\n \n // Load artist files for mentions (from Supabase)", "status": "modified"}, {"additions": 18, "deletions": 0, "filename": "lib/recoupable/buildOrgRepoUrl.ts", "patch": "@@ -0,0 +1,18 @@\n+import { toKebabCase } from \"@/lib/string/toKebabCase\";\n+import { RECOUPABLE_GITHUB_OWNER } from \"./githubOwner\";\n+\n+/**\n+ * Builds the GitHub URL for a Recoupable org's per-org repository.\n+ * Convention: `https://github.com/recoupable/org--`.\n+ *\n+ * Ported from open-agents `apps/web/lib/recoupable/build-org-repo-url.ts`\n+ * so chat.recoupable.com and sandbox.recoupable.com construct the same\n+ * URL for the same org.\n+ */\n+export function buildOrgRepoUrl(params: {\n+ organizationName: string;\n+ organizationId: string;\n+}): string {\n+ const slug = toKebabCase(params.organizationName);\n+ return `https://github.com/${RECOUPABLE_GITHUB_OWNER}/org-${slug}-${params.organizationId}`;\n+}", "status": "added"}, {"additions": 24, "deletions": 0, "filename": "lib/recoupable/buildPersonalRepoUrl.ts", "patch": "@@ -0,0 +1,24 @@\n+import { toKebabCase } from \"@/lib/string/toKebabCase\";\n+import { RECOUPABLE_GITHUB_OWNER } from \"./githubOwner\";\n+\n+/**\n+ * Builds the GitHub URL for an account's per-account (\"personal\") repository,\n+ * used as the fallback when the user has no Recoupable organization selected.\n+ * Convention: `https://github.com/recoupable/-`.\n+ *\n+ * Example: `recoupable/sweetman-fb678396-a68f-4294-ae50-b8cacf9ce77b`.\n+ *\n+ * Mirrors `buildOrgRepoUrl` for orgs (which uses an `org-` prefix); personal\n+ * repos use no prefix because the account name is already the disambiguator.\n+ *\n+ * Ported from open-agents `apps/web/lib/recoupable/build-personal-repo-url.ts`\n+ * so chat.recoupable.com and sandbox.recoupable.com construct the same\n+ * URL for the same account.\n+ */\n+export function buildPersonalRepoUrl(params: {\n+ accountName: string;\n+ accountId: string;\n+}): string {\n+ const slug = toKebabCase(params.accountName);\n+ return `https://github.com/${RECOUPABLE_GITHUB_OWNER}/${slug}-${params.accountId}`;\n+}", "status": "added"}, {"additions": 11, "deletions": 0, "filename": "lib/recoupable/githubOwner.ts", "patch": "@@ -0,0 +1,11 @@\n+/**\n+ * The GitHub organization that owns every Recoupable workspace repo,\n+ * both per-Recoupable-org repos (`recoupable/org--`) and\n+ * per-account personal repos (`recoupable/-`).\n+ *\n+ * Single source of truth so renames or alternate-environment overrides\n+ * stay in lockstep across builders, parsers, and GitHub API callers.\n+ *\n+ * Ported from open-agents `apps/web/lib/recoupable/github-owner.ts`.\n+ */\n+export const RECOUPABLE_GITHUB_OWNER = \"recoupable\";", "status": "added"}, {"additions": 33, "deletions": 0, "filename": "lib/sandboxes/SandboxCreateRequestError.ts", "patch": "@@ -0,0 +1,33 @@\n+/**\n+ * Error thrown by `createSandbox` when `POST /api/sandbox` fails.\n+ * Carries the response status and any structured error payload\n+ * (`reason`, `actionUrl`) so the UI can render a useful message\n+ * (e.g. \"Reconnect GitHub\" with a deep link) instead of a generic\n+ * \"request failed\".\n+ *\n+ * Ported from open-agents\n+ * `apps/web/lib/sandbox/sandbox-create-request-error.ts`.\n+ */\n+export class SandboxCreateRequestError extends Error {\n+ readonly reason?: string;\n+ readonly actionUrl?: string;\n+ readonly status: number;\n+ readonly responseBody?: string;\n+\n+ constructor(\n+ message: string,\n+ options: {\n+ status: number;\n+ reason?: string;\n+ actionUrl?: string;\n+ responseBody?: string;\n+ },\n+ ) {\n+ super(message);\n+ this.name = \"SandboxCreateRequestError\";\n+ this.reason = options.reason;\n+ this.actionUrl = options.actionUrl;\n+ this.status = options.status;\n+ this.responseBody = options.responseBody;\n+ }\n+}", "status": "added"}, {"additions": 117, "deletions": 0, "filename": "lib/sandboxes/createSandbox.ts", "patch": "@@ -1,7 +1,124 @@\n+import { getClientApiBaseUrl } from \"@/lib/api/getClientApiBaseUrl\";\n+import { SandboxCreateRequestError } from \"./SandboxCreateRequestError\";\n+\n+/**\n+ * Sandbox row shape used by the listing UI (`useSandboxes`,\n+ * `SandboxList`, `SandboxListCard`). Kept here for backwards-compat\n+ * with the existing 4 callers that import `type { Sandbox }` from\n+ * this file.\n+ */\n export interface Sandbox {\n sandboxId: string;\n sandboxStatus: \"pending\" | \"running\" | \"stopping\" | \"stopped\" | \"failed\";\n timeout: number;\n createdAt: string;\n runId?: string;\n }\n+\n+/**\n+ * Newly-provisioned sandbox response from `POST /api/sandbox`. Matches\n+ * open-agents' `SandboxInfo & { type }` shape so chat.recoupable.com\n+ * and sandbox.recoupable.com can both pass the result into\n+ * `runAgentWorkflow`'s `agentContext.sandbox`.\n+ */\n+export interface CreateSandboxResponse {\n+ type: string;\n+ createdAt: number;\n+ timeout: number | null;\n+ currentBranch?: string;\n+}\n+\n+interface CreateSandboxErrorResponse {\n+ error?: string;\n+ reason?: string;\n+ actionUrl?: string;\n+}\n+\n+function parseCreateSandboxErrorResponse(\n+ rawBody: string,\n+): CreateSandboxErrorResponse | null {\n+ if (!rawBody) return null;\n+ try {\n+ const parsed = JSON.parse(rawBody) as unknown;\n+ if (!parsed || typeof parsed !== \"object\") return null;\n+ return parsed as CreateSandboxErrorResponse;\n+ } catch {\n+ return null;\n+ }\n+}\n+\n+function getOptionalString(value: unknown): string | undefined {\n+ if (typeof value !== \"string\") return undefined;\n+ const trimmed = value.trim();\n+ return trimmed.length > 0 ? trimmed : undefined;\n+}\n+\n+function getFallbackSandboxCreateErrorMessage(status: number): string {\n+ if (status === 403) {\n+ return \"Sandbox access denied. Please reconnect GitHub and try again.\";\n+ }\n+ return \"Failed to create sandbox. Please try again.\";\n+}\n+\n+/**\n+ * Provision a sandbox for the given session via `POST /api/sandbox`\n+ * on recoup-api. Ported from open-agents\n+ * `apps/web/lib/sandbox/create-sandbox.ts` (DRY) so chat.recoupable.com\n+ * and sandbox.recoupable.com use the same provisioning path.\n+ *\n+ * recoup-api owns the sandbox lifecycle (provisioning, lifecycle\n+ * workflow, snapshot lookup, global-skill install) so the sandbox is\n+ * born in recoup-api's Vercel project and the chat workflow's\n+ * `sandbox.exec` calls — which also resolve via recoup-api's OIDC —\n+ * can reach it without any cross-project credential plumbing.\n+ *\n+ * @param cloneUrl - Repo URL to clone into the sandbox. Built via\n+ * `buildOrgRepoUrl` (active org selected) or `buildPersonalRepoUrl`\n+ * (personal account fallback).\n+ * @param sessionId - Session UUID created via `createSession`.\n+ * @param recoupAccessToken - Short-lived Privy JWT. Forwarded as\n+ * `Authorization: Bearer …` so recoup-api's `validateAuthContext`\n+ * accepts the cross-origin request.\n+ */\n+export async function createSandbox(\n+ cloneUrl: string,\n+ sessionId: string,\n+ recoupAccessToken: string | null,\n+): Promise {\n+ const headers: Record = {\n+ \"Content-Type\": \"application/json\",\n+ };\n+ if (recoupAccessToken) {\n+ headers.Authorization = `Bearer ${recoupAccessToken}`;\n+ }\n+\n+ const response = await fetch(`${getClientApiBaseUrl()}/api/sandbox`, {\n+ method: \"POST\",\n+ headers,\n+ body: JSON.stringify({ repoUrl: cloneUrl, sessionId }),\n+ });\n+\n+ if (!response.ok) {\n+ const rawBody = await response.text().catch(() => \"\");\n+ const payload = parseCreateSandboxErrorResponse(rawBody);\n+ const message =\n+ getOptionalString(payload?.error) ??\n+ getFallbackSandboxCreateErrorMessage(response.status);\n+\n+ throw new SandboxCreateRequestError(message, {\n+ status: response.status,\n+ reason: getOptionalString(payload?.reason),\n+ actionUrl: getOptionalString(payload?.actionUrl),\n+ responseBody: rawBody || undefined,\n+ });\n+ }\n+\n+ const data = (await response.json()) as {\n+ mode: string;\n+ createdAt: number;\n+ timeout: number | null;\n+ currentBranch?: string;\n+ };\n+\n+ return { ...data, type: data.mode };\n+}", "status": "modified"}, {"additions": 77, "deletions": 0, "filename": "lib/sessions/createSession.ts", "patch": "@@ -0,0 +1,77 @@\n+import { getClientApiBaseUrl } from \"@/lib/api/getClientApiBaseUrl\";\n+\n+/**\n+ * Body accepted by recoup-api `POST /api/sessions`. Mirrors the\n+ * server-side Zod schema in `api/lib/sessions/validateCreateSessionBody.ts`.\n+ * All fields are optional — pass `cloneUrl` so the session row records\n+ * which repo the sandbox will clone.\n+ */\n+export interface CreateSessionInput {\n+ title?: string;\n+ cloneUrl?: string;\n+ branch?: string;\n+ sandboxType?: \"vercel\";\n+}\n+\n+/**\n+ * Session + first-chat shape returned by `POST /api/sessions`. We\n+ * intentionally type only the fields chat.recoupable.com reads at the\n+ * call site (the session id, plus the chat id we hand to the workflow\n+ * transport); the server returns a richer payload that we don't need\n+ * to model here.\n+ */\n+export interface CreateSessionResponse {\n+ session: { id: string };\n+ chat: { id: string };\n+}\n+\n+interface CreateSessionErrorResponse {\n+ error?: string;\n+}\n+\n+/**\n+ * Create a session row on recoup-api so the workflow transport has a\n+ * `sessionId` to attach the chat to. Mirrors the cutover that\n+ * sandbox.recoupable.com (open-agents) already made — both surfaces\n+ * use the same recoup-api `POST /api/sessions` so session ownership\n+ * lives in one place.\n+ *\n+ * @param input - Session metadata. Pass `cloneUrl` (built via\n+ * `buildOrgRepoUrl` / `buildPersonalRepoUrl`) so the session row\n+ * records which workspace repo this chat targets.\n+ * @param recoupAccessToken - Short-lived Privy JWT, forwarded as\n+ * `Authorization: Bearer …`.\n+ */\n+export async function createSession(\n+ input: CreateSessionInput,\n+ recoupAccessToken: string | null,\n+): Promise {\n+ const headers: Record = {\n+ \"Content-Type\": \"application/json\",\n+ };\n+ if (recoupAccessToken) {\n+ headers.Authorization = `Bearer ${recoupAccessToken}`;\n+ }\n+\n+ const response = await fetch(`${getClientApiBaseUrl()}/api/sessions`, {\n+ method: \"POST\",\n+ headers,\n+ body: JSON.stringify(input),\n+ });\n+\n+ if (!response.ok) {\n+ const rawBody = await response.text().catch(() => \"\");\n+ let parsed: CreateSessionErrorResponse | null = null;\n+ if (rawBody) {\n+ try {\n+ parsed = JSON.parse(rawBody) as CreateSessionErrorResponse;\n+ } catch {\n+ parsed = null;\n+ }\n+ }\n+ const message = parsed?.error ?? \"Failed to create session\";\n+ throw new Error(message);\n+ }\n+\n+ return (await response.json()) as CreateSessionResponse;\n+}", "status": "added"}, {"additions": 15, "deletions": 0, "filename": "lib/string/toKebabCase.ts", "patch": "@@ -0,0 +1,15 @@\n+/**\n+ * Converts an arbitrary string into kebab-case slug form.\n+ * - lowercases\n+ * - collapses any non-alphanumeric runs to a single `-`\n+ * - trims leading / trailing `-`\n+ *\n+ * Used to build per-org and per-account repo URLs from human-entered\n+ * names. Ported from open-agents `apps/web/lib/string/to-kebab-case.ts`.\n+ */\n+export function toKebabCase(input: string): string {\n+ return input\n+ .toLowerCase()\n+ .replace(/[^a-z0-9]+/g, \"-\")\n+ .replace(/^-+|-+$/g, \"\");\n+}", "status": "added"}, {"additions": 8, "deletions": 0, "filename": "providers/VercelChatProvider.tsx", "patch": "@@ -58,6 +58,12 @@ const VercelChatContext = createContext(\n interface VercelChatProviderProps {\n children: ReactNode;\n chatId: string;\n+ /**\n+ * Session id from the new-chat bootstrap. Forwarded into\n+ * `useVercelChat` -> `useChatTransport`; presence flips the\n+ * transport to recoup-api's `/api/chat/workflow`.\n+ */\n+ sessionId?: string;\n initialMessages?: UIMessage[];\n }\n \n@@ -67,6 +73,7 @@ interface VercelChatProviderProps {\n export function VercelChatProvider({\n children,\n chatId,\n+ sessionId,\n initialMessages,\n }: VercelChatProviderProps) {\n const {\n@@ -114,6 +121,7 @@ export function VercelChatProvider({\n availableModels,\n } = useVercelChat({\n id: chatId,\n+ sessionId,\n initialMessages,\n attachments,\n textAttachments,", "status": "modified"}], "message": "feat: route new chats through /api/chat/workflow\n\nNew chats now provision a recoup-api session + sandbox before the\nfirst message and stream through recoup-api's /api/chat/workflow\nendpoint (Path C cutover, recoupable/chat#1747 Phase 1 + 3). Existing\nchats opened from history continue using the legacy /api/chat until\nPhase 2 backfills session_id onto those rows.\n\nURL builders, kebab helper, sandbox provisioner, and error class are\nported from open-agents (DRY) so chat.recoupable.com and\nsandbox.recoupable.com construct identical cloneUrls and hit the same\nrecoup-api endpoints.\n\nCo-Authored-By: Claude Opus 4.7 ", "sha": "ca7faa7d9c1e239ce8302de8aad5e01f1c4d1d25"}], "post_review_commits": ["ca76acdff54277acc021911901bb72121667187b", "40707d6a6334419e143bcbd9eb897f1121a6d341", "d00f8e63508ed6244d8e67a91e19627eed27345d"], "pr_author": "sweetmantech", "pr_title": "feat: route new chats through recoup-api /api/chat/workflow", "repo_name": "recoupable/app"}, "repo": "recoupable/app", "snapshot": "snapshots/178bd949ffb266d6052c22434a5f619e689c842a3a5bf9323746bc9e121bf51d.pack", "split": "rl", "task_id": "4fdc9271f1725ace72d865abcb79606ca27e4b7802267b956c57f1e41e861180"} {"base_sha": "e55ecfbebca0da102cd5a47f9bff907a24917d83", "cohort": null, "context": {"canonical_pr_url": "https://github.com/jaylfc/taOS/pull/2362", "id": "51e5c467d7e987e613dd54cf2b964bc398eb9f5884f2555f705076cf40d61feb", "preparation_mode": "source-only", "snapshot": {"base_ref": "e55ecfbebca0da102cd5a47f9bff907a24917d83", "base_sha": "e55ecfbebca0da102cd5a47f9bff907a24917d83", "body": "", "head_ref": "35d95980d1d702c382a2663e6e66e7cd873a8cc6", "head_sha": "35d95980d1d702c382a2663e6e66e7cd873a8cc6", "name": "taOS", "number": 2362, "owner": "jaylfc", "pr_url": "https://github.com/jaylfc/taOS/pull/2362", "title": ""}}, "head_sha": "35d95980d1d702c382a2663e6e66e7cd873a8cc6", "metadata": {"group_id": "71152d589a50d05f66a2a1943d5a49d55e1cad89919e67698123cf0d2ad39208", "snapshot": {"base_sha": "e55ecfbebca0da102cd5a47f9bff907a24917d83", "external_requirements": [], "head_sha": "35d95980d1d702c382a2663e6e66e7cd873a8cc6", "objects": 3710, "objects_sha256": "21b8d44e308cb29290dfeea89589d829b4427f96805cf24fb8272d4249dab3a0", "patch_sha256": "fafe86ca9a76c46e7049caa49bf2f957884f7701d8e310945673dba5a10026f3"}}, "pr_number": 2362, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "security", "commit_sha": "8c5c036818bf", "description": "The live LiteLLM proxy master key at data/.litellm_master_key was not ignored: its bare `_key` suffix matched neither `*.key` nor `data/*.key`, leaving it vulnerable to accidental staging.", "file_path": ".gitignore"}, {"action_id": "A2", "action_type": "fix", "category": "security", "commit_sha": "8c5c036818bf", "description": "The secret-ignore gate did not require or test protection for data/.litellm_master_key, so it could pass while that known secret remained unignored.", "file_path": "scripts/check_secret_ignores.py"}, {"action_id": "A3", "action_type": "fix", "category": "documentation", "commit_sha": "acf89f337438", "description": "The release guide’s command block lacked a language tag, triggering Markdownlint MD040.", "file_path": "docs/RELEASING.md"}], "commits_under_review": [{"author": "jaylfc", "date": "2026-08-11T20:24:27Z", "files": [{"additions": 23, "deletions": 0, "filename": ".claude/skills/taos-development-skill/SKILL.md", "patch": "@@ -452,6 +452,29 @@ trailer, which is logged by the gate:\n Store-Unwired-Intentionally: , \n ```\n \n+## Secret-ignores gate\n+\n+A gate (`.github/workflows/secret-ignores-gate.yml`, running `scripts/check_secret_ignores.py`)\n+verifies that the committed `.gitignore` still protects known secret-shaped paths on every\n+promotion target. A `.gitignore` rule is the kind of file a rebase conflict can quietly drop\n+during a dev->master promotion while every test stays green and nothing builds red, so the\n+protection is asserted here, not assumed. The gate runs on push to `master`, `dev` and\n+`release/*` (a dropped rule fails the branch it lands on) and on PRs to those branches (a\n+conflict-resolution loss fails before the merge, since the merge commit's `.gitignore` is what\n+is checked).\n+\n+Two signals, defense in depth:\n+\n+- Every required protection rule must appear verbatim as an active line of `.gitignore`\n+ (`*.key`, `identity.json`, `*.p8`, `*credentials.json`, `*creds*.json`, the `*_private.*`\n+ key shapes, `secrets/`, `data/hub/`, and the rest listed in `REQUIRED_PATTERNS` in the\n+ script). Comment prose and narrower sibling rules do not satisfy a rule.\n+- A set of secret-shaped paths (`data/hub/identity.json`, `foo.key`, `creds.json`, `x.p8`,\n+ `y_credentials.json`, ...) must all be reported ignored by `git check-ignore`.\n+\n+Removing any one protection pattern turns the gate red -- proven by a parametrized test that\n+drops each pattern from a copy of the real `.gitignore` and asserts the guard fails.\n+\n ## Upstream conventions (from CONTRIBUTING.md)\n \n - **Target branch is `dev`, not `master`.** `master` is the stable live-install track.", "status": "modified"}, {"additions": 35, "deletions": 0, "filename": ".github/workflows/secret-ignores-gate.yml", "patch": "@@ -0,0 +1,35 @@\n+name: Secret-ignores gate\n+\n+# Verifies that the committed .gitignore still protects known secret-shaped\n+# paths (data/hub/identity.json, foo.key, creds.json, x.p8, ...) on every\n+# promotion target. A .gitignore is the kind of file a rebase conflict can\n+# quietly drop during a dev->master promotion while every test still passes and\n+# nothing builds red, so promotion is verified here, not assumed.\n+#\n+# Trigger scope is deliberate:\n+# - push to master/dev/release/* : a dropped pattern fails the branch it\n+# lands on (this is the post-promotion check from tsk-laezfg step 1).\n+# - pull_request to master/dev/release/* : a conflict-resolution loss fails\n+# BEFORE the merge, since the merge commit's .gitignore is what is checked.\n+# The run is pure stdlib (~1s), so it carries no shard-timeout risk.\n+#\n+# See scripts/check_secret_ignores.py for REQUIRED_PATTERNS and SECRET_PATHS.\n+\n+on:\n+ push:\n+ branches: [master, dev, release/*]\n+ pull_request:\n+ branches: [master, dev, release/*]\n+\n+jobs:\n+ secret-ignores-gate:\n+ runs-on: ubuntu-latest\n+ permissions:\n+ contents: read\n+ steps:\n+ - uses: actions/checkout@v7\n+ - uses: actions/setup-python@v7\n+ with:\n+ python-version: \"3.12\"\n+ - name: Assert secret-shaped paths are ignored\n+ run: python scripts/check_secret_ignores.py", "status": "added"}, {"additions": 12, "deletions": 0, "filename": "changelog.d/tsk-laezfg-secret-ignores-gate.md", "patch": "@@ -0,0 +1,12 @@\n+### Security\n+\n+- **CI**: `secret-ignores-gate` workflow and `scripts/check_secret_ignores.py` now\n+ assert, on push to `master`/`dev`/`release/*` and on PRs to those branches, that the\n+ committed `.gitignore` still contains every secret-protection rule (`*.key`,\n+ `*.p8`, `identity.json`, `*credentials.json`, `*creds*.json`, the `*_private.*` key\n+ shapes, `secrets/`, `data/hub/`, and more) and that known secret-shaped paths\n+ (`data/hub/identity.json`, `foo.key`, `creds.json`, `x.p8`, `y_credentials.json`,\n+ ...) are all reported ignored by `git check-ignore`. Closes the \"promotion must be\n+ verified, not assumed\" gap from #2171/#2173: a `.gitignore` conflict resolution can\n+ quietly drop a key-material rule while every test stays green. Removing any one\n+ pattern is proven to fail the gate by a parametrized test.", "status": "added"}, {"additions": 14, "deletions": 0, "filename": "docs/RELEASING.md", "patch": "@@ -34,6 +34,20 @@ CI runs the backend pytest suite and frontend vitest on every PR; both must be g\n Once the PR is merged to `dev`, open a follow-up PR from `dev` to `master`.\n After that PR merges, the install-count telemetry at taos.my starts recording the new version for every fresh install.\n \n+The `secret-ignores-gate` runs on the `master` push (and on the PR merge result)\n+and confirms the promoted `.gitignore` still ignores every secret-shaped path it\n+did on `dev` -- `identity.json`, `*.key`, `*.p8`, `*credentials.json`, `*creds*.json`\n+and the `*_private.*` key shapes, plus the `secrets/` and `data/hub/` rules. Re-run\n+it by hand if a conflict resolution touched `.gitignore`:\n+\n+```\n+python3 scripts/check_secret_ignores.py\n+```\n+\n+Do not skip this: a `.gitignore` conflict resolution can quietly drop a\n+key-material rule while every test stays green. The gate is the verification, not\n+an assumption.\n+\n ### 5. Tag and create a GitHub Release\n \n On `master`, after the merge commit:", "status": "modified"}, {"additions": 211, "deletions": 0, "filename": "scripts/check_secret_ignores.py", "patch": "@@ -0,0 +1,211 @@\n+#!/usr/bin/env python3\n+\"\"\"Secret-material ignore guard.\n+\n+Verifies that the committed `.gitignore` on the branch under test still\n+protects known secret-shaped paths. After a dev->master promotion a\n+`.gitignore` rule can be silently dropped during conflict resolution (a\n+`.gitignore` is exactly the kind of file a rebase conflict quietly loses while\n+every test still passes and nothing builds red), so this gate asserts the\n+protection mechanically instead of assuming promotion carried it.\n+\n+The check runs on push to `master`, `dev` and `release/*` -- so a dropped\n+pattern fails the branch it actually lands on -- and on PRs targeting those\n+branches -- so a conflict-resolution loss fails BEFORE the merge. See\n+`.github/workflows/secret-ignores-gate.yml`.\n+\n+Two independent signals, defense in depth:\n+\n+ 1. REQUIRED_PATTERNS. Each entry must appear verbatim as an active rule line\n+ in `.gitignore`. A rule line is a non-blank, non-comment line (comment =\n+ first non-whitespace char is `#`). Matching the exact line (rather than a\n+ loose substring across the file) is deliberate: it ignores the comment\n+ prose that discusses these patterns and treats a different-but-similar\n+ rule (e.g. `data/*.key`) as NOT satisfying the `master`-level `*.key` rule.\n+ Removing any required rule line turns the gate red deterministically -- this\n+ is the \"prove it goes red by removing one pattern\" mechanism.\n+\n+ 2. SECRET_PATHS. Each path must be reported as ignored by `git check-ignore`,\n+ i.e. the protection actually takes effect. This catches holes that line\n+ presence cannot (a rule that is present but malformed, or a path that no\n+ longer matches), and is the \"secret-shaped paths are ALL ignored\" check\n+ from tsk-laezfg.\n+\n+Usage:\n+ python scripts/check_secret_ignores.py\n+ python scripts/check_secret_ignores.py --repo-root /path/to/repo\n+\"\"\"\n+from __future__ import annotations\n+\n+import argparse\n+import subprocess\n+import sys\n+from dataclasses import dataclass\n+from pathlib import Path\n+\n+REPO_ROOT = Path(__file__).resolve().parent.parent\n+GITIGNORE_NAME = \".gitignore\"\n+\n+# Protection rules whose absence must fail the gate. These are the secret-\n+# material rules added in response to data/hub/identity.json being committed to\n+# PR #2043 with signing_private and encryption_private in plaintext (#2171,\n+# #2173). Each is matched as an exact active rule line so a dropped rule is\n+# detected even when its text is still mentioned in a comment or covered by a\n+# narrower sibling rule.\n+REQUIRED_PATTERNS = [\n+ \"*.key\",\n+ \"*_private.pem\",\n+ \"*_private.key\",\n+ \"*_private.json\",\n+ \"*_private_key*\",\n+ \"identity.json\",\n+ \"*.p8\",\n+ \"*credentials.json\",\n+ \"*creds*.json\",\n+ \"secrets/\",\n+ \"*.token\",\n+ \"*.cred\",\n+ \"data/.secrets_key\",\n+ \"data/.seeded-agent-tokens.json\",\n+ \"data/secrets.db*\",\n+ \"data/*.key\",\n+ \"data/*.token\",\n+ \"data/hub/\",\n+]\n+\n+# Secret-shaped paths that must actually be ignored by `git check-ignore`. Each\n+# is annotated with its primary protecting rule. Not every path is exclusive\n+# (some are double-protected by design); the REQUIRED_PATTERNS check above is\n+# what makes every single pattern's removal detectable. These paths assert the\n+# protection has real teeth on the branch under test.\n+SECRET_PATHS = [\n+ \"data/hub/identity.json\", # data/hub/ , identity.json\n+ \"identity.json\", # identity.json\n+ \"foo.key\", # *.key\n+ \"x.p8\", # *.p8\n+ \"creds.json\", # *creds*.json\n+ \"y_credentials.json\", # *credentials.json (also *creds*.json)\n+ \"app_private.pem\", # *_private.pem\n+ \"app_private.json\", # *_private.json\n+ \"signing_private_key.pem\", # *_private_key*\n+ \"foo.token\", # *.token\n+ \"foo.cred\", # *.cred\n+ \"secrets/foo.token\", # secrets/\n+ \"data/.secrets_key\", # data/.secrets_key\n+ \"data/secrets.db-wal\", # data/secrets.db*\n+]\n+\n+\n+@dataclass\n+class Violation:\n+ kind: str # \"pattern\" or \"path\"\n+ detail: str\n+\n+\n+def _run_git(args: list[str], repo_root: Path) -> subprocess.CompletedProcess:\n+ return subprocess.run(\n+ [\"git\", *args],\n+ cwd=repo_root,\n+ capture_output=True,\n+ text=True,\n+ )\n+\n+\n+def _read_gitignore(repo_root: Path) -> str:\n+ path = repo_root / GITIGNORE_NAME\n+ if not path.exists():\n+ return \"\"\n+ return path.read_text(encoding=\"utf-8\")\n+\n+\n+def _active_rule_lines(gitignore_text: str) -> list[str]:\n+ \"\"\"Return the active (non-blank, non-comment) rule lines, stripped.\n+\n+ A `.gitignore` rule line is an active rule unless it is blank or its first\n+ non-whitespace character is `#` (a comment). Trailing/leading whitespace is\n+ stripped so cosmetic reformatting does not make the gate trip.\n+ \"\"\"\n+ lines: list[str] = []\n+ for raw in gitignore_text.splitlines():\n+ stripped = raw.strip()\n+ if not stripped or stripped.startswith(\"#\"):\n+ continue\n+ lines.append(stripped)\n+ return lines\n+\n+\n+def check_patterns(gitignore_text: str) -> list[str]:\n+ \"\"\"Return the required patterns absent from the .gitignore text.\"\"\"\n+ active = _active_rule_lines(gitignore_text)\n+ missing: list[str] = []\n+ for pattern in REQUIRED_PATTERNS:\n+ if pattern not in active:\n+ missing.append(pattern)\n+ return missing\n+\n+\n+def is_path_ignored(path: str, repo_root: Path) -> bool:\n+ \"\"\"True if `git check-ignore` reports `path` as ignored on `repo_root`.\"\"\"\n+ result = _run_git([\"check-ignore\", \"--quiet\", path], repo_root)\n+ return result.returncode == 0\n+\n+\n+def check_paths(repo_root: Path) -> list[str]:\n+ \"\"\"Return secret-shaped paths that are NOT ignored on `repo_root`.\"\"\"\n+ not_ignored: list[str] = []\n+ for path in SECRET_PATHS:\n+ if not is_path_ignored(path, repo_root):\n+ not_ignored.append(path)\n+ return not_ignored\n+\n+\n+def check_secret_ignores(repo_root: Path = REPO_ROOT) -> list[Violation]:\n+ \"\"\"Return all violations on `repo_root` (empty == clean).\"\"\"\n+ text = _read_gitignore(repo_root)\n+ violations: list[Violation] = [\n+ Violation(\"pattern\", p) for p in check_patterns(text)\n+ ]\n+ # `git check-ignore` requires a usable git directory; a missing .git is\n+ # treated as \"nothing is ignored\" so every secret path is a violation.\n+ if not is_usable_git_repo(repo_root):\n+ violations.extend(Violation(\"path\", p) for p in SECRET_PATHS)\n+ return violations\n+ violations.extend(Violation(\"path\", p) for p in check_paths(repo_root))\n+ return violations\n+\n+\n+def is_usable_git_repo(repo_root: Path) -> bool:\n+ \"\"\"True if `repo_root` is a git working tree we can check-ignore against.\"\"\"\n+ result = _run_git([\"rev-parse\", \"--is-inside-work-tree\"], repo_root)\n+ return result.returncode == 0 and result.stdout.strip() == \"true\"\n+\n+\n+def main(argv: list[str] | None = None) -> int:\n+ parser = argparse.ArgumentParser(description=__doc__)\n+ parser.add_argument(\n+ \"--repo-root\",\n+ default=str(REPO_ROOT),\n+ help=\"Repository root whose .gitignore to check (default: this checkout).\",\n+ )\n+ args = parser.parse_args(argv)\n+ repo_root = Path(args.repo_root)\n+\n+ violations = check_secret_ignores(repo_root)\n+ if not violations:\n+ print(\"secret-ignores-guard: clean\")\n+ return 0\n+\n+ patterns = sorted(v.detail for v in violations if v.kind == \"pattern\")\n+ paths = sorted(v.detail for v in violations if v.kind == \"path\")\n+ if patterns:\n+ print(\"SECRET-IGNORE FAIL: .gitignore is missing required protection patterns:\")\n+ for p in patterns:\n+ print(f\" - {p}\")\n+ if paths:\n+ print(\"SECRET-IGNORE FAIL: these secret-shaped paths would NOT be ignored:\")\n+ for p in paths:\n+ print(f\" - {p}\")\n+ return 1\n+\n+\n+if __name__ == \"__main__\":\n+ sys.exit(main())", "status": "added"}, {"additions": 171, "deletions": 0, "filename": "tests/test_check_secret_ignores.py", "patch": "@@ -0,0 +1,171 @@\n+\"\"\"Tests for the secret-material ignore guard (scripts/check_secret_ignores.py).\n+\n+The guard asserts two things on the branch under test:\n+ 1. Every REQUIRED_PATTERN appears as an exact active rule line in .gitignore.\n+ 2. Every SECRET_PATH is reported ignored by `git check-ignore`.\n+\n+The headline guarantee from tsk-laezfg is \"PROVEN to fail when a pattern is\n+removed\": a parametrized test builds a synthetic repo from a copy of the real\n+.gitignore, drops ONE required pattern line, and asserts the guard goes red. A\n+companion real-tree test asserts the committed .gitignore on this branch is\n+green, so the gate is a live regression guard and not dead code.\n+\"\"\"\n+from __future__ import annotations\n+\n+import subprocess\n+import sys\n+from pathlib import Path\n+\n+import pytest\n+\n+# scripts/ is not a package; make it importable like the other scripts/*.py\n+# gate tests (see tests/test_check_deleted_symbols.py).\n+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / \"scripts\"))\n+import check_secret_ignores as csi # noqa: E402\n+\n+REPO_ROOT = Path(__file__).resolve().parent.parent\n+REAL_GITIGNORE = REPO_ROOT / \".gitignore\"\n+\n+\n+def _git(repo: Path, *args: str) -> None:\n+ subprocess.run([\"git\", *args], cwd=repo, capture_output=True, text=True, check=True)\n+\n+\n+def _init_repo(repo: Path) -> None:\n+ repo.mkdir(parents=True, exist_ok=True)\n+ _git(repo, \"init\")\n+ _git(repo, \"config\", \"user.name\", \"Test\")\n+ _git(repo, \"config\", \"user.email\", \"test@test.com\")\n+ _git(repo, \"config\", \"commit.gpgsign\", \"false\")\n+ # No inherited global/system ignores -- the only ignores in the synthetic\n+ # repo come from the .gitignore we write, so the gate's path assertions stay\n+ # deterministic.\n+ _git(repo, \"config\", \"core.excludesFile\", \"/dev/null\")\n+ _git(repo, \"branch\", \"-M\", \"main\")\n+\n+\n+def _commit_gitignore(repo: Path, text: str) -> None:\n+ (repo / \".gitignore\").write_text(text, encoding=\"utf-8\")\n+ _git(repo, \"add\", \".gitignore\")\n+ _git(repo, \"commit\", \"-m\", \"gitignore\")\n+\n+\n+def _gitignore_without(text: str, pattern: str) -> str:\n+ \"\"\"Return `text` with the exact active rule line `pattern` removed.\"\"\"\n+ kept: list[str] = []\n+ for raw in text.splitlines():\n+ if raw.strip() == pattern:\n+ continue\n+ kept.append(raw)\n+ return \"\\n\".join(kept) + (\"\\n\" if text.endswith(\"\\n\") else \"\")\n+\n+\n+# ---------------------------------------------------------------------------\n+# Pattern-presence check (pure, no git)\n+# ---------------------------------------------------------------------------\n+\n+\n+class TestCheckPatterns:\n+ def test_active_rule_lines_drops_comments_and_blanks(self):\n+ text = (\n+ \"# a comment *.key\\n\"\n+ \"\\n\"\n+ \" *.key \\n\"\n+ \"data/hub/\\n\"\n+ )\n+ assert csi._active_rule_lines(text) == [\"*.key\", \"data/hub/\"]\n+\n+ def test_all_required_patterns_present_on_real_tree(self):\n+ text = REAL_GITIGNORE.read_text(encoding=\"utf-8\")\n+ assert csi.check_patterns(text) == []\n+\n+ @pytest.mark.parametrize(\"pattern\", csi.REQUIRED_PATTERNS)\n+ def test_removing_a_single_pattern_is_detected(self, pattern: str):\n+ \"\"\"Dropping ONE required rule line turns the pattern check red for\n+ exactly that pattern -- this is the core 'remove a pattern -> red'\n+ proof, run against every required pattern.\"\"\"\n+ text = _gitignore_without(REAL_GITIGNORE.read_text(encoding=\"utf-8\"), pattern)\n+ missing = csi.check_patterns(text)\n+ assert missing == [pattern]\n+\n+ def test_comment_mention_does_not_satisfy_a_pattern(self):\n+ \"\"\"A pattern name in a comment (#-prefixed) must not count as present.\"\"\"\n+ text = \"# *.key is for key material\\ndata/hub/\\n\"\n+ assert \"data/hub/\" not in csi.check_patterns(text)\n+ assert \"*.key\" in csi.check_patterns(text)\n+\n+ def test_narrow_rule_does_not_satisfy_a_root_rule(self):\n+ \"\"\"`data/*.key` must not satisfy the master-level `*.key` rule, and vice\n+ versa -- matching is exact-line, not substring.\"\"\"\n+ assert \"*.key\" in csi.check_patterns(\"data/*.key\\n\")\n+ assert \"data/*.key\" in csi.check_patterns(\"*.key\\n\")\n+\n+ def test_missing_gitignore_reports_all_patterns(self):\n+ assert set(csi.REQUIRED_PATTERNS).issubset(set(csi.check_patterns(\"\")))\n+\n+\n+# ---------------------------------------------------------------------------\n+# Path-check (git check-ignore), integration with synthetic repos\n+# ---------------------------------------------------------------------------\n+\n+\n+class TestCheckPaths:\n+ def test_secret_paths_ignored_on_real_gitignore(self, tmp_path: Path):\n+ repo = tmp_path / \"repo\"\n+ _init_repo(repo)\n+ _commit_gitignore(repo, REAL_GITIGNORE.read_text(encoding=\"utf-8\"))\n+ assert csi.check_paths(repo) == []\n+\n+ def test_path_not_ignored_when_pattern_removed(self, tmp_path: Path):\n+ repo = tmp_path / \"repo\"\n+ _init_repo(repo)\n+ text = _gitignore_without(\n+ REAL_GITIGNORE.read_text(encoding=\"utf-8\"), \"*.key\"\n+ )\n+ _commit_gitignore(repo, text)\n+ assert \"foo.key\" in csi.check_paths(repo)\n+\n+ def test_path_under_ignored_dir_is_ignored(self, tmp_path: Path):\n+ repo = tmp_path / \"repo\"\n+ _init_repo(repo)\n+ _commit_gitignore(repo, \"data/hub/\\nidentity.json\\n\")\n+ assert csi.is_path_ignored(\"data/hub/identity.json\", repo)\n+\n+\n+# ---------------------------------------------------------------------------\n+# Full guard: green on the real tree, red on a single removed pattern\n+# ---------------------------------------------------------------------------\n+\n+\n+class TestCheckSecretIgnores:\n+ def test_real_tree_passes(self):\n+ assert csi.check_secret_ignores(REPO_ROOT) == []\n+\n+ @pytest.mark.parametrize(\"pattern\", csi.REQUIRED_PATTERNS)\n+ def test_real_gitignore_minus_one_pattern_fails(self, tmp_path: Path, pattern: str):\n+ \"\"\"PROVEN red: copy the committed .gitignore, drop ONE required pattern,\n+ and the guard must report a violation.\"\"\"\n+ repo = tmp_path / \"repo\"\n+ _init_repo(repo)\n+ text = _gitignore_without(REAL_GITIGNORE.read_text(encoding=\"utf-8\"), pattern)\n+ _commit_gitignore(repo, text)\n+\n+ violations = csi.check_secret_ignores(repo)\n+\n+ pattern_violations = [v for v in violations if v.kind == \"pattern\"]\n+ assert pattern_violations, f\"removing {pattern!r} did not trip the pattern guard\"\n+ assert any(v.detail == pattern for v in pattern_violations)\n+\n+ def test_real_gitignore_missing_key_makes_foo_key_unignored(\n+ self, tmp_path: Path\n+ ):\n+ repo = tmp_path / \"repo\"\n+ _init_repo(repo)\n+ text = _gitignore_without(REAL_GITIGNORE.read_text(encoding=\"utf-8\"), \"*.key\")\n+ _commit_gitignore(repo, text)\n+\n+ violations = csi.check_secret_ignores(repo)\n+\n+ details = {v.detail for v in violations}\n+ assert \"*.key\" in details\n+ assert \"foo.key\" in details", "status": "added"}], "message": "chore(security): gate .gitignore secret ignores on master/dev/release/*\n\nAdd scripts/check_secret_ignores.py, which asserts that the committed\n.gitignore (a) still contains every required secret-protection rule as an\nactive line and (b) ignores a canonical set of secret-shaped paths\n(data/hub/identity.json, foo.key, creds.json, x.p8, y_credentials.json, ...)\nvia git check-ignore. Covered by tests/test_check_secret_ignores.py,\nincluding a parametrized test that drops each required pattern from a copy of\nthe real .gitignore and proves the guard goes red, plus a real-tree\nregression asserting this branch is green.\n\n.github/workflows/secret-ignores-gate.yml runs the guard on push and PR to\nmaster, dev, and release/*, so a dropped pattern fails the branch it lands on\nrather than being assumed during dev->master promotion.\n\nDocs: Secret-ignores gate section in the contributor skill and a\npost-promotion verification step in docs/RELEASING.md. Changelog fragment\nadded.\n\nRefs tsk-laezfg.", "sha": "35d95980d1d702c382a2663e6e66e7cd873a8cc6"}], "post_review_commits": ["8c5c036818bf712b54fd9c2a2c8083c3c0685ec2", "acf89f337438fa252decc0fcac460c6077c228af"], "pr_author": "jaylfc", "pr_title": "VERIFY at next release: secret-material .gitignore is dev-ONLY, master has NO protection", "repo_name": "jaylfc/taOS"}, "repo": "jaylfc/taOS", "snapshot": "snapshots/71152d589a50d05f66a2a1943d5a49d55e1cad89919e67698123cf0d2ad39208.pack", "split": "rl", "task_id": "51e5c467d7e987e613dd54cf2b964bc398eb9f5884f2555f705076cf40d61feb"} {"base_sha": "7b3eb8406c054212bccdb5615ea4fcf9c9f867a5", "cohort": null, "context": {"canonical_pr_url": "https://github.com/tony-defa/swarm-cluster/pull/29", "id": "531a870e7efc44d8b44deb3c1abfd60c16d3baa63fc202402bb39cdc0c9bf8a6", "preparation_mode": "source-only", "snapshot": {"base_ref": "7b3eb8406c054212bccdb5615ea4fcf9c9f867a5", "base_sha": "7b3eb8406c054212bccdb5615ea4fcf9c9f867a5", "body": "", "head_ref": "f6ff392d4ca6a4b46b9ee0027d1071ee81a7d910", "head_sha": "f6ff392d4ca6a4b46b9ee0027d1071ee81a7d910", "name": "swarm-cluster", "number": 29, "owner": "tony-defa", "pr_url": "https://github.com/tony-defa/swarm-cluster/pull/29", "title": ""}}, "head_sha": "f6ff392d4ca6a4b46b9ee0027d1071ee81a7d910", "metadata": {"group_id": "a04661cfe379b896ff8780ade8e3ffefa6c5fa57a5a5319c229186a5f87a7856", "snapshot": {"base_sha": "7b3eb8406c054212bccdb5615ea4fcf9c9f867a5", "external_requirements": [], "head_sha": "f6ff392d4ca6a4b46b9ee0027d1071ee81a7d910", "objects": 221, "objects_sha256": "32270001d34e4f98d5086b1f74ffdabd7619de1fcce1aec1a92642947ad0fa64", "patch_sha256": "b4ac684d8c56363e5b05e70c27a73fecde568419b5d0f288b39cdb470ad38025"}}, "pr_number": 29, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "33b65380ed98", "description": "The CalRS service did not receive CALRS_BASE_URL, so its OIDC redirect URIs and email links could point to the wrong host despite the variable being present in the example configuration.", "file_path": "apps/calrs/calrs.yml"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "33b65380ed98", "description": "The persistent CalRS SQLite database had no backup service, leaving its data without scheduled backups or retention.", "file_path": "apps/calrs/calrs.yml"}, {"action_id": "A3", "action_type": "improvement", "category": "documentation", "commit_sha": "33b65380ed98", "description": "The example environment file lacked the host backup path, backup frequency, and retention settings needed to configure the new backup service.", "file_path": "apps/calrs/example.env"}, {"action_id": "A4", "action_type": "improvement", "category": "documentation", "commit_sha": "33b65380ed98", "description": "The CalRS README did not explain how the SQLite backup service works or which settings control its interval and retention.", "file_path": "apps/calrs/README.md"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "64f1a6808ee7", "description": "Host directories created for stack volumes were assigned to the docker group but were not made group-writable, which could prevent group members from writing to them.", "file_path": "deploy-stack.sh"}], "commits_under_review": [{"author": "kilo-code-bot[bot]", "date": "2026-08-02T12:41:31Z", "files": [{"additions": 26, "deletions": 0, "filename": "apps/calrs/README.md", "patch": "@@ -0,0 +1,26 @@\n+# CalRS\n+\n+Fast, self-hostable scheduling platform. Like Cal.com, but written in Rust. CalRS connects to CalDAV calendars, defines bookable meeting types, and shares a link for scheduling.\n+\n+### `calrs.yml`\n+This file defines the Docker Compose stack for CalRS. It includes the CalRS service, a volume for persistent SQLite data, and network configuration to connect to the Traefik proxy.\n+\n+## Prerequisites\n+### Storage\n+A centralized storage solution is required.\n+\n+### Service dependencies\n+Mandatory stacks are:\n+- `system/traefik.yml`\n+\n+### Create pre-configured data folder\n+No pre-configured data folder available.\n+\n+### Create docker secrets\n+No docker secrets are required.\n+\n+### Create network\n+No network needs to be created.\n+\n+## Other notes\n+CalRS uses SQLite for storage, which is a single-file database located at `/var/lib/calrs`. The `CALRS_BASE_URL` environment variable must be set to the public URL of the service (e.g., `https://cal.example.com`) so that OIDC redirect URIs and email links point to the correct host.\n\\ No newline at end of file", "status": "added"}, {"additions": 37, "deletions": 0, "filename": "apps/calrs/calrs.yml", "patch": "@@ -0,0 +1,37 @@\n+x-default-opts: &default-opts\n+ env_file:\n+ .env\n+ logging:\n+ options:\n+ max-size: \"1m\"\n+\n+services:\n+ calrs:\n+ <<: *default-opts\n+ image: ghcr.io/olivierlambert/calrs:${CALRS_TAG}\n+ volumes:\n+ - data:/var/lib/calrs\n+ networks:\n+ - proxy_network\n+ deploy:\n+ replicas: 1\n+ restart_policy:\n+ condition: on-failure\n+ labels:\n+ traefik.enable: \"true\"\n+ traefik.http.routers.calrs.entrypoints: ${ENTRYPOINT:-websecure}\n+ traefik.http.routers.calrs.rule: Host(`${DOMAIN:-calrs.host.local}`)\n+ traefik.http.routers.calrs.service: calrs\n+ traefik.http.services.calrs.loadbalancer.server.port: 3000\n+\n+networks:\n+ proxy_network:\n+ external: true\n+\n+volumes:\n+ data:\n+ driver: local\n+ driver_opts:\n+ device: ${HOST_CALRS_DATA}\n+ type: none\n+ o: bind\n\\ No newline at end of file", "status": "added"}, {"additions": 12, "deletions": 0, "filename": "apps/calrs/example.env", "patch": "@@ -0,0 +1,12 @@\n+# Host volume paths\n+HOST_CALRS_DATA=/cluster/calrs_data/data\n+\n+# Image tags\n+CALRS_TAG=latest\n+\n+# Proxy configuration\n+ENTRYPOINT=\n+DOMAIN=\n+\n+# CalRS configuration\n+CALRS_BASE_URL=https://calrs.host.local\n\\ No newline at end of file", "status": "added"}], "message": "feat(calrs): add calrs application", "sha": "f6ff392d4ca6a4b46b9ee0027d1071ee81a7d910"}], "post_review_commits": ["501a92a42348f877e076d98d27487434b29922e4", "33b65380ed98bca4c82df1f9d5d379fc508041f2", "64f1a6808ee7bbc94b621e570cc8e663ed0c2dae"], "pr_author": "kilo-code-bot[bot]", "pr_title": "Fix #28: Add CalRS stack", "repo_name": "tony-defa/swarm-cluster"}, "repo": "tony-defa/swarm-cluster", "snapshot": "snapshots/a04661cfe379b896ff8780ade8e3ffefa6c5fa57a5a5319c229186a5f87a7856.pack", "split": "rl", "task_id": "531a870e7efc44d8b44deb3c1abfd60c16d3baa63fc202402bb39cdc0c9bf8a6"} {"base_sha": "ab5a6173255b7da0060c8b9926b06c533118982d", "cohort": null, "context": {"canonical_pr_url": "https://github.com/komi-store/komi-store/pull/584", "id": "54f7cd4f49207f1420d60cb22040debe30eb709a3ae72138fa5ebbd30f2a8ba4", "preparation_mode": "source-only", "snapshot": {"base_ref": "ab5a6173255b7da0060c8b9926b06c533118982d", "base_sha": "ab5a6173255b7da0060c8b9926b06c533118982d", "body": "", "head_ref": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89", "head_sha": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89", "name": "komi-store", "number": 584, "owner": "komi-store", "pr_url": "https://github.com/komi-store/komi-store/pull/584", "title": ""}}, "head_sha": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89", "metadata": {"group_id": "5399060ac05b2b5919487531c5f3fd146d87bfac32a5f20104bb33b0b05d4d28", "snapshot": {"base_sha": "ab5a6173255b7da0060c8b9926b06c533118982d", "external_requirements": [], "head_sha": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89", "objects": 1577, "objects_sha256": "d710e00b5c8e252674eeb20578be35c47aa51561cb5395d2b48e8b3439b17dec", "patch_sha256": "e4b19b33f181a28bbbf1af3a67f59cf1a91dc63221b2db53b096440d92bd3d37"}}, "pr_number": 584, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "performance", "commit_sha": "10e2204b85c9", "description": "Home fetched the current user from ProfileRepository during repository mapping, repeatedly accessing its suspend cache and DataStore.", "file_path": "feature/home/presentation/src/commonMain/kotlin/zed/rainxch/home/presentation/HomeViewModel.kt"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "10e2204b85c9", "description": "Already-loaded Home repositories retained stale self-owned badges after login, logout, or account switching until they were reloaded.", "file_path": "feature/home/presentation/src/commonMain/kotlin/zed/rainxch/home/presentation/HomeViewModel.kt"}, {"action_id": "A3", "action_type": "improvement", "category": "performance", "commit_sha": "10e2204b85c9", "description": "Search fetched the current user again while mapping paginated and explore results, repeatedly accessing ProfileRepository's suspend cache and DataStore.", "file_path": "feature/search/presentation/src/commonMain/kotlin/zed/rainxch/search/presentation/SearchViewModel.kt"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "10e2204b85c9", "description": "Already-loaded Search results retained stale self-owned badges after login, logout, or account switching until they were reloaded.", "file_path": "feature/search/presentation/src/commonMain/kotlin/zed/rainxch/search/presentation/SearchViewModel.kt"}, {"action_id": "A5", "action_type": "new_feature", "category": "other", "commit_sha": "2546d942de40", "description": "Repository details did not show a self-owned badge beside the owner, including when the signed-in user or loaded repository changed.", "file_path": "feature/details/presentation/src/commonMain/kotlin/zed/rainxch/details/presentation/components/AppHeader.kt"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "bd84f0854a86", "description": "The DetailsViewModel dependency-injection factory did not supply its newly required ProfileRepository constructor argument, preventing the updated view model from being constructed.", "file_path": "composeApp/src/commonMain/kotlin/zed/rainxch/githubstore/app/di/ViewModelsModule.kt"}, {"action_id": "A7", "action_type": "new_feature", "category": "other", "commit_sha": "af794e19486e", "description": "Starred repository items did not indicate when the signed-in user owned the repository or update that indication when the user changed.", "file_path": "feature/starred/presentation/src/commonMain/kotlin/zed/rainxch/starred/presentation/StarredReposViewModel.kt"}, {"action_id": "A8", "action_type": "new_feature", "category": "other", "commit_sha": "3903cf9ce9b8", "description": "Favourite repository items did not indicate when the signed-in user owned the repository or update that indication when the user changed.", "file_path": "feature/favourites/presentation/src/commonMain/kotlin/zed/rainxch/favourites/presentation/FavouritesViewModel.kt"}, {"action_id": "A9", "action_type": "fix", "category": "bug", "commit_sha": "3a02b7bec8c4", "description": "A long owner login could consume the entire RepositoryCard row width, leaving no space to render the self-owned badge.", "file_path": "core/presentation/src/commonMain/kotlin/zed/rainxch/core/presentation/components/RepositoryCard.kt"}], "commits_under_review": [{"author": "rainxchzed", "date": "2026-05-12T13:40:54Z", "files": [{"additions": 16, "deletions": 0, "filename": "core/presentation/src/commonMain/kotlin/zed/rainxch/core/presentation/components/RepositoryCard.kt", "patch": "@@ -18,6 +18,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape\n import androidx.compose.material.icons.Icons\n import androidx.compose.material.icons.automirrored.outlined.CallSplit\n import androidx.compose.material.icons.filled.CheckCircle\n+import androidx.compose.material.icons.filled.Verified\n import androidx.compose.material.icons.filled.Favorite\n import androidx.compose.material.icons.filled.OpenInBrowser\n import androidx.compose.material.icons.filled.Share\n@@ -63,6 +64,7 @@ import zed.rainxch.githubstore.core.presentation.res.home_view_details\n import zed.rainxch.githubstore.core.presentation.res.installed\n import zed.rainxch.githubstore.core.presentation.res.open_in_browser\n import zed.rainxch.githubstore.core.presentation.res.seen_badge\n+import zed.rainxch.githubstore.core.presentation.res.self_owned_badge\n import zed.rainxch.githubstore.core.presentation.res.share_repository\n import zed.rainxch.githubstore.core.presentation.res.update_available\n \n@@ -151,6 +153,10 @@ fun RepositoryCard(\n softWrap = false,\n overflow = TextOverflow.Ellipsis,\n )\n+\n+ if (discoveryRepositoryUi.isCurrentUserOwner) {\n+ OfficialBadge()\n+ }\n }\n \n Text(\n@@ -455,6 +461,16 @@ fun InstallStatusBadge(\n }\n }\n \n+@Composable\n+fun OfficialBadge(modifier: Modifier = Modifier) {\n+ Icon(\n+ imageVector = Icons.Filled.Verified,\n+ contentDescription = stringResource(Res.string.self_owned_badge),\n+ modifier = modifier.size(16.dp),\n+ tint = MaterialTheme.colorScheme.primary,\n+ )\n+}\n+\n @Composable\n fun SeenBadge(modifier: Modifier = Modifier) {\n Surface(", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/kotlin/zed/rainxch/core/presentation/model/DiscoveryRepositoryUi.kt", "patch": "@@ -6,5 +6,6 @@ data class DiscoveryRepositoryUi(\n val isFavourite: Boolean,\n val isStarred: Boolean,\n val isSeen: Boolean = false,\n+ val isCurrentUserOwner: Boolean = false,\n val repository: GithubRepoSummaryUi,\n )", "status": "modified"}], "message": "feat(presentation): OfficialBadge composable for self-owned repos", "sha": "1d75a4ffd73ce88737ab8387e89fd38205825187"}, {"author": "rainxchzed", "date": "2026-05-12T13:41:01Z", "files": [{"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-ar/strings-ar.xml", "patch": "@@ -644,6 +644,7 @@\n إعادة تعيين جميع المستودعات المشاهَدة لتظهر مجدداً في الخلاصات\n تم مسح سجل المشاهدة\n تمت المشاهدة\n+ هذا المستودع لك\n الخصوصية\n ساعد في تحسين البحث\n مشاركة بيانات الاستخدام (عمليات البحث والتثبيتات والتفاعلات) المرتبطة بمعرّف تحليلي قابل لإعادة التعيين. لا تتم مشاركة تفاصيل الحساب.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-bn/strings-bn.xml", "patch": "@@ -643,6 +643,7 @@\n সমস্ত দেখা রিপোজিটরি রিসেট করুন যাতে সেগুলো ফিডে আবার দেখা যায়\n দেখার ইতিহাস মুছে ফেলা হয়েছে\n দেখা হয়েছে\n+ এই রিপো আপনার\n গোপনীয়তা\n অনুসন্ধান উন্নত করতে সহায়তা করুন\n পুনরায় সেট করা যায় এমন একটি বিশ্লেষণ আইডির সাথে যুক্ত ব্যবহার ডেটা (অনুসন্ধান, ইনস্টল, ইন্টারঅ্যাকশন) শেয়ার করুন। অ্যাকাউন্ট বিবরণ শেয়ার করা হয় না।", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-es/strings-es.xml", "patch": "@@ -604,6 +604,7 @@\n Restablecer todos los repositorios vistos para que aparezcan de nuevo en las fuentes\n Historial de vistos borrado\n Visto\n+ Eres dueño de este repo\n Privacidad\n Ayudar a mejorar la búsqueda\n Compartir datos de uso (búsquedas, instalaciones, interacciones) asociados a un ID de análisis restablecible. No se comparten detalles de la cuenta.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-fr/strings-fr.xml", "patch": "@@ -605,6 +605,7 @@\n Réinitialiser tous les dépôts consultés pour qu'ils réapparaissent dans les flux\n Historique des consultations effacé\n Consulté\n+ Vous possédez ce dépôt\n Confidentialité\n Aider à améliorer la recherche\n Partager des données d'utilisation (recherches, installations, interactions) associées à un identifiant d'analyse réinitialisable. Aucun détail de compte n'est partagé.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-hi/strings-hi.xml", "patch": "@@ -642,6 +642,7 @@\n सभी देखे गए रिपॉजिटरी रीसेट करें ताकि वे फ़ीड में फिर से दिखें\n देखने का इतिहास साफ़ किया गया\n देखा गया\n+ यह रेपो आपका है\n गोपनीयता\n खोज को बेहतर बनाने में मदद करें\n रीसेट करने योग्य एनालिटिक्स आईडी से जुड़े उपयोग डेटा (खोज, इंस्टॉल, इंटरैक्शन) साझा करें। खाता विवरण साझा नहीं किए जाते।", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-it/strings-it.xml", "patch": "@@ -643,6 +643,7 @@\n Reimposta tutti i repository visualizzati in modo che ricompaiano nei feed\n Cronologia visualizzazioni cancellata\n Visualizzato\n+ Sei il proprietario di questo repo\n Privacy\n Aiuta a migliorare la ricerca\n Condividi dati di utilizzo (ricerche, installazioni, interazioni) associati a un ID analitico ripristinabile. Nessun dettaglio dell'account viene condiviso.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-ja/strings-ja.xml", "patch": "@@ -606,6 +606,7 @@\n すべての閲覧済みリポジトリをリセットしてフィードに再表示します\n 閲覧履歴をクリアしました\n 閲覧済み\n+ あなたが所有するリポジトリ\n プライバシー\n 検索の改善に協力\n リセット可能な分析 ID に関連付けられた使用データ(検索、インストール、操作)を共有します。アカウント情報は共有されません。", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-ko/strings-ko.xml", "patch": "@@ -641,6 +641,7 @@\n 모든 조회 기록을 초기화하여 피드에 다시 표시합니다\n 조회 기록이 삭제되었습니다\n 확인함\n+ 내가 소유한 저장소\n 개인 정보 보호\n 검색 개선에 도움 주기\n 재설정 가능한 분석 ID에 연결된 사용 데이터(검색, 설치, 상호작용)를 공유합니다. 계정 정보는 공유되지 않습니다.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-pl/strings-pl.xml", "patch": "@@ -607,6 +607,7 @@\n Zresetuj wszystkie przeglądane repozytoria, aby ponownie pojawiły się w kanałach\n Historia przeglądania wyczyszczona\n Przeglądane\n+ Jesteś właścicielem tego repo\n Prywatność\n Pomóż ulepszyć wyszukiwanie\n Udostępniaj dane o użyciu (wyszukiwania, instalacje, interakcje) powiązane z resetowalnym identyfikatorem analitycznym. Żadne dane konta nie są udostępniane.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-ru/strings-ru.xml", "patch": "@@ -607,6 +607,7 @@\n Сбросить все просмотренные репозитории, чтобы они снова появились в лентах\n История просмотров очищена\n Просмотрено\n+ Ваш репозиторий\n Конфиденциальность\n Помочь улучшить поиск\n Отправлять данные об использовании (поиски, установки, взаимодействия), связанные со сбрасываемым идентификатором аналитики. Данные учётной записи не передаются.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-tr/strings-tr.xml", "patch": "@@ -641,6 +641,7 @@\n Tüm görüntülenen depoları sıfırlayarak akışlarda tekrar görünmelerini sağlayın\n Görüntüleme geçmişi temizlendi\n Görüntülendi\n+ Bu deponun sahibisin\n Gizlilik\n Aramayı iyileştirmeye yardım et\n Sıfırlanabilir bir analiz kimliğiyle ilişkilendirilmiş kullanım verilerini (aramalar, yüklemeler, etkileşimler) paylaş. Hesap ayrıntıları paylaşılmaz.", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values-zh-rCN/strings-zh-rCN.xml", "patch": "@@ -607,6 +607,7 @@\n 重置所有已浏览的仓库,使其重新出现在信息流中\n 浏览记录已清除\n 已浏览\n+ 你拥有此仓库\n 隐私\n 帮助改进搜索\n 分享与可重置分析 ID 关联的使用数据(搜索、安装、交互)。不分享账户详情。", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "core/presentation/src/commonMain/composeResources/values/strings.xml", "patch": "@@ -767,6 +767,7 @@\n Reset all seen repositories so they appear again in feeds\n Seen history cleared\n Viewed\n+ You own this repo\n \n \n Privacy", "status": "modified"}], "message": "chore(strings): self_owned_badge across 13 locales", "sha": "be4cf5644c05971df55c7266619ab18ecef5898e"}, {"author": "rainxchzed", "date": "2026-05-12T13:41:07Z", "files": [{"additions": 1, "deletions": 0, "filename": "feature/home/presentation/build.gradle.kts", "patch": "@@ -11,6 +11,7 @@ kotlin {\n implementation(projects.core.domain)\n implementation(projects.core.presentation)\n implementation(projects.feature.home.domain)\n+ implementation(projects.feature.profile.domain)\n \n implementation(libs.kotlinx.collections.immutable)\n ", "status": "modified"}, {"additions": 6, "deletions": 0, "filename": "feature/home/presentation/src/commonMain/kotlin/zed/rainxch/home/presentation/HomeViewModel.kt", "patch": "@@ -39,6 +39,7 @@ import zed.rainxch.home.domain.model.HomeCategory\n import zed.rainxch.home.domain.model.TopicCategory\n import zed.rainxch.home.domain.repository.HomeRepository\n import zed.rainxch.home.presentation.HomeEvent.*\n+import zed.rainxch.profile.domain.repository.ProfileRepository\n \n class HomeViewModel(\n private val homeRepository: HomeRepository,\n@@ -51,6 +52,7 @@ class HomeViewModel(\n private val shareManager: ShareManager,\n private val tweaksRepository: TweaksRepository,\n private val seenReposRepository: SeenReposRepository,\n+ private val profileRepository: ProfileRepository,\n ) : ViewModel() {\n private var hasLoadedInitialData = false\n private var currentJob: Job? = null\n@@ -366,6 +368,7 @@ class HomeViewModel(\n .associateBy { it.repoId }\n \n val seenIds = _state.value.seenRepoIds\n+ val currentLogin = profileRepository.getUser().first()?.username\n \n return repos.map { repo ->\n val apps = installedAppsMap[repo.id].orEmpty()\n@@ -377,6 +380,9 @@ class HomeViewModel(\n isFavourite = favourite != null,\n isStarred = starred != null,\n isSeen = repo.id in seenIds,\n+ isCurrentUserOwner =\n+ currentLogin != null &&\n+ repo.owner.login.equals(currentLogin, ignoreCase = true),\n isUpdateAvailable = apps.any { it.hasActualUpdate() },\n repository = repo.toUi(),\n )", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "feature/search/presentation/build.gradle.kts", "patch": "@@ -11,6 +11,7 @@ kotlin {\n implementation(projects.core.domain)\n implementation(projects.core.presentation)\n implementation(projects.feature.search.domain)\n+ implementation(projects.feature.profile.domain)\n \n \n implementation(libs.androidx.compose.ui.tooling.preview)", "status": "modified"}, {"additions": 10, "deletions": 0, "filename": "feature/search/presentation/src/commonMain/kotlin/zed/rainxch/search/presentation/SearchViewModel.kt", "patch": "@@ -36,6 +36,7 @@ import zed.rainxch.core.domain.utils.ShareManager\n import zed.rainxch.core.presentation.model.DiscoveryRepositoryUi\n import zed.rainxch.core.presentation.utils.toUi\n import zed.rainxch.domain.repository.SearchRepository\n+import zed.rainxch.profile.domain.repository.ProfileRepository\n import zed.rainxch.githubstore.core.presentation.res.Res\n import zed.rainxch.githubstore.core.presentation.res.failed_to_share_link\n import zed.rainxch.githubstore.core.presentation.res.link_copied_to_clipboard\n@@ -63,6 +64,7 @@ class SearchViewModel(\n private val seenReposRepository: SeenReposRepository,\n private val searchHistoryRepository: SearchHistoryRepository,\n private val telemetryRepository: TelemetryRepository,\n+ private val profileRepository: ProfileRepository,\n ) : ViewModel() {\n private var hasLoadedInitialData = false\n private var currentSearchJob: Job? = null\n@@ -349,6 +351,7 @@ class SearchViewModel(\n currentPage = paginatedRepos.nextPageIndex\n \n val seenIds = _state.value.seenRepoIds\n+ val currentLogin = profileRepository.getUser().first()?.username\n \n val newReposWithStatus =\n paginatedRepos.repos.map { repo ->\n@@ -361,6 +364,9 @@ class SearchViewModel(\n isFavourite = favourite != null,\n isStarred = starred != null,\n isSeen = repo.id in seenIds,\n+ isCurrentUserOwner =\n+ currentLogin != null &&\n+ repo.owner.login.equals(currentLogin, ignoreCase = true),\n isUpdateAvailable = apps.any { it.hasActualUpdate() },\n repository = repo.toUi(),\n )\n@@ -772,6 +778,7 @@ class SearchViewModel(\n val favoritesMap = favouritesRepository.getAllFavorites().first().associateBy { it.repoId }\n val starredMap = starredRepository.getAllStarred().first().associateBy { it.repoId }\n val seenIds = _state.value.seenRepoIds\n+ val currentLogin = profileRepository.getUser().first()?.username\n \n val existingIds = _state.value.repositories.map { it.repository.id }.toSet()\n \n@@ -784,6 +791,9 @@ class SearchViewModel(\n isFavourite = favoritesMap[repo.id] != null,\n isStarred = starredMap[repo.id] != null,\n isSeen = repo.id in seenIds,\n+ isCurrentUserOwner =\n+ currentLogin != null &&\n+ repo.owner.login.equals(currentLogin, ignoreCase = true),\n isUpdateAvailable = apps.any { it.hasActualUpdate() },\n repository = repo.toUi(),\n )", "status": "modified"}], "message": "feat(home,search): compute isCurrentUserOwner via ProfileRepository", "sha": "a8b57037a215d8768745aebeda74598e2f78ea7b"}, {"author": "rainxchzed", "date": "2026-05-12T13:41:20Z", "files": [{"additions": 2, "deletions": 1, "filename": "core/presentation/src/commonMain/composeResources/files/whatsnew/17.json", "patch": "@@ -10,7 +10,8 @@\n \"Ignore updates per app — silence the update badge for any app you don't want to update.\",\n \"Skip a specific update — dismiss a single release if it's a false-positive prompt; you'll be re-notified when a newer one lands.\",\n \"Silent install via root — Magisk, KernelSU, and APatch users can now install without Shizuku or Dhizuku.\",\n- \"Search in Starred and Favourites — quickly filter long lists by repo name, owner, description, or language.\"\n+ \"Search in Starred and Favourites — quickly filter long lists by repo name, owner, description, or language.\",\n+ \"Self-owned ✓ badge — when you're signed in, repos you own get a verified checkmark on Home and Search cards.\"\n ]\n },\n {", "status": "modified"}], "message": "chore(whatsnew): note self-owned ✓ badge", "sha": "5f3de6d10a682dff8456e0b4e416e872d2a9ad89"}], "post_review_commits": ["10e2204b85c9274622c04df54a6a6ca19eefa7f3", "2546d942de40790963ee6166db116769557fd850", "bd84f0854a867461762f752a5e2967443ccf3ab1", "af794e19486eec2bf47e1756f6ec379b6b7cd6e3", "3903cf9ce9b89778fd67e656d35a847e69e6733b", "3a02b7bec8c4ea4037bf678094b4f975e69855e9"], "pr_author": "rainxchzed", "pr_title": "feat(e20): self-owned ✓ badge on Home + Search cards", "repo_name": "komi-store/komi-store"}, "repo": "komi-store/komi-store", "snapshot": "snapshots/5399060ac05b2b5919487531c5f3fd146d87bfac32a5f20104bb33b0b05d4d28.pack", "split": "rl", "task_id": "54f7cd4f49207f1420d60cb22040debe30eb709a3ae72138fa5ebbd30f2a8ba4"} {"base_sha": "7b76834d0312ee3b5bac5b26b7f584aa5eee9706", "cohort": null, "context": {"canonical_pr_url": "https://github.com/thensls/nsls-builder-toolkit/pull/76", "id": "55e95bba29fe7cdd2c0a840d9dda52136f05e0cda6193de9e895c48d9db2d562", "preparation_mode": "source-only", "snapshot": {"base_ref": "7b76834d0312ee3b5bac5b26b7f584aa5eee9706", "base_sha": "7b76834d0312ee3b5bac5b26b7f584aa5eee9706", "body": "", "head_ref": "c49c6f62b504be0364d486a4b97063c66a00db4e", "head_sha": "c49c6f62b504be0364d486a4b97063c66a00db4e", "name": "nsls-builder-toolkit", "number": 76, "owner": "thensls", "pr_url": "https://github.com/thensls/nsls-builder-toolkit/pull/76", "title": ""}}, "head_sha": "c49c6f62b504be0364d486a4b97063c66a00db4e", "metadata": {"group_id": "313e29498b436a94b8a17fe59eac24b90a1f8fed2831a3e3c68bcf65d4a0e603", "snapshot": {"base_sha": "7b76834d0312ee3b5bac5b26b7f584aa5eee9706", "external_requirements": [], "head_sha": "c49c6f62b504be0364d486a4b97063c66a00db4e", "objects": 334, "objects_sha256": "4894f804402c62e3884efec956a87d4c370ccc1b60e55420840895e21487aee1", "patch_sha256": "88f47924bc24bec21c1f1b551efad0f8ef4f1141a20f46117a60ed6ef3453946"}}, "pr_number": 76, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "9b2384b937a0", "description": "Chat substeps could display a “Grounded” note when configured with a grounding spec, even though chat requests do not forward that spec to the proxy; only generate substeps are grounded.", "file_path": "skills/track-prototype/prototype/player.js"}], "commits_under_review": [{"author": "kprentiss", "date": "2026-07-02T13:03:17Z", "files": [{"additions": 18, "deletions": 3, "filename": "skills/track-prototype/prototype/player.js", "patch": "@@ -109,7 +109,8 @@ function renderPromptContextNote() {\n if (ownSlugs.has(slug)) entered.push([slug, val]);\n else if (prereqProfile[slug]) synthetic.push([slug, val, (prereqProfile[slug] || {}).from]);\n }\n- if (!entered.length && !synthetic.length) return;\n+ const groundingSpec = sub.aiPromptConfig?.grounding;\n+ if (!entered.length && !synthetic.length && !groundingSpec) return;\n const clip = (v) => { const s = String(v); return escapeHtml(s.length > 70 ? s.slice(0, 67) + \"…\" : s); };\n const group = (title, rows) => rows.length\n ? `
${title}
`\n@@ -122,10 +123,21 @@ function renderPromptContextNote() {\n \"position:fixed;right:12px;bottom:12px;max-width:300px;max-height:45vh;overflow:auto;z-index:50;\"\n + \"background:#fffbe6;border:1px solid #e6d9a8;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.15);\"\n + \"padding:10px 12px;font-size:11px;line-height:1.35;color:#3d2f1f;font-family:system-ui,sans-serif\");\n+ // Grounded line: this substep pulls REAL cited figures (via the proxy) for the\n+ // mapped major, so the numbers in the output are real, not model-guessed.\n+ let groundedBlock = \"\";\n+ if (groundingSpec) {\n+ const majorSlug = groundingSpec.from?.major;\n+ const majorVal = majorSlug ? state.answers[majorSlug] : null;\n+ groundedBlock = `
Grounded — real data
`\n+ + `
🔎 Real BLS figures injected for `\n+ + `${escapeHtml(majorVal || majorSlug || \"major\")}
`;\n+ }\n note.innerHTML = `
📌 Prompt context note
`\n + `
Data behind this AI output
`\n + group(\"Entered in this demo\", entered)\n- + group(\"Synthetic — prerequisite\", synthetic);\n+ + group(\"Synthetic — prerequisite\", synthetic)\n+ + groundedBlock;\n root.appendChild(note);\n }\n \n@@ -330,7 +342,10 @@ async function maybeRunGenerateAI() {\n aiController = new AbortController();\n \n const ok = await streamFromProxy(\n- { type: \"generate\", template: sub.aiPromptConfig?.template || sub.prompt, profile: state.answers },\n+ // `grounding` (if the substep declares it) lets the proxy inject REAL cited\n+ // labor-market figures into the template before the AI call — the value-moment\n+ // grounding companion. Omitted → the proxy forwards the template unchanged.\n+ { type: \"generate\", template: sub.aiPromptConfig?.template || sub.prompt, profile: state.answers, grounding: sub.aiPromptConfig?.grounding },\n (d) => { out.textContent += d; },\n aiController.signal\n );", "status": "modified"}, {"additions": 21, "deletions": 7, "filename": "skills/value-moment/references/generate-substep-emission.md", "patch": "@@ -31,8 +31,8 @@ in `prompt`.\n \n **Note the template references the profile block, not `{slug}` tokens** — see\n \"Token mechanics\" below for why. This example is a **model-reasoned** moment: it\n-forbids numbers in the prompt. For a **grounded** moment with real figures, see\n-\"Grounding\" below (real data payload is future-only today).\n+forbids numbers in the prompt. For a **grounded** moment with real figures, add a\n+`grounding` spec — the companion is shipped; see \"Grounding\" below.\n \n Keys that matter for a value moment:\n \n@@ -92,11 +92,25 @@ an unresolved token:\n (not as a token), when the set is tiny and stable, and cite the source inline\n so a reviewer can check it. e.g. `\"…Ohio marketing-role entry wages (BLS OEWS,\n May 2024): …\"`. This validates and renders.\n-- **Future:** a companion data-fetch tool (see the SKILL's \"Companion\" section)\n- will supply a `{data}` payload (BLS OEWS by SOC/area, O*NET growth outlook) as\n- a real, resolvable input. `{data}` is **not a supported token yet** — do not\n- emit it until that tool and validator support land. Design grounded prompts so\n- a supplied data block drops in cleanly when it does.\n+- **Automatic (grounding companion, v1 shipped):** declare a `grounding` spec on\n+ the substep's `aiPromptConfig`. At runtime the demo proxy (Track Studio\n+ `/api/generate`) resolves REAL cited figures from the baked snapshot (NCES\n+ CIP↔SOC crosswalk + BLS OEWS) for the member's mapped major and **injects them\n+ into the template** with a strict \"use ONLY these figures\" instruction — so the\n+ AI phrases true numbers and invents none. No `{data}` token; the proxy appends\n+ the block. Shape:\n+ ```json\n+ \"aiPromptConfig\": {\n+ \"template\": \"The member's major is in the profile. Using ONLY the labor-market figures provided, name the roles it commonly leads to and their pay.\",\n+ \"grounding\": { \"need\": [\"careers\",\"salary\"], \"from\": { \"major\": \"major\", \"location\": \"home-state\" } },\n+ \"executeOn\": \"enter\"\n+ }\n+ ```\n+ `from` maps which collected slugs feed the lookup. If the major isn't in the\n+ snapshot (or a figure is missing), the proxy injects nothing/less and the prompt\n+ stays qualitative — the faithfulness fallback. Write the template to *use the\n+ provided figures*, never to state a number itself. (v1 = national salary; state/\n+ metro wages + BLS EP growth are fast-follows.)\n \n For a **model-reasoned** or **illustrative** moment there is no data payload —\n the template carries the honesty framing directly (qualitative, or \"roughly / as", "status": "modified"}], "message": "feat: wire grounding companion into the player + value-moment docs\n\nComplements the Track Studio grounding v1 (real BLS/NCES figures injected by the\nproxy).\n\n- player.js: generate POST now includes the substep's `grounding` spec so the\n proxy can resolve + inject real figures; omitted → unchanged. The 📌 prompt-\n context note gains a \"Grounded — real data\" line when a substep is grounded, so\n the author sees that the numbers in the output are real BLS figures for their\n major, not model-guessed.\n- value-moment generate-substep-emission.md: the grounding companion is shipped —\n replaced the \"future-only {data}\" framing with the real `grounding` declaration\n shape ({need, from:{major,location}}) the proxy consumes, and the faithfulness\n fallback when a figure is missing.\n\nCo-Authored-By: Claude Opus 4.8 (1M context) ", "sha": "c49c6f62b504be0364d486a4b97063c66a00db4e"}], "post_review_commits": ["9b2384b937a08e174b9344f813fff37e602a1165"], "pr_author": "kprentiss", "pr_title": "feat: wire grounding companion into player + value-moment docs", "repo_name": "thensls/nsls-builder-toolkit"}, "repo": "thensls/nsls-builder-toolkit", "snapshot": "snapshots/313e29498b436a94b8a17fe59eac24b90a1f8fed2831a3e3c68bcf65d4a0e603.pack", "split": "rl", "task_id": "55e95bba29fe7cdd2c0a840d9dda52136f05e0cda6193de9e895c48d9db2d562"} {"base_sha": "f6ed49a1c9566ffadc1669ea5d14efd6145baa05", "cohort": null, "context": {"canonical_pr_url": "https://github.com/thensls/nsls-builder-toolkit/pull/162", "id": "56f98277d80632408f5ccb9ef6af777cdd5015021b993b2257802f2cd3d4aae0", "preparation_mode": "source-only", "snapshot": {"base_ref": "f6ed49a1c9566ffadc1669ea5d14efd6145baa05", "base_sha": "f6ed49a1c9566ffadc1669ea5d14efd6145baa05", "body": "", "head_ref": "ba8f135c8486bf6d6f98dfe04e15f947cccdd93f", "head_sha": "ba8f135c8486bf6d6f98dfe04e15f947cccdd93f", "name": "nsls-builder-toolkit", "number": 162, "owner": "thensls", "pr_url": "https://github.com/thensls/nsls-builder-toolkit/pull/162", "title": ""}}, "head_sha": "ba8f135c8486bf6d6f98dfe04e15f947cccdd93f", "metadata": {"group_id": "890f50bafcb3e5807480f0f6f7327731615e334eff9d4db84550d05a6c1c025c", "snapshot": {"base_sha": "f6ed49a1c9566ffadc1669ea5d14efd6145baa05", "external_requirements": [], "head_sha": "ba8f135c8486bf6d6f98dfe04e15f947cccdd93f", "objects": 496, "objects_sha256": "51038ea4ad9bca1960fabb7acb3a9cfb3f2550fb94dcbfc8fd9fe1819e2ad67d", "patch_sha256": "162bc6a945dcbcdbbf76f4a207b4b7cea8b168be95fa921c73b9ec12bf21246c"}}, "pr_number": 162, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "19ac2698ba08", "description": "Exporting the token in the same command as the Node lookup masked lookup failures, allowing deployment to continue with an empty NETLIFY_AUTH_TOKEN.", "file_path": "skills/netlify-deploy/SKILL.md"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "19ac2698ba08", "description": "The shell config-file probe ignored XDG_CONFIG_HOME, so it missed Netlify credentials stored outside ~/.config on Linux.", "file_path": "skills/netlify-deploy/SKILL.md"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "19ac2698ba08", "description": "The config-file probe and token extractor omitted the Windows APPDATA location, so they could not find credentials there.", "file_path": "skills/netlify-deploy/SKILL.md"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "19ac2698ba08", "description": "The provision-builder Linux config lookup hardcoded ~/.config and missed credentials when XDG_CONFIG_HOME was set.", "file_path": "skills/provision-builder/SKILL.md"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "19ac2698ba08", "description": "The provision-builder Windows lookup omitted the Config directory from Netlify CLI's APPDATA path.", "file_path": "skills/provision-builder/SKILL.md"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "821954b70c09", "description": "The auth instructions ran netlify status before reading the token; in non-interactive sessions its prompt could hang and prevent deployment.", "file_path": "skills/netlify-deploy/SKILL.md"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "821954b70c09", "description": "The Site ID instructions suggested netlify sites:list, which could also hang on a non-interactive CLI prompt.", "file_path": "skills/netlify-deploy/SKILL.md"}, {"action_id": "A8", "action_type": "fix", "category": "bug", "commit_sha": "821954b70c09", "description": "The token extractor selected the first user in a multi-identity config, potentially deploying with a personal or former-employer account instead of the intended identity.", "file_path": "skills/netlify-deploy/SKILL.md"}], "commits_under_review": [{"author": "joe-cupka", "date": "2026-08-31T22:52:01Z", "files": [{"additions": 40, "deletions": 8, "filename": "skills/netlify-deploy/SKILL.md", "patch": "@@ -29,20 +29,52 @@ Confirm: `netlify-cli/24.x.x` or higher.\n \n ### 2. Auth Token\n \n-The Netlify auth token is stored at:\n-```\n-~/.netlify/config.json\n+**First: you usually don't need the token at all.** If the CLI is already\n+logged in, `netlify deploy` and `netlify sites:list` authenticate themselves.\n+Check before going hunting:\n+\n+```bash\n+netlify status\n ```\n \n-Look under `.users[userId].auth.token`. Retrieve it with:\n+If that prints an account, skip to Site ID.\n+\n+**If you do need the raw token**, its location is platform- and version-\n+dependent. `~/.netlify/config.json` is the *legacy* path and does not exist on\n+current CLI versions — on macOS the file lives under `~/Library/Preferences/`.\n+Probe the candidates rather than hardcoding one:\n \n ```bash\n-node -e \"const c=require(process.env.HOME+'/.netlify/config.json'); const uid=Object.keys(c.users)[0]; console.log(c.users[uid].auth.token)\"\n+for f in \"$HOME/Library/Preferences/netlify/config.json\" \\\n+ \"$HOME/.config/netlify/config.json\" \\\n+ \"$HOME/.netlify/config.json\"; do\n+ [ -f \"$f\" ] && echo \"$f\" && break\n+done\n ```\n \n-Save to a variable for use in deploy commands:\n+| Platform | Path |\n+|---|---|\n+| macOS | `~/Library/Preferences/netlify/config.json` |\n+| Linux | `~/.config/netlify/config.json` (respects `XDG_CONFIG_HOME`) |\n+| Windows | `%APPDATA%\\netlify\\Config\\config.json` |\n+| Legacy (pre-20.x) | `~/.netlify/config.json` |\n+\n+Extract the token from whichever path exists:\n+\n ```bash\n-export NETLIFY_AUTH_TOKEN=$(node -e \"const c=require(process.env.HOME+'/.netlify/config.json'); const uid=Object.keys(c.users)[0]; console.log(c.users[uid].auth.token)\")\n+export NETLIFY_AUTH_TOKEN=$(node -e '\n+ const fs=require(\"fs\"), path=require(\"path\"), home=process.env.HOME||process.env.USERPROFILE;\n+ const cands=[\n+ path.join(home,\"Library/Preferences/netlify/config.json\"),\n+ path.join(process.env.XDG_CONFIG_HOME||path.join(home,\".config\"),\"netlify/config.json\"),\n+ path.join(home,\".netlify/config.json\"),\n+ ];\n+ const f=cands.find(fs.existsSync);\n+ if(!f){console.error(\"No netlify config found; run: netlify login\");process.exit(1);}\n+ const c=JSON.parse(fs.readFileSync(f,\"utf8\"));\n+ const uid=Object.keys(c.users)[0];\n+ console.log(c.users[uid].auth.token);\n+')\n ```\n \n ### 3. Site ID\n@@ -225,7 +257,7 @@ After visual review:\n ## Environment\n \n - **CLI**: `netlify-cli` ≥ 24.x via `npm install -g netlify-cli@latest`\n-- **Auth**: `~/.netlify/config.json` → `.users[uid].auth.token`\n+- **Auth**: CLI is usually already logged in (`netlify status`). Raw token, if needed: `~/Library/Preferences/netlify/config.json` on macOS, `~/.config/netlify/config.json` on Linux → `.users[uid].auth.token`. `~/.netlify/config.json` is legacy and absent on CLI 20.x+.\n - **Site for SLT slides**: `slt-pipeline-slides.netlify.app` → NETLIFY_SITE_ID = `ea5aa7d1-dfa7-4048-8cae-b185b434ce1e`\n - **Deploy dir pattern**: `/tmp/[project]-deploy/index.html`\n - **Playwright MCP**: Available via `mcp__plugin_playwright_playwright__*` tools", "status": "modified"}], "message": "Fix stale Netlify auth token path in netlify-deploy skill\n\n`~/.netlify/config.json` is the legacy CLI location and does not exist on\nnetlify-cli 20.x+. On macOS the config lives at\n`~/Library/Preferences/netlify/config.json`; on Linux at\n`~/.config/netlify/config.json`.\n\nThe documented snippet used `require(HOME + '/.netlify/config.json')`, which\nthrows MODULE_NOT_FOUND. Because it ran inside `$(...)`, the failure was\nsilent — `NETLIFY_AUTH_TOKEN` got set to empty (or to captured stderr when\n`2>&1` was present), and the error only surfaced later as a confusing auth\nfailure.\n\nChanges:\n- Lead with `netlify status`; the CLI is usually already authenticated and\n the raw token is not needed at all.\n- Replace the hardcoded path with a probe across macOS / Linux / legacy\n locations, plus a platform table including Windows.\n- Make the extraction snippet fail loudly with a pointer to `netlify login`\n instead of silently producing an empty token.\n\nVerified on netlify-cli/26.1.0, darwin-arm64, node v24.13.0.\n\nCo-Authored-By: Claude Opus 5 (1M context) ", "sha": "ba8f135c8486bf6d6f98dfe04e15f947cccdd93f"}], "post_review_commits": ["19ac2698ba08e6fb6c5a30a0142a2ade1efccd6a", "821954b70c09b856d95971f96aeda5a829aff465"], "pr_author": "joe-cupka", "pr_title": "Fix stale Netlify auth token path in netlify-deploy skill", "repo_name": "thensls/nsls-builder-toolkit"}, "repo": "thensls/nsls-builder-toolkit", "snapshot": "snapshots/890f50bafcb3e5807480f0f6f7327731615e334eff9d4db84550d05a6c1c025c.pack", "split": "rl", "task_id": "56f98277d80632408f5ccb9ef6af777cdd5015021b993b2257802f2cd3d4aae0"} {"base_sha": "8fa90c471b25671a09b59a989d9c0c9367e5797b", "cohort": null, "context": {"canonical_pr_url": "https://github.com/dzackgarza/itree/pull/21", "id": "577068f19c4cdf65337fcdf40035d1e18e361a837edcb0f3c8d818006ae59b37", "preparation_mode": "source-only", "snapshot": {"base_ref": "8fa90c471b25671a09b59a989d9c0c9367e5797b", "base_sha": "8fa90c471b25671a09b59a989d9c0c9367e5797b", "body": "", "head_ref": "2812fea653edc52c9fe1925eec42f1910d2c3e3f", "head_sha": "2812fea653edc52c9fe1925eec42f1910d2c3e3f", "name": "itree", "number": 21, "owner": "dzackgarza", "pr_url": "https://github.com/dzackgarza/itree/pull/21", "title": ""}}, "head_sha": "2812fea653edc52c9fe1925eec42f1910d2c3e3f", "metadata": {"group_id": "1446e828d0fd6be706766642918349805fd8b749ed476d7a8557d43ff6f18b31", "snapshot": {"base_sha": "8fa90c471b25671a09b59a989d9c0c9367e5797b", "external_requirements": [], "head_sha": "2812fea653edc52c9fe1925eec42f1910d2c3e3f", "objects": 59, "objects_sha256": "8f1e17876f0f3959212372ba03c9d53cd1d010a71f7d57c9329ea028c73b9714", "patch_sha256": "122a8bcc0a8a611760a42c46048ec3fa8b4d1541e6162ca139fd5e3c552f7b33"}}, "pr_number": 21, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "529b3db78106", "description": "Account scans ignored the configured deferral_label and used the default 'deferred', misclassifying custom-labeled intentional shelves as W030 instead of I010.", "file_path": "src/itree/validate.py"}, {"action_id": "A2", "action_type": "improvement", "category": "performance", "commit_sha": "529b3db78106", "description": "The doctor command loaded configuration twice, once for the report and again for structure questions, causing redundant reads and potentially inconsistent settings within one invocation.", "file_path": "src/itree/cli.py"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "529b3db78106", "description": "The GitHub query fetched only the first 20 issue labels, so a deferral label beyond that limit could be missed and an intentional shelf reported as W030.", "file_path": "src/itree/github.py"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "82c05c832de5", "description": "Deferral-label matching was case-sensitive even though GitHub label identity is case-insensitive; a label such as 'Deferred' was incorrectly treated as different from configured 'deferred'.", "file_path": "src/itree/validate.py"}, {"action_id": "A5", "action_type": "fix", "category": "documentation", "commit_sha": "82c05c832de5", "description": "The I010 diagnostic meaning said the grouping was labeled 'deferred' even when a different deferral label was configured.", "file_path": "src/itree/validate.py"}, {"action_id": "A6", "action_type": "improvement", "category": "performance", "commit_sha": "beb302c16c0d", "description": "Account scans loaded configuration inside repo_health for every repository, repeatedly reading the config file during a concurrent scan and coupling health calculation to config I/O.", "file_path": "src/itree/validate.py"}, {"action_id": "A7", "action_type": "fix", "category": "documentation", "commit_sha": "df3d2b624774", "description": "The W030 remediation instructed users to add the 'deferred' label even when a different deferral label was configured, so following the advice would not clear the warning.", "file_path": "src/itree/validate.py"}], "commits_under_review": [{"author": "dzackgarza", "date": "2026-07-10T12:20:35Z", "files": [{"additions": 8, "deletions": 0, "filename": "src/itree/WORKFLOWS.md", "patch": "@@ -126,3 +126,11 @@ Keep it proportional:\n \n The tree should be as small as the work is.\n When in doubt, absorb.\n+\n+## Deferred groupings (long-horizon shelves)\n+\n+A milestone or backlog ledger may legitimately hold no work units yet, on purpose: far-future capabilities are often best left un-broken-down until prerequisite work lands, so premature breakdown does not churn.\n+\n+Label such a grouping `deferred` (configurable via `deferral_label` in `~/.config/itree/config.toml`). `itree doctor` then reports it as informational `I010` (\"deferred, awaiting breakdown\") instead of warning `W030` (dead shelf).\n+An untagged empty grouping still warns as a stale shelf.\n+Because a deferred grouping has no open work units, `next` skips past it until its work is filed in.", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "src/itree/cli.py", "patch": "@@ -750,7 +750,7 @@ def doctor(\n print(f\"GitHub/auth/API failure: {e}\")\n sys.exit(3)\n \n- report = generate_doctor_report(dag)\n+ report = generate_doctor_report(dag, deferral_label=load_config().deferral_label)\n \n if as_json:\n print(report.model_dump_json(indent=2))", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "src/itree/github.py", "patch": "@@ -25,6 +25,7 @@\n body\n url\n milestone { title }\n+ labels(first: 20) { nodes { name } }\n subIssues(first: 100) {\n totalCount\n nodes { number }", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "src/itree/metrics.py", "patch": "@@ -31,6 +31,7 @@ class MetricsConfig(BaseModel):\n loc_per_work_unit: int = 400\n flat_children_ratio: float = 0.5\n flat_min_children: int = 6\n+ deferral_label: str = \"deferred\"\n \n \n class PresentCodeSize(BaseModel):", "status": "modified"}, {"additions": 13, "deletions": 2, "filename": "src/itree/models.py", "patch": "@@ -2,9 +2,9 @@\n \n import re\n from enum import StrEnum\n-from typing import Annotated, Literal, Self\n+from typing import Annotated, Any, Literal, Self\n \n-from pydantic import BaseModel, ConfigDict, Field, model_validator\n+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator\n \n IssueNumber = Annotated[int, Field(gt=0)]\n GithubIssueId = Annotated[int, Field(gt=0)]\n@@ -126,6 +126,15 @@ class GithubIssue(BaseModel):\n state_reason: str | None = None\n milestone: Milestone | None = None\n pull_request: dict | None = None\n+ labels: tuple[str, ...] = ()\n+\n+ @field_validator(\"labels\", mode=\"before\")\n+ @classmethod\n+ def _normalize_labels(cls, value: Any) -> tuple[str, ...]:\n+ \"\"\"Accept REST (``[{\"name\": ...}]``) and plain-string label shapes alike.\"\"\"\n+ if value is None:\n+ return ()\n+ return tuple(item[\"name\"] if isinstance(item, dict) else item for item in value)\n \n @classmethod\n def from_graphql(cls, node: dict) -> GithubIssue:\n@@ -137,6 +146,7 @@ def from_graphql(cls, node: dict) -> GithubIssue:\n \"\"\"\n milestone = node.get(\"milestone\")\n state_reason = node.get(\"stateReason\")\n+ label_nodes = node[\"labels\"][\"nodes\"]\n return cls(\n id=node[\"databaseId\"],\n number=node[\"number\"],\n@@ -146,6 +156,7 @@ def from_graphql(cls, node: dict) -> GithubIssue:\n body=node.get(\"body\") or None,\n state_reason=state_reason.lower() if state_reason else None,\n milestone=Milestone(title=milestone[\"title\"]) if milestone else None,\n+ labels=tuple(label[\"name\"] for label in label_nodes),\n )\n \n @property", "status": "modified"}, {"additions": 31, "deletions": 2, "filename": "src/itree/validate.py", "patch": "@@ -104,6 +104,9 @@ class DiagnosticDetails(TypedDict):\n \"remediation\": [\n \"A. Close the grouping issue if its work is complete.\",\n \"B. Move live work under it if it is supposed to be active.\",\n+ \"C. If it is an intentional long-horizon shelf awaiting breakdown, label it 'deferred' \"\n+ \"(configurable via deferral_label in ~/.config/itree/config.toml); \"\n+ \"doctor then reports it as I010 instead of warning.\",\n ],\n },\n \"W020\": {\n@@ -188,6 +191,13 @@ class DiagnosticDetails(TypedDict):\n \"meaning\": \"Traversal is deterministic. The reported next work-unit issue is safe for agents.\",\n \"remediation\": [],\n },\n+ \"I010\": {\n+ \"title\": \"deferred_grouping\",\n+ \"severity\": \"info\",\n+ \"meaning\": \"An intentionally deferred grouping (labeled 'deferred') has no open descendants yet. \"\n+ \"It is a long-horizon shelf awaiting breakdown once it becomes the next item, not a stale one.\",\n+ \"remediation\": [],\n+ },\n }\n \n \n@@ -283,7 +293,7 @@ def repo_health(dag: RepoDag) -> RepoHealth:\n )\n \n \n-def generate_doctor_report(dag: RepoDag) -> DoctorReport:\n+def generate_doctor_report(dag: RepoDag, deferral_label: str = \"deferred\") -> DoctorReport:\n dag = issue_only_dag(dag)\n findings_list: list[Finding] = []\n \n@@ -541,10 +551,16 @@ def calculate_depths(node: TreeNode, current_depth: int) -> None:\n work_unit_nodes.append(node)\n \n # W030: open grouping issue (other than the root) with no open descendants.\n+ # A grouping carrying the deferral label is an intentional long-horizon\n+ # shelf awaiting breakdown, not a dead one: it is reported as I010 instead.\n dead_groupings = []\n+ deferred_groupings = []\n for node in tree_nodes[1:]:\n if node.issue.is_open and is_grouping_issue(node.issue.title) and not any(d.issue.is_open for d in node.descendants()):\n- dead_groupings.append(f'#{node.issue.number} \"{node.issue.title}\" has no open descendants')\n+ if deferral_label in node.issue.labels:\n+ deferred_groupings.append(f'#{node.issue.number} \"{node.issue.title}\" is deferred, awaiting breakdown')\n+ else:\n+ dead_groupings.append(f'#{node.issue.number} \"{node.issue.title}\" has no open descendants')\n \n if dead_groupings:\n f_details = DIAGNOSTIC_CATALOG[\"W030\"]\n@@ -559,6 +575,19 @@ def calculate_depths(node: TreeNode, current_depth: int) -> None:\n )\n )\n \n+ if deferred_groupings:\n+ f_details = DIAGNOSTIC_CATALOG[\"I010\"]\n+ findings_list.append(\n+ Finding(\n+ code=\"I010\",\n+ severity=\"info\",\n+ title=f_details[\"title\"],\n+ evidence=deferred_groupings,\n+ meaning=f_details[\"meaning\"],\n+ remediation=f_details[\"remediation\"],\n+ )\n+ )\n+\n # W041: active milestone without milestone ledger\n active_milestones = set()\n for issue in dag.issues.values():", "status": "modified"}, {"additions": 59, "deletions": 11, "filename": "tests/fixtures/graphql_issues_pages.json", "patch": "@@ -3,7 +3,10 @@\n \"data\": {\n \"repository\": {\n \"issues\": {\n- \"pageInfo\": { \"hasNextPage\": true, \"endCursor\": \"cursor1\" },\n+ \"pageInfo\": {\n+ \"hasNextPage\": true,\n+ \"endCursor\": \"cursor1\"\n+ },\n \"nodes\": [\n {\n \"number\": 1,\n@@ -16,9 +19,21 @@\n \"milestone\": null,\n \"subIssues\": {\n \"totalCount\": 2,\n- \"nodes\": [{ \"number\": 2 }, { \"number\": 3 }]\n+ \"nodes\": [\n+ {\n+ \"number\": 2\n+ },\n+ {\n+ \"number\": 3\n+ }\n+ ]\n },\n- \"blockedBy\": { \"nodes\": [] }\n+ \"blockedBy\": {\n+ \"nodes\": []\n+ },\n+ \"labels\": {\n+ \"nodes\": []\n+ }\n },\n {\n \"number\": 2,\n@@ -29,8 +44,20 @@\n \"body\": null,\n \"url\": \"https://github.com/testowner/testrepo/issues/2\",\n \"milestone\": null,\n- \"subIssues\": { \"totalCount\": 1, \"nodes\": [{ \"number\": 4 }] },\n- \"blockedBy\": { \"nodes\": [] }\n+ \"subIssues\": {\n+ \"totalCount\": 1,\n+ \"nodes\": [\n+ {\n+ \"number\": 4\n+ }\n+ ]\n+ },\n+ \"blockedBy\": {\n+ \"nodes\": []\n+ },\n+ \"labels\": {\n+ \"nodes\": []\n+ }\n }\n ]\n }\n@@ -41,7 +68,10 @@\n \"data\": {\n \"repository\": {\n \"issues\": {\n- \"pageInfo\": { \"hasNextPage\": false, \"endCursor\": null },\n+ \"pageInfo\": {\n+ \"hasNextPage\": false,\n+ \"endCursor\": null\n+ },\n \"nodes\": [\n {\n \"number\": 3,\n@@ -51,9 +81,19 @@\n \"stateReason\": null,\n \"body\": \"## Acceptance Criteria\\n- Proven.\",\n \"url\": \"https://github.com/testowner/testrepo/issues/3\",\n- \"milestone\": { \"title\": \"v1\" },\n- \"subIssues\": { \"totalCount\": 0, \"nodes\": [] },\n- \"blockedBy\": { \"nodes\": [] }\n+ \"milestone\": {\n+ \"title\": \"v1\"\n+ },\n+ \"subIssues\": {\n+ \"totalCount\": 0,\n+ \"nodes\": []\n+ },\n+ \"blockedBy\": {\n+ \"nodes\": []\n+ },\n+ \"labels\": {\n+ \"nodes\": []\n+ }\n },\n {\n \"number\": 4,\n@@ -64,8 +104,16 @@\n \"body\": \"## Acceptance Criteria\\n- Proven.\",\n \"url\": \"https://github.com/testowner/testrepo/issues/4\",\n \"milestone\": null,\n- \"subIssues\": { \"totalCount\": 0, \"nodes\": [] },\n- \"blockedBy\": { \"nodes\": [] }\n+ \"subIssues\": {\n+ \"totalCount\": 0,\n+ \"nodes\": []\n+ },\n+ \"blockedBy\": {\n+ \"nodes\": []\n+ },\n+ \"labels\": {\n+ \"nodes\": []\n+ }\n }\n ]\n }", "status": "modified"}, {"additions": 4, "deletions": 0, "filename": "tests/test_build_dag.py", "patch": "@@ -23,6 +23,7 @@ def _node(\n children: tuple[int, ...] = (),\n blocked_by: tuple[int, ...] = (),\n total_children: int | None = None,\n+ labels: tuple[str, ...] = (),\n ) -> dict:\n return {\n \"number\": number,\n@@ -33,6 +34,7 @@ def _node(\n \"body\": None,\n \"url\": f\"https://github.com/testowner/testrepo/issues/{number}\",\n \"milestone\": None,\n+ \"labels\": {\"nodes\": [{\"name\": name} for name in labels]},\n \"subIssues\": {\n \"totalCount\": total_children if total_children is not None else len(children),\n \"nodes\": [{\"number\": child} for child in children],\n@@ -135,8 +137,10 @@ def test_from_graphql_field_mapping() -> None:\n \"body\": \"Body text\",\n \"url\": \"https://github.com/o/r/issues/7\",\n \"milestone\": {\"title\": \"v1\"},\n+ \"labels\": {\"nodes\": [{\"name\": \"bug\"}]},\n }\n issue = GithubIssue.from_graphql(node)\n+ assert issue.labels == (\"bug\",)\n assert issue.id == 1234\n assert issue.number == 7\n assert issue.state == IssueState.closed", "status": "modified"}, {"additions": 87, "deletions": 0, "filename": "tests/test_doctor.py", "patch": "@@ -21,6 +21,7 @@ def _issue(\n state: IssueState = IssueState.open,\n body: str | None = None,\n milestone: str | None = None,\n+ labels: tuple[str, ...] = (),\n ) -> GithubIssue:\n m = Milestone(title=milestone) if milestone else None\n return GithubIssue(\n@@ -31,6 +32,7 @@ def _issue(\n html_url=f\"https://github.com/t/t/issues/{number}\",\n body=body,\n milestone=m,\n+ labels=labels,\n )\n \n \n@@ -298,6 +300,91 @@ def test_doctor_report_root_never_flagged_dead_grouping() -> None:\n assert all(f.code != \"W030\" for f in report.findings)\n \n \n+def test_doctor_deferred_grouping_suppresses_w030() -> None:\n+ \"\"\"A grouping labeled 'deferred' is an intentional long-horizon shelf, not a dead one.\"\"\"\n+ dag = RepoDag(\n+ repo_ref=_repo_ref(),\n+ issues={\n+ 1: _issue(1, \"Ledger: Root\"),\n+ 2: _issue(2, \"Milestone: far future\", labels=(\"deferred\",)),\n+ 3: _issue(\n+ 3,\n+ \"Live work unit\",\n+ body=\"## Acceptance Criteria\\n- Proven at the boundary.\",\n+ ),\n+ },\n+ children_of={1: (2, 3), 2: ()},\n+ )\n+ report = generate_doctor_report(dag)\n+ assert all(f.code != \"W030\" for f in report.findings)\n+\n+\n+def test_doctor_deferred_grouping_surfaces_info_finding() -> None:\n+ \"\"\"Deferred shelves stay visible via a non-warning I010 line that names them.\"\"\"\n+ dag = RepoDag(\n+ repo_ref=_repo_ref(),\n+ issues={\n+ 1: _issue(1, \"Ledger: Root\"),\n+ 2: _issue(2, \"Milestone: far future\", labels=(\"deferred\",)),\n+ 3: _issue(\n+ 3,\n+ \"Live work unit\",\n+ body=\"## Acceptance Criteria\\n- Proven at the boundary.\",\n+ ),\n+ },\n+ children_of={1: (2, 3), 2: ()},\n+ )\n+ report = generate_doctor_report(dag)\n+ info = [f for f in report.findings if f.code == \"I010\"]\n+ assert len(info) == 1\n+ assert \"#2\" in info[0].evidence[0]\n+ assert info[0].severity == \"info\"\n+ # An info-only deferral must not push the repo out of OK status.\n+ assert report.status == \"ok\"\n+\n+\n+def test_doctor_untagged_empty_grouping_still_warns_alongside_deferred() -> None:\n+ \"\"\"Only the tagged grouping is spared; an untagged empty shelf still warns W030.\"\"\"\n+ dag = RepoDag(\n+ repo_ref=_repo_ref(),\n+ issues={\n+ 1: _issue(1, \"Ledger: Root\"),\n+ 2: _issue(2, \"Milestone: far future\", labels=(\"deferred\",)),\n+ 3: _issue(3, \"Milestone: stale shelf\"),\n+ 4: _issue(\n+ 4,\n+ \"Live work unit\",\n+ body=\"## Acceptance Criteria\\n- Proven at the boundary.\",\n+ ),\n+ },\n+ children_of={1: (2, 3, 4), 2: (), 3: ()},\n+ )\n+ report = generate_doctor_report(dag)\n+ w030 = [f for f in report.findings if f.code == \"W030\"]\n+ assert len(w030) == 1\n+ assert \"#3\" in w030[0].evidence[0]\n+ assert all(\"#2\" not in e for e in w030[0].evidence)\n+\n+\n+def test_doctor_deferral_label_is_configurable() -> None:\n+ \"\"\"The sanctioned label name is a knob; a custom label suppresses W030 too.\"\"\"\n+ dag = RepoDag(\n+ repo_ref=_repo_ref(),\n+ issues={\n+ 1: _issue(1, \"Ledger: Root\"),\n+ 2: _issue(2, \"Milestone: far future\", labels=(\"long-horizon\",)),\n+ 3: _issue(\n+ 3,\n+ \"Live work unit\",\n+ body=\"## Acceptance Criteria\\n- Proven at the boundary.\",\n+ ),\n+ },\n+ children_of={1: (2, 3), 2: ()},\n+ )\n+ report = generate_doctor_report(dag, deferral_label=\"long-horizon\")\n+ assert all(f.code != \"W030\" for f in report.findings)\n+\n+\n def test_doctor_report_duplicate_reachable_issue() -> None:\n \"\"\"ERROR E013 is triggered when an issue has multiple parents under the root.\"\"\"\n dag = RepoDag(", "status": "modified"}, {"additions": 39, "deletions": 0, "filename": "tests/test_models.py", "patch": "@@ -105,6 +105,45 @@ def test_closed_issue(self) -> None:\n )\n assert issue.is_open is False\n \n+ def test_labels_default_empty(self) -> None:\n+ \"\"\"Labels default to an empty tuple when absent.\"\"\"\n+ issue = GithubIssue(\n+ id=1,\n+ number=1,\n+ title=\"T\",\n+ state=IssueState.open,\n+ html_url=\"https://github.com/o/r/issues/1\",\n+ )\n+ assert issue.labels == ()\n+\n+ def test_labels_from_rest_shape(self) -> None:\n+ \"\"\"REST returns labels as objects with a 'name'; the validator flattens them.\"\"\"\n+ issue = GithubIssue.model_validate(\n+ {\n+ \"id\": 1,\n+ \"number\": 1,\n+ \"title\": \"T\",\n+ \"state\": \"open\",\n+ \"html_url\": \"https://github.com/o/r/issues/1\",\n+ \"labels\": [{\"name\": \"deferred\"}, {\"name\": \"enhancement\"}],\n+ }\n+ )\n+ assert issue.labels == (\"deferred\", \"enhancement\")\n+\n+ def test_labels_from_graphql_shape(self) -> None:\n+ \"\"\"from_graphql flattens the nested labels.nodes[].name shape.\"\"\"\n+ issue = GithubIssue.from_graphql(\n+ {\n+ \"databaseId\": 1,\n+ \"number\": 1,\n+ \"title\": \"T\",\n+ \"state\": \"OPEN\",\n+ \"url\": \"https://github.com/o/r/issues/1\",\n+ \"labels\": {\"nodes\": [{\"name\": \"deferred\"}]},\n+ }\n+ )\n+ assert issue.labels == (\"deferred\",)\n+\n \n class TestTreeNode:\n \"\"\"Tests for TreeNode model.\"\"\"", "status": "modified"}], "message": "feat(doctor): recognize a 'deferred' label so W030 spares intentional shelves\n\nW030 flagged every empty grouping as a dead shelf, pressuring maintainers to\nprematurely break down or close long-horizon milestone ledgers. Now a grouping\nlabeled 'deferred' (configurable via deferral_label in config.toml) is reported\nas informational I010 ('awaiting breakdown') instead of warning W030; untagged\nempty groupings still warn. next naturally skips deferred groupings since they\nhold no open work units.\n\nThreads GitHub labels through the GraphQL fetch and GithubIssue model (accepting\nboth REST and GraphQL label shapes). --explain W030 and WORKFLOWS.md document the\ndeferral tag as the sanctioned route for long-horizon shelves.\n\nCloses #19.\n\nCo-Authored-By: Claude Opus 4.8 (1M context) ", "sha": "2812fea653edc52c9fe1925eec42f1910d2c3e3f"}], "post_review_commits": ["529b3db78106945f51cdcdb6f2cf4a7ef21491f9", "82c05c832de547ea6fa64af398f4584d69fba281", "beb302c16c0db718a856bdf37a0d4f8182db36c4", "df3d2b624774c92aaca373c85da5b5172d6eb3c8"], "pr_author": "dzackgarza", "pr_title": "feat(doctor): recognize a 'deferred' label so W030 spares intentional shelves", "repo_name": "dzackgarza/itree"}, "repo": "dzackgarza/itree", "snapshot": "snapshots/1446e828d0fd6be706766642918349805fd8b749ed476d7a8557d43ff6f18b31.pack", "split": "rl", "task_id": "577068f19c4cdf65337fcdf40035d1e18e361a837edcb0f3c8d818006ae59b37"} {"base_sha": "b010d3a5ebce52bfbb43b45cb5e43b44ed83f1f8", "cohort": null, "context": {"canonical_pr_url": "https://github.com/IamCoder18/aaravlabs-old/pull/50", "id": "58ad111173b8ead06039c713f1e4dee1c6d4d5cb7d520842ba130b74b39632c3", "preparation_mode": "source-only", "snapshot": {"base_ref": "b010d3a5ebce52bfbb43b45cb5e43b44ed83f1f8", "base_sha": "b010d3a5ebce52bfbb43b45cb5e43b44ed83f1f8", "body": "", "head_ref": "7ebe76d70af968fb59a03223f1ebbd9efda8ef1c", "head_sha": "7ebe76d70af968fb59a03223f1ebbd9efda8ef1c", "name": "aaravlabs-old", "number": 50, "owner": "IamCoder18", "pr_url": "https://github.com/IamCoder18/aaravlabs-old/pull/50", "title": ""}}, "head_sha": "7ebe76d70af968fb59a03223f1ebbd9efda8ef1c", "metadata": {"group_id": "30d3f595d64737348bebfecdab63c81a45a7492dfd5d2dca94f18f49033e14c3", "snapshot": {"base_sha": "b010d3a5ebce52bfbb43b45cb5e43b44ed83f1f8", "external_requirements": [], "head_sha": "7ebe76d70af968fb59a03223f1ebbd9efda8ef1c", "objects": 288, "objects_sha256": "75e62c946d0b33629391b3a403f2911096f77b1f71b1e5f578bf57b24c50e8f0", "patch_sha256": "3719c8b472b0600da5872860f2fd81f9b0dda9b1a082280d6e1f42aa85696e9e"}}, "pr_number": 50, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "security", "commit_sha": "042d52be4294", "description": "Several CSV export fields bypassed escapeCsvField, so quotes or other special characters could produce malformed CSV and potentially allow CSV injection.", "file_path": "src/routes/api/export/+server.ts"}, {"action_id": "A2", "action_type": "cleanup", "category": "other", "commit_sha": "042d52be4294", "description": "The benchmark used a stub escapeCsvField that only converted values to strings, so its performance measurements did not reflect the export code's escaping overhead.", "file_path": "benchmark.ts"}], "commits_under_review": [{"author": "IamCoder18", "date": "2026-04-24T18:49:35Z", "files": [{"additions": 59, "deletions": 0, "filename": "benchmark.ts", "patch": "@@ -0,0 +1,59 @@\n+const rows = Array.from({ length: 100000 }, (_, i) => ({\n+ session_id: `session_${i}`,\n+ start_time: '2023-01-01T00:00:00.000Z',\n+ end_time: '2023-01-01T01:00:00.000Z',\n+ preferences: { theme: 'dark' },\n+ question_id: `question_${i}`,\n+ problem: 'What is 2+2?',\n+ topic: 'math',\n+ difficulty: 'easy',\n+ user_steps: '2+2=4',\n+ user_answer: '4',\n+ steps_correct: true,\n+ answer_correct: true,\n+ steps_analysis: 'Good',\n+ answer_analysis: 'Good',\n+ attempt_time: '2023-01-01T00:05:00.000Z'\n+}));\n+\n+function escapeCsvField(value: any) { return String(value); }\n+\n+function withMap() {\n+ const csvRows = [];\n+ rows.forEach((row: any) => {\n+ const csvRow = [\n+ row.session_id,\n+ row.start_time,\n+ row.end_time || '',\n+ escapeCsvField(JSON.stringify(row.preferences)),\n+ row.question_id || '',\n+ escapeCsvField(row.problem || ''),\n+ row.topic || '',\n+ row.difficulty || '',\n+ escapeCsvField(row.user_steps || ''),\n+ escapeCsvField(row.user_answer || ''),\n+ row.steps_correct || '',\n+ row.answer_correct || '',\n+ escapeCsvField(row.steps_analysis || ''),\n+ escapeCsvField(row.answer_analysis || ''),\n+ row.attempt_time || ''\n+ ].map(field => `\"${field}\"`);\n+\n+ csvRows.push(csvRow.join(','));\n+ });\n+}\n+\n+function withoutMap() {\n+ const csvRows = [];\n+ rows.forEach((row: any) => {\n+ csvRows.push(`\"${row.session_id}\",\"${row.start_time}\",\"${row.end_time || ''}\",\"${escapeCsvField(JSON.stringify(row.preferences))}\",\"${row.question_id || ''}\",\"${escapeCsvField(row.problem || '')}\",\"${row.topic || ''}\",\"${row.difficulty || ''}\",\"${escapeCsvField(row.user_steps || '')}\",\"${escapeCsvField(row.user_answer || '')}\",\"${row.steps_correct || ''}\",\"${row.answer_correct || ''}\",\"${escapeCsvField(row.steps_analysis || '')}\",\"${escapeCsvField(row.answer_analysis || '')}\",\"${row.attempt_time || ''}\"`);\n+ });\n+}\n+\n+console.time('withMap');\n+withMap();\n+console.timeEnd('withMap');\n+\n+console.time('withoutMap');\n+withoutMap();\n+console.timeEnd('withoutMap');", "status": "added"}, {"additions": 114, "deletions": 5, "filename": "bun.lock", "patch": "@@ -25,6 +25,7 @@\n \"@tailwindcss/typography\": \"^0.5.16\",\n \"@testing-library/jest-dom\": \"^6.6.3\",\n \"@testing-library/svelte\": \"^5.2.8\",\n+ \"@vitest/coverage-v8\": \"^3.2.4\",\n \"jsdom\": \"^26.1.0\",\n \"postcss\": \"^8.5.6\",\n \"svelte\": \"^5.0.0\",\n@@ -52,10 +53,18 @@\n \n \"@babel/code-frame\": [\"@babel/code-frame@7.27.1\", \"\", { \"dependencies\": { \"@babel/helper-validator-identifier\": \"^7.27.1\", \"js-tokens\": \"^4.0.0\", \"picocolors\": \"^1.1.1\" } }, \"sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==\"],\n \n+ \"@babel/helper-string-parser\": [\"@babel/helper-string-parser@7.27.1\", \"\", {}, \"sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==\"],\n+\n \"@babel/helper-validator-identifier\": [\"@babel/helper-validator-identifier@7.27.1\", \"\", {}, \"sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow==\"],\n \n+ \"@babel/parser\": [\"@babel/parser@7.29.2\", \"\", { \"dependencies\": { \"@babel/types\": \"^7.29.0\" }, \"bin\": \"./bin/babel-parser.js\" }, \"sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==\"],\n+\n \"@babel/runtime\": [\"@babel/runtime@7.27.6\", \"\", {}, \"sha512-vbavdySgbTTrmFE+EsiqUTzlOr5bzlnJtUv9PynGCAKvfQqjIXbvFdumPM/GxMDfyuGMJaJAU6TO4zc1Jf1i8Q==\"],\n \n+ \"@babel/types\": [\"@babel/types@7.29.0\", \"\", { \"dependencies\": { \"@babel/helper-string-parser\": \"^7.27.1\", \"@babel/helper-validator-identifier\": \"^7.28.5\" } }, \"sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==\"],\n+\n+ \"@bcoe/v8-coverage\": [\"@bcoe/v8-coverage@1.0.2\", \"\", {}, \"sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==\"],\n+\n \"@better-auth/core\": [\"@better-auth/core@1.5.6\", \"\", { \"dependencies\": { \"@opentelemetry/semantic-conventions\": \"^1.39.0\", \"@standard-schema/spec\": \"^1.1.0\", \"zod\": \"^4.3.6\" }, \"peerDependencies\": { \"@better-auth/utils\": \"0.3.1\", \"@better-fetch/fetch\": \"1.1.21\", \"@cloudflare/workers-types\": \">=4\", \"@opentelemetry/api\": \"^1.9.0\", \"better-call\": \"1.3.2\", \"jose\": \"^6.1.0\", \"kysely\": \"^0.28.5\", \"nanostores\": \"^1.0.1\" }, \"optionalPeers\": [\"@cloudflare/workers-types\"] }, \"sha512-Ez9DZdIMFyxHremmoLz1emFPGNQomDC1jqqBPnZ6Ci+6TiGN3R9w/Y03cJn6I8r1ycKgOzeVMZtJ/erOZ27Gsw==\"],\n \n \"@better-auth/drizzle-adapter\": [\"@better-auth/drizzle-adapter@1.5.6\", \"\", { \"peerDependencies\": { \"@better-auth/core\": \"1.5.6\", \"@better-auth/utils\": \"^0.3.0\", \"drizzle-orm\": \">=0.41.0\" }, \"optionalPeers\": [\"drizzle-orm\"] }, \"sha512-VfFFmaoFw3ug12SiSuIwzrMoHyIVmkMGWm9gZ4sXdYYVX4HboCL4m3fjzOhppcmK5OGatRuU+N1UX6wxCITcXw==\"],\n@@ -146,8 +155,12 @@\n \n \"@google/generative-ai\": [\"@google/generative-ai@0.24.1\", \"\", {}, \"sha512-MqO+MLfM6kjxcKoy0p1wRzG3b4ZZXtPI+z2IE26UogS2Cm/XHO+7gGRBh6gcJsOiIVoH93UwKvW4HdgiOZCy9Q==\"],\n \n+ \"@isaacs/cliui\": [\"@isaacs/cliui@8.0.2\", \"\", { \"dependencies\": { \"string-width\": \"^5.1.2\", \"string-width-cjs\": \"npm:string-width@^4.2.0\", \"strip-ansi\": \"^7.0.1\", \"strip-ansi-cjs\": \"npm:strip-ansi@^6.0.1\", \"wrap-ansi\": \"^8.1.0\", \"wrap-ansi-cjs\": \"npm:wrap-ansi@^7.0.0\" } }, \"sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==\"],\n+\n \"@isaacs/fs-minipass\": [\"@isaacs/fs-minipass@4.0.1\", \"\", { \"dependencies\": { \"minipass\": \"^7.0.4\" } }, \"sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==\"],\n \n+ \"@istanbuljs/schema\": [\"@istanbuljs/schema@0.1.6\", \"\", {}, \"sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==\"],\n+\n \"@jridgewell/gen-mapping\": [\"@jridgewell/gen-mapping@0.3.12\", \"\", { \"dependencies\": { \"@jridgewell/sourcemap-codec\": \"^1.5.0\", \"@jridgewell/trace-mapping\": \"^0.3.24\" } }, \"sha512-OuLGC46TjB5BbN1dH8JULVVZY4WTdkF7tV9Ys6wLL1rubZnCMstOhNHueU5bLCrnRuDhKPDM4g6sw4Bel5Gzqg==\"],\n \n \"@jridgewell/resolve-uri\": [\"@jridgewell/resolve-uri@3.1.2\", \"\", {}, \"sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==\"],\n@@ -164,6 +177,8 @@\n \n \"@opentelemetry/semantic-conventions\": [\"@opentelemetry/semantic-conventions@1.40.0\", \"\", {}, \"sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw==\"],\n \n+ \"@pkgjs/parseargs\": [\"@pkgjs/parseargs@0.11.0\", \"\", {}, \"sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==\"],\n+\n \"@polka/url\": [\"@polka/url@1.0.0-next.29\", \"\", {}, \"sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==\"],\n \n \"@rollup/plugin-commonjs\": [\"@rollup/plugin-commonjs@28.0.6\", \"\", { \"dependencies\": { \"@rollup/pluginutils\": \"^5.0.1\", \"commondir\": \"^1.0.1\", \"estree-walker\": \"^2.0.2\", \"fdir\": \"^6.2.0\", \"is-reference\": \"1.2.1\", \"magic-string\": \"^0.30.3\", \"picomatch\": \"^4.0.2\" }, \"peerDependencies\": { \"rollup\": \"^2.68.0||^3.0.0||^4.0.0\" } }, \"sha512-XSQB1K7FUU5QP+3lOQmVCE3I0FcbbNvmNT4VJSj93iUjayaARrTQeoRdiYQoftAJBLrR9t2agwAd3ekaTgHNlw==\"],\n@@ -294,6 +309,8 @@\n \n \"@types/trusted-types\": [\"@types/trusted-types@2.0.7\", \"\", {}, \"sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==\"],\n \n+ \"@vitest/coverage-v8\": [\"@vitest/coverage-v8@3.2.4\", \"\", { \"dependencies\": { \"@ampproject/remapping\": \"^2.3.0\", \"@bcoe/v8-coverage\": \"^1.0.2\", \"ast-v8-to-istanbul\": \"^0.3.3\", \"debug\": \"^4.4.1\", \"istanbul-lib-coverage\": \"^3.2.2\", \"istanbul-lib-report\": \"^3.0.1\", \"istanbul-lib-source-maps\": \"^5.0.6\", \"istanbul-reports\": \"^3.1.7\", \"magic-string\": \"^0.30.17\", \"magicast\": \"^0.3.5\", \"std-env\": \"^3.9.0\", \"test-exclude\": \"^7.0.1\", \"tinyrainbow\": \"^2.0.0\" }, \"peerDependencies\": { \"@vitest/browser\": \"3.2.4\", \"vitest\": \"3.2.4\" }, \"optionalPeers\": [\"@vitest/browser\"] }, \"sha512-EyF9SXU6kS5Ku/U82E259WSnvg6c8KTjppUncuNdm5QHpe17mwREHnjDzozC8x9MZ0xfBUFSaLkRv4TMA75ALQ==\"],\n+\n \"@vitest/expect\": [\"@vitest/expect@3.2.4\", \"\", { \"dependencies\": { \"@types/chai\": \"^5.2.2\", \"@vitest/spy\": \"3.2.4\", \"@vitest/utils\": \"3.2.4\", \"chai\": \"^5.2.0\", \"tinyrainbow\": \"^2.0.0\" } }, \"sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==\"],\n \n \"@vitest/mocker\": [\"@vitest/mocker@3.2.4\", \"\", { \"dependencies\": { \"@vitest/spy\": \"3.2.4\", \"estree-walker\": \"^3.0.3\", \"magic-string\": \"^0.30.17\" }, \"peerDependencies\": { \"msw\": \"^2.4.9\", \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0-0\" }, \"optionalPeers\": [\"msw\"] }, \"sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==\"],\n@@ -324,8 +341,12 @@\n \n \"assertion-error\": [\"assertion-error@2.0.1\", \"\", {}, \"sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==\"],\n \n+ \"ast-v8-to-istanbul\": [\"ast-v8-to-istanbul@0.3.12\", \"\", { \"dependencies\": { \"@jridgewell/trace-mapping\": \"^0.3.31\", \"estree-walker\": \"^3.0.3\", \"js-tokens\": \"^10.0.0\" } }, \"sha512-BRRC8VRZY2R4Z4lFIL35MwNXmwVqBityvOIwETtsCSwvjl0IdgFsy9NhdaA6j74nUdtJJlIypeRhpDam19Wq3g==\"],\n+\n \"axobject-query\": [\"axobject-query@4.1.0\", \"\", {}, \"sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==\"],\n \n+ \"balanced-match\": [\"balanced-match@4.0.4\", \"\", {}, \"sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==\"],\n+\n \"base64-js\": [\"base64-js@1.5.1\", \"\", {}, \"sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==\"],\n \n \"better-auth\": [\"better-auth@1.5.6\", \"\", { \"dependencies\": { \"@better-auth/core\": \"1.5.6\", \"@better-auth/drizzle-adapter\": \"1.5.6\", \"@better-auth/kysely-adapter\": \"1.5.6\", \"@better-auth/memory-adapter\": \"1.5.6\", \"@better-auth/mongo-adapter\": \"1.5.6\", \"@better-auth/prisma-adapter\": \"1.5.6\", \"@better-auth/telemetry\": \"1.5.6\", \"@better-auth/utils\": \"0.3.1\", \"@better-fetch/fetch\": \"1.1.21\", \"@noble/ciphers\": \"^2.1.1\", \"@noble/hashes\": \"^2.0.1\", \"better-call\": \"1.3.2\", \"defu\": \"^6.1.4\", \"jose\": \"^6.1.3\", \"kysely\": \"^0.28.12\", \"nanostores\": \"^1.1.1\", \"zod\": \"^4.3.6\" }, \"peerDependencies\": { \"@lynx-js/react\": \"*\", \"@prisma/client\": \"^5.0.0 || ^6.0.0 || ^7.0.0\", \"@sveltejs/kit\": \"^2.0.0\", \"@tanstack/react-start\": \"^1.0.0\", \"@tanstack/solid-start\": \"^1.0.0\", \"better-sqlite3\": \"^12.0.0\", \"drizzle-kit\": \">=0.31.4\", \"drizzle-orm\": \">=0.41.0\", \"mongodb\": \"^6.0.0 || ^7.0.0\", \"mysql2\": \"^3.0.0\", \"next\": \"^14.0.0 || ^15.0.0 || ^16.0.0\", \"pg\": \"^8.0.0\", \"prisma\": \"^5.0.0 || ^6.0.0 || ^7.0.0\", \"react\": \"^18.0.0 || ^19.0.0\", \"react-dom\": \"^18.0.0 || ^19.0.0\", \"solid-js\": \"^1.0.0\", \"svelte\": \"^4.0.0 || ^5.0.0\", \"vitest\": \"^2.0.0 || ^3.0.0 || ^4.0.0\", \"vue\": \"^3.0.0\" }, \"optionalPeers\": [\"@lynx-js/react\", \"@prisma/client\", \"@tanstack/react-start\", \"@tanstack/solid-start\", \"better-sqlite3\", \"drizzle-kit\", \"drizzle-orm\", \"mongodb\", \"mysql2\", \"next\", \"prisma\", \"react\", \"react-dom\", \"solid-js\", \"vue\"] }, \"sha512-QSpJTqaT1XVfWRQe/fm3PgeuwOIlz1nWX/Dx7nsHStJ382bLzmDbQk2u7IT0IJ6wS5SRxfqEE1Ev9TXontgyAQ==\"],\n@@ -336,6 +357,8 @@\n \n \"bignumber.js\": [\"bignumber.js@9.3.1\", \"\", {}, \"sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==\"],\n \n+ \"brace-expansion\": [\"brace-expansion@5.0.5\", \"\", { \"dependencies\": { \"balanced-match\": \"^4.0.2\" } }, \"sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==\"],\n+\n \"buffer-equal-constant-time\": [\"buffer-equal-constant-time@1.0.1\", \"\", {}, \"sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==\"],\n \n \"cac\": [\"cac@6.7.14\", \"\", {}, \"sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==\"],\n@@ -366,6 +389,8 @@\n \n \"create-require\": [\"create-require@1.1.1\", \"\", {}, \"sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==\"],\n \n+ \"cross-spawn\": [\"cross-spawn@7.0.6\", \"\", { \"dependencies\": { \"path-key\": \"^3.1.0\", \"shebang-command\": \"^2.0.0\", \"which\": \"^2.0.1\" } }, \"sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==\"],\n+\n \"css-tree\": [\"css-tree@3.2.1\", \"\", { \"dependencies\": { \"mdn-data\": \"2.27.1\", \"source-map-js\": \"^1.2.1\" } }, \"sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==\"],\n \n \"css.escape\": [\"css.escape@1.5.1\", \"\", {}, \"sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==\"],\n@@ -402,8 +427,12 @@\n \n \"dotenv\": [\"dotenv@17.2.1\", \"\", {}, \"sha512-kQhDYKZecqnM0fCnzI5eIv5L4cAe/iRI+HqMbO/hbRdTAeXDG+M9FjipUxNfbARuEg4iHIbhnhs78BCHNbSxEQ==\"],\n \n+ \"eastasianwidth\": [\"eastasianwidth@0.2.0\", \"\", {}, \"sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==\"],\n+\n \"ecdsa-sig-formatter\": [\"ecdsa-sig-formatter@1.0.11\", \"\", { \"dependencies\": { \"safe-buffer\": \"^5.0.1\" } }, \"sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==\"],\n \n+ \"emoji-regex\": [\"emoji-regex@9.2.2\", \"\", {}, \"sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==\"],\n+\n \"enhanced-resolve\": [\"enhanced-resolve@5.18.3\", \"\", { \"dependencies\": { \"graceful-fs\": \"^4.2.4\", \"tapable\": \"^2.2.0\" } }, \"sha512-d4lC8xfavMeBjzGr2vECC3fsGXziXZQyJxD868h2M/mBI3PwAuODxAkLkq5HYuvrPYcUtiLzsTo8U3PgX3Ocww==\"],\n \n \"entities\": [\"entities@6.0.1\", \"\", {}, \"sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==\"],\n@@ -428,6 +457,8 @@\n \n \"fflate\": [\"fflate@0.4.8\", \"\", {}, \"sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==\"],\n \n+ \"foreground-child\": [\"foreground-child@3.3.1\", \"\", { \"dependencies\": { \"cross-spawn\": \"^7.0.6\", \"signal-exit\": \"^4.0.1\" } }, \"sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==\"],\n+\n \"formdata-polyfill\": [\"formdata-polyfill@4.0.10\", \"\", { \"dependencies\": { \"fetch-blob\": \"^3.1.2\" } }, \"sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==\"],\n \n \"fsevents\": [\"fsevents@2.3.3\", \"\", { \"os\": \"darwin\" }, \"sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==\"],\n@@ -438,6 +469,8 @@\n \n \"gcp-metadata\": [\"gcp-metadata@7.0.1\", \"\", { \"dependencies\": { \"gaxios\": \"^7.0.0\", \"google-logging-utils\": \"^1.0.0\", \"json-bigint\": \"^1.0.0\" } }, \"sha512-UcO3kefx6dCcZkgcTGgVOTFb7b1LlQ02hY1omMjjrrBzkajRMCFgYOjs7J71WqnuG1k2b+9ppGL7FsOfhZMQKQ==\"],\n \n+ \"glob\": [\"glob@10.5.0\", \"\", { \"dependencies\": { \"foreground-child\": \"^3.1.0\", \"jackspeak\": \"^3.1.2\", \"minimatch\": \"^9.0.4\", \"minipass\": \"^7.1.2\", \"package-json-from-dist\": \"^1.0.0\", \"path-scurry\": \"^1.11.1\" }, \"bin\": { \"glob\": \"dist/esm/bin.mjs\" } }, \"sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==\"],\n+\n \"google-auth-library\": [\"google-auth-library@10.1.0\", \"\", { \"dependencies\": { \"base64-js\": \"^1.3.0\", \"ecdsa-sig-formatter\": \"^1.0.11\", \"gaxios\": \"^7.0.0\", \"gcp-metadata\": \"^7.0.0\", \"google-logging-utils\": \"^1.0.0\", \"gtoken\": \"^8.0.0\", \"jws\": \"^4.0.0\" } }, \"sha512-GspVjZj1RbyRWpQ9FbAXMKjFGzZwDKnUHi66JJ+tcjcu5/xYAP1pdlWotCuIkMwjfVsxxDvsGZXGLzRt72D0sQ==\"],\n \n \"google-logging-utils\": [\"google-logging-utils@1.1.1\", \"\", {}, \"sha512-rcX58I7nqpu4mbKztFeOAObbomBbHU2oIb/d3tJfF3dizGSApqtSwYJigGCooHdnMyQBIw8BrWyK96w3YXgr6A==\"],\n@@ -452,6 +485,8 @@\n \n \"html-encoding-sniffer\": [\"html-encoding-sniffer@4.0.0\", \"\", { \"dependencies\": { \"whatwg-encoding\": \"^3.1.1\" } }, \"sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==\"],\n \n+ \"html-escaper\": [\"html-escaper@2.0.2\", \"\", {}, \"sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==\"],\n+\n \"http-proxy-agent\": [\"http-proxy-agent@7.0.2\", \"\", { \"dependencies\": { \"agent-base\": \"^7.1.0\", \"debug\": \"^4.3.4\" } }, \"sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==\"],\n \n \"https-proxy-agent\": [\"https-proxy-agent@7.0.6\", \"\", { \"dependencies\": { \"agent-base\": \"^7.1.2\", \"debug\": \"4\" } }, \"sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==\"],\n@@ -462,19 +497,33 @@\n \n \"is-core-module\": [\"is-core-module@2.16.1\", \"\", { \"dependencies\": { \"hasown\": \"^2.0.2\" } }, \"sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==\"],\n \n+ \"is-fullwidth-code-point\": [\"is-fullwidth-code-point@3.0.0\", \"\", {}, \"sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==\"],\n+\n \"is-module\": [\"is-module@1.0.0\", \"\", {}, \"sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==\"],\n \n \"is-potential-custom-element-name\": [\"is-potential-custom-element-name@1.0.1\", \"\", {}, \"sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==\"],\n \n \"is-reference\": [\"is-reference@3.0.3\", \"\", { \"dependencies\": { \"@types/estree\": \"^1.0.6\" } }, \"sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==\"],\n \n+ \"isexe\": [\"isexe@2.0.0\", \"\", {}, \"sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==\"],\n+\n \"isomorphic-dompurify\": [\"isomorphic-dompurify@3.7.1\", \"\", { \"dependencies\": { \"dompurify\": \"^3.3.3\", \"jsdom\": \"^29.0.1\" } }, \"sha512-ChhzwwCm7k8h8ANiq1Vc7geCWeHGaAPusgXU5N4mu7Y2wChgn2JHvbUe6aH/XQOUG3+KV+GmqSq95MntW/V1ng==\"],\n \n+ \"istanbul-lib-coverage\": [\"istanbul-lib-coverage@3.2.2\", \"\", {}, \"sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==\"],\n+\n+ \"istanbul-lib-report\": [\"istanbul-lib-report@3.0.1\", \"\", { \"dependencies\": { \"istanbul-lib-coverage\": \"^3.0.0\", \"make-dir\": \"^4.0.0\", \"supports-color\": \"^7.1.0\" } }, \"sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==\"],\n+\n+ \"istanbul-lib-source-maps\": [\"istanbul-lib-source-maps@5.0.6\", \"\", { \"dependencies\": { \"@jridgewell/trace-mapping\": \"^0.3.23\", \"debug\": \"^4.1.1\", \"istanbul-lib-coverage\": \"^3.0.0\" } }, \"sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==\"],\n+\n+ \"istanbul-reports\": [\"istanbul-reports@3.2.0\", \"\", { \"dependencies\": { \"html-escaper\": \"^2.0.0\", \"istanbul-lib-report\": \"^3.0.0\" } }, \"sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==\"],\n+\n+ \"jackspeak\": [\"jackspeak@3.4.3\", \"\", { \"dependencies\": { \"@isaacs/cliui\": \"^8.0.2\" }, \"optionalDependencies\": { \"@pkgjs/parseargs\": \"^0.11.0\" } }, \"sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==\"],\n+\n \"jiti\": [\"jiti@2.4.2\", \"\", { \"bin\": \"lib/jiti-cli.mjs\" }, \"sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==\"],\n \n \"jose\": [\"jose@6.2.2\", \"\", {}, \"sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==\"],\n \n- \"js-tokens\": [\"js-tokens@4.0.0\", \"\", {}, \"sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==\"],\n+ \"js-tokens\": [\"js-tokens@10.0.0\", \"\", {}, \"sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==\"],\n \n \"jsdom\": [\"jsdom@26.1.0\", \"\", { \"dependencies\": { \"cssstyle\": \"^4.2.1\", \"data-urls\": \"^5.0.0\", \"decimal.js\": \"^10.5.0\", \"html-encoding-sniffer\": \"^4.0.0\", \"http-proxy-agent\": \"^7.0.2\", \"https-proxy-agent\": \"^7.0.6\", \"is-potential-custom-element-name\": \"^1.0.1\", \"nwsapi\": \"^2.2.16\", \"parse5\": \"^7.2.1\", \"rrweb-cssom\": \"^0.8.0\", \"saxes\": \"^6.0.0\", \"symbol-tree\": \"^3.2.4\", \"tough-cookie\": \"^5.1.1\", \"w3c-xmlserializer\": \"^5.0.0\", \"webidl-conversions\": \"^7.0.0\", \"whatwg-encoding\": \"^3.1.1\", \"whatwg-mimetype\": \"^4.0.0\", \"whatwg-url\": \"^14.1.1\", \"ws\": \"^8.18.0\", \"xml-name-validator\": \"^5.0.0\" }, \"peerDependencies\": { \"canvas\": \"^3.0.0\" }, \"optionalPeers\": [\"canvas\"] }, \"sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==\"],\n \n@@ -530,6 +579,10 @@\n \n \"magic-string\": [\"magic-string@0.30.17\", \"\", { \"dependencies\": { \"@jridgewell/sourcemap-codec\": \"^1.5.0\" } }, \"sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==\"],\n \n+ \"magicast\": [\"magicast@0.3.5\", \"\", { \"dependencies\": { \"@babel/parser\": \"^7.25.4\", \"@babel/types\": \"^7.25.4\", \"source-map-js\": \"^1.2.0\" } }, \"sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==\"],\n+\n+ \"make-dir\": [\"make-dir@4.0.0\", \"\", { \"dependencies\": { \"semver\": \"^7.5.3\" } }, \"sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==\"],\n+\n \"make-error\": [\"make-error@1.3.6\", \"\", {}, \"sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==\"],\n \n \"mdn-data\": [\"mdn-data@2.27.1\", \"\", {}, \"sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==\"],\n@@ -538,6 +591,8 @@\n \n \"mini-svg-data-uri\": [\"mini-svg-data-uri@1.4.4\", \"\", { \"bin\": \"cli.js\" }, \"sha512-r9deDe9p5FJUPZAk3A59wGH7Ii9YrjjWw0jmw/liSbHl2CHiyXj6FcDXDu2K3TjVAXqiJdaw3xxwlZZr9E6nHg==\"],\n \n+ \"minimatch\": [\"minimatch@10.2.5\", \"\", { \"dependencies\": { \"brace-expansion\": \"^5.0.5\" } }, \"sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==\"],\n+\n \"minipass\": [\"minipass@7.1.2\", \"\", {}, \"sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==\"],\n \n \"minizlib\": [\"minizlib@3.0.2\", \"\", { \"dependencies\": { \"minipass\": \"^7.1.2\" } }, \"sha512-oG62iEk+CYt5Xj2YqI5Xi9xWUeZhDI8jjQmC5oThVH5JGCTgIjr7ciJDzC7MBzYd//WvR1OTmP5Q38Q8ShQtVA==\"],\n@@ -560,10 +615,16 @@\n \n \"nwsapi\": [\"nwsapi@2.2.20\", \"\", {}, \"sha512-/ieB+mDe4MrrKMT8z+mQL8klXydZWGR5Dowt4RAGKbJ3kIGEx3X4ljUo+6V73IXtUPWgfOlU5B9MlGxFO5T+cA==\"],\n \n+ \"package-json-from-dist\": [\"package-json-from-dist@1.0.1\", \"\", {}, \"sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==\"],\n+\n \"parse5\": [\"parse5@7.3.0\", \"\", { \"dependencies\": { \"entities\": \"^6.0.0\" } }, \"sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==\"],\n \n+ \"path-key\": [\"path-key@3.1.1\", \"\", {}, \"sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==\"],\n+\n \"path-parse\": [\"path-parse@1.0.7\", \"\", {}, \"sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==\"],\n \n+ \"path-scurry\": [\"path-scurry@1.11.1\", \"\", { \"dependencies\": { \"lru-cache\": \"^10.2.0\", \"minipass\": \"^5.0.0 || ^6.0.2 || ^7.0.0\" } }, \"sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==\"],\n+\n \"pathe\": [\"pathe@2.0.3\", \"\", {}, \"sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==\"],\n \n \"pathval\": [\"pathval@2.0.1\", \"\", {}, \"sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==\"],\n@@ -634,10 +695,18 @@\n \n \"saxes\": [\"saxes@6.0.0\", \"\", { \"dependencies\": { \"xmlchars\": \"^2.2.0\" } }, \"sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==\"],\n \n+ \"semver\": [\"semver@7.7.4\", \"\", { \"bin\": { \"semver\": \"bin/semver.js\" } }, \"sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==\"],\n+\n \"set-cookie-parser\": [\"set-cookie-parser@2.7.1\", \"\", {}, \"sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==\"],\n \n+ \"shebang-command\": [\"shebang-command@2.0.0\", \"\", { \"dependencies\": { \"shebang-regex\": \"^3.0.0\" } }, \"sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==\"],\n+\n+ \"shebang-regex\": [\"shebang-regex@3.0.0\", \"\", {}, \"sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==\"],\n+\n \"siginfo\": [\"siginfo@2.0.0\", \"\", {}, \"sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==\"],\n \n+ \"signal-exit\": [\"signal-exit@4.1.0\", \"\", {}, \"sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==\"],\n+\n \"sirv\": [\"sirv@3.0.1\", \"\", { \"dependencies\": { \"@polka/url\": \"^1.0.0-next.24\", \"mrmime\": \"^2.0.0\", \"totalist\": \"^3.0.0\" } }, \"sha512-FoqMu0NCGBLCcAkS1qA+XJIQTR6/JHfQXl+uGteNCQ76T91DMUjPa9xfmeqMY3z80nLSg9yQmNjK0Px6RWsH/A==\"],\n \n \"source-map-js\": [\"source-map-js@1.2.1\", \"\", {}, \"sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==\"],\n@@ -648,6 +717,14 @@\n \n \"std-env\": [\"std-env@3.9.0\", \"\", {}, \"sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw==\"],\n \n+ \"string-width\": [\"string-width@5.1.2\", \"\", { \"dependencies\": { \"eastasianwidth\": \"^0.2.0\", \"emoji-regex\": \"^9.2.2\", \"strip-ansi\": \"^7.0.1\" } }, \"sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==\"],\n+\n+ \"string-width-cjs\": [\"string-width@4.2.3\", \"\", { \"dependencies\": { \"emoji-regex\": \"^8.0.0\", \"is-fullwidth-code-point\": \"^3.0.0\", \"strip-ansi\": \"^6.0.1\" } }, \"sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==\"],\n+\n+ \"strip-ansi\": [\"strip-ansi@7.2.0\", \"\", { \"dependencies\": { \"ansi-regex\": \"^6.2.2\" } }, \"sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==\"],\n+\n+ \"strip-ansi-cjs\": [\"strip-ansi@6.0.1\", \"\", { \"dependencies\": { \"ansi-regex\": \"^5.0.1\" } }, \"sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==\"],\n+\n \"strip-indent\": [\"strip-indent@3.0.0\", \"\", { \"dependencies\": { \"min-indent\": \"^1.0.0\" } }, \"sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==\"],\n \n \"strip-literal\": [\"strip-literal@3.0.0\", \"\", { \"dependencies\": { \"js-tokens\": \"^9.0.1\" } }, \"sha512-TcccoMhJOM3OebGhSBEmp3UZ2SfDMZUEBdRA/9ynfLi8yYajyWX3JiXArcJt4Umh4vISpspkQIY8ZZoCqjbviA==\"],\n@@ -668,6 +745,8 @@\n \n \"tar\": [\"tar@7.4.3\", \"\", { \"dependencies\": { \"@isaacs/fs-minipass\": \"^4.0.0\", \"chownr\": \"^3.0.0\", \"minipass\": \"^7.1.2\", \"minizlib\": \"^3.0.1\", \"mkdirp\": \"^3.0.1\", \"yallist\": \"^5.0.0\" } }, \"sha512-5S7Va8hKfV7W5U6g3aYxXmlPoZVAwUMy9AOKyF2fVuZa2UD3qZjg578OrLRt8PcNN1PleVaL/5/yYATNL0ICUw==\"],\n \n+ \"test-exclude\": [\"test-exclude@7.0.2\", \"\", { \"dependencies\": { \"@istanbuljs/schema\": \"^0.1.2\", \"glob\": \"^10.4.1\", \"minimatch\": \"^10.2.2\" } }, \"sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==\"],\n+\n \"tinybench\": [\"tinybench@2.9.0\", \"\", {}, \"sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==\"],\n \n \"tinyexec\": [\"tinyexec@0.3.2\", \"\", {}, \"sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==\"],\n@@ -726,8 +805,14 @@\n \n \"whatwg-url\": [\"whatwg-url@14.2.0\", \"\", { \"dependencies\": { \"tr46\": \"^5.1.0\", \"webidl-conversions\": \"^7.0.0\" } }, \"sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==\"],\n \n+ \"which\": [\"which@2.0.2\", \"\", { \"dependencies\": { \"isexe\": \"^2.0.0\" }, \"bin\": { \"node-which\": \"./bin/node-which\" } }, \"sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==\"],\n+\n \"why-is-node-running\": [\"why-is-node-running@2.3.0\", \"\", { \"dependencies\": { \"siginfo\": \"^2.0.0\", \"stackback\": \"0.0.2\" }, \"bin\": \"cli.js\" }, \"sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==\"],\n \n+ \"wrap-ansi\": [\"wrap-ansi@8.1.0\", \"\", { \"dependencies\": { \"ansi-styles\": \"^6.1.0\", \"string-width\": \"^5.0.1\", \"strip-ansi\": \"^7.0.1\" } }, \"sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==\"],\n+\n+ \"wrap-ansi-cjs\": [\"wrap-ansi@7.0.0\", \"\", { \"dependencies\": { \"ansi-styles\": \"^4.0.0\", \"string-width\": \"^4.1.0\", \"strip-ansi\": \"^6.0.0\" } }, \"sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==\"],\n+\n \"ws\": [\"ws@8.18.3\", \"\", { \"peerDependencies\": { \"bufferutil\": \"^4.0.1\", \"utf-8-validate\": \">=5.0.2\" }, \"optionalPeers\": [\"bufferutil\", \"utf-8-validate\"] }, \"sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==\"],\n \n \"xml-name-validator\": [\"xml-name-validator@5.0.0\", \"\", {}, \"sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==\"],\n@@ -746,14 +831,14 @@\n \n \"@asamuzakjp/css-color/lru-cache\": [\"lru-cache@10.4.3\", \"\", {}, \"sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==\"],\n \n- \"@asamuzakjp/dom-selector/lru-cache\": [\"lru-cache@11.2.7\", \"\", {}, \"sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==\"],\n+ \"@babel/code-frame/js-tokens\": [\"js-tokens@4.0.0\", \"\", {}, \"sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==\"],\n+\n+ \"@babel/types/@babel/helper-validator-identifier\": [\"@babel/helper-validator-identifier@7.28.5\", \"\", {}, \"sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==\"],\n \n \"@cspotcode/source-map-support/@jridgewell/trace-mapping\": [\"@jridgewell/trace-mapping@0.3.9\", \"\", { \"dependencies\": { \"@jridgewell/resolve-uri\": \"^3.0.3\", \"@jridgewell/sourcemap-codec\": \"^1.4.10\" } }, \"sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==\"],\n \n \"@rollup/plugin-commonjs/is-reference\": [\"is-reference@1.2.1\", \"\", { \"dependencies\": { \"@types/estree\": \"*\" } }, \"sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==\"],\n \n- \"@rollup/pluginutils/estree-walker\": [\"estree-walker@2.0.2\", \"\", {}, \"sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==\"],\n-\n \"@testing-library/dom/aria-query\": [\"aria-query@5.3.0\", \"\", { \"dependencies\": { \"dequal\": \"^2.0.3\" } }, \"sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==\"],\n \n \"@testing-library/dom/chalk\": [\"chalk@4.1.2\", \"\", { \"dependencies\": { \"ansi-styles\": \"^4.1.0\", \"supports-color\": \"^7.1.0\" } }, \"sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==\"],\n@@ -762,15 +847,35 @@\n \n \"@vitest/mocker/estree-walker\": [\"estree-walker@3.0.3\", \"\", { \"dependencies\": { \"@types/estree\": \"^1.0.0\" } }, \"sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==\"],\n \n+ \"ast-v8-to-istanbul/@jridgewell/trace-mapping\": [\"@jridgewell/trace-mapping@0.3.31\", \"\", { \"dependencies\": { \"@jridgewell/resolve-uri\": \"^3.1.0\", \"@jridgewell/sourcemap-codec\": \"^1.4.14\" } }, \"sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==\"],\n+\n+ \"ast-v8-to-istanbul/estree-walker\": [\"estree-walker@3.0.3\", \"\", { \"dependencies\": { \"@types/estree\": \"^1.0.0\" } }, \"sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==\"],\n+\n \"better-call/set-cookie-parser\": [\"set-cookie-parser@3.1.0\", \"\", {}, \"sha512-kjnC1DXBHcxaOaOXBHBeRtltsDG2nUiUni+jP92M9gYdW12rsmx92UsfpH7o5tDRs7I1ZZPSQJQGv3UaRfCiuw==\"],\n \n+ \"glob/minimatch\": [\"minimatch@9.0.9\", \"\", { \"dependencies\": { \"brace-expansion\": \"^2.0.2\" } }, \"sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==\"],\n+\n \"isomorphic-dompurify/jsdom\": [\"jsdom@29.0.1\", \"\", { \"dependencies\": { \"@asamuzakjp/css-color\": \"^5.0.1\", \"@asamuzakjp/dom-selector\": \"^7.0.3\", \"@bramus/specificity\": \"^2.4.2\", \"@csstools/css-syntax-patches-for-csstree\": \"^1.1.1\", \"@exodus/bytes\": \"^1.15.0\", \"css-tree\": \"^3.2.1\", \"data-urls\": \"^7.0.0\", \"decimal.js\": \"^10.6.0\", \"html-encoding-sniffer\": \"^6.0.0\", \"is-potential-custom-element-name\": \"^1.0.1\", \"lru-cache\": \"^11.2.7\", \"parse5\": \"^8.0.0\", \"saxes\": \"^6.0.0\", \"symbol-tree\": \"^3.2.4\", \"tough-cookie\": \"^6.0.1\", \"undici\": \"^7.24.5\", \"w3c-xmlserializer\": \"^5.0.0\", \"webidl-conversions\": \"^8.0.1\", \"whatwg-mimetype\": \"^5.0.0\", \"whatwg-url\": \"^16.0.1\", \"xml-name-validator\": \"^5.0.0\" }, \"peerDependencies\": { \"canvas\": \"^3.0.0\" }, \"optionalPeers\": [\"canvas\"] }, \"sha512-z6JOK5gRO7aMybVq/y/MlIpKh8JIi68FBKMUtKkK2KH/wMSRlCxQ682d08LB9fYXplyY/UXG8P4XXTScmdjApg==\"],\n \n+ \"path-scurry/lru-cache\": [\"lru-cache@10.4.3\", \"\", {}, \"sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==\"],\n+\n \"pretty-format/ansi-styles\": [\"ansi-styles@5.2.0\", \"\", {}, \"sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==\"],\n \n+ \"string-width-cjs/emoji-regex\": [\"emoji-regex@8.0.0\", \"\", {}, \"sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==\"],\n+\n+ \"string-width-cjs/strip-ansi\": [\"strip-ansi@6.0.1\", \"\", { \"dependencies\": { \"ansi-regex\": \"^5.0.1\" } }, \"sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==\"],\n+\n+ \"strip-ansi/ansi-regex\": [\"ansi-regex@6.2.2\", \"\", {}, \"sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==\"],\n+\n \"strip-literal/js-tokens\": [\"js-tokens@9.0.1\", \"\", {}, \"sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==\"],\n \n- \"@testing-library/dom/chalk/ansi-styles\": [\"ansi-styles@4.3.0\", \"\", { \"dependencies\": { \"color-convert\": \"^2.0.1\" } }, \"sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==\"],\n+ \"wrap-ansi/ansi-styles\": [\"ansi-styles@6.2.3\", \"\", {}, \"sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==\"],\n+\n+ \"wrap-ansi-cjs/string-width\": [\"string-width@4.2.3\", \"\", { \"dependencies\": { \"emoji-regex\": \"^8.0.0\", \"is-fullwidth-code-point\": \"^3.0.0\", \"strip-ansi\": \"^6.0.1\" } }, \"sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==\"],\n+\n+ \"wrap-ansi-cjs/strip-ansi\": [\"strip-ansi@6.0.1\", \"\", { \"dependencies\": { \"ansi-regex\": \"^5.0.1\" } }, \"sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==\"],\n+\n+ \"glob/minimatch/brace-expansion\": [\"brace-expansion@2.1.0\", \"\", { \"dependencies\": { \"balanced-match\": \"^1.0.0\" } }, \"sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==\"],\n \n \"isomorphic-dompurify/jsdom/@asamuzakjp/css-color\": [\"@asamuzakjp/css-color@5.1.5\", \"\", { \"dependencies\": { \"@csstools/css-calc\": \"^3.1.1\", \"@csstools/css-color-parser\": \"^4.0.2\", \"@csstools/css-parser-algorithms\": \"^4.0.0\", \"@csstools/css-tokenizer\": \"^4.0.0\", \"lru-cache\": \"^11.2.7\" } }, \"sha512-8cMAA1bE66Mb/tfmkhcfJLjEPgyT7SSy6lW6id5XL113ai1ky76d/1L27sGnXCMsLfq66DInAU3OzuahB4lu9Q==\"],\n \n@@ -788,6 +893,10 @@\n \n \"isomorphic-dompurify/jsdom/whatwg-url\": [\"whatwg-url@16.0.1\", \"\", { \"dependencies\": { \"@exodus/bytes\": \"^1.11.0\", \"tr46\": \"^6.0.0\", \"webidl-conversions\": \"^8.0.1\" } }, \"sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==\"],\n \n+ \"wrap-ansi-cjs/string-width/emoji-regex\": [\"emoji-regex@8.0.0\", \"\", {}, \"sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==\"],\n+\n+ \"glob/minimatch/brace-expansion/balanced-match\": [\"balanced-match@1.0.2\", \"\", {}, \"sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==\"],\n+\n \"isomorphic-dompurify/jsdom/@asamuzakjp/css-color/@csstools/css-calc\": [\"@csstools/css-calc@3.1.1\", \"\", { \"peerDependencies\": { \"@csstools/css-parser-algorithms\": \"^4.0.0\", \"@csstools/css-tokenizer\": \"^4.0.0\" } }, \"sha512-HJ26Z/vmsZQqs/o3a6bgKslXGFAungXGbinULZO3eMsOyNJHeBBZfup5FiZInOghgoM4Hwnmw+OgbJCNg1wwUQ==\"],\n \n \"isomorphic-dompurify/jsdom/@asamuzakjp/css-color/@csstools/css-color-parser\": [\"@csstools/css-color-parser@4.0.2\", \"\", { \"dependencies\": { \"@csstools/color-helpers\": \"^6.0.2\", \"@csstools/css-calc\": \"^3.1.1\" }, \"peerDependencies\": { \"@csstools/css-parser-algorithms\": \"^4.0.0\", \"@csstools/css-tokenizer\": \"^4.0.0\" } }, \"sha512-0GEfbBLmTFf0dJlpsNU7zwxRIH0/BGEMuXLTCvFYxuL1tNhqzTbtnFICyJLTNK4a+RechKP75e7w42ClXSnJQw==\"],", "status": "modified"}, {"additions": 2, "deletions": 18, "filename": "src/routes/api/export/+server.ts", "patch": "@@ -72,25 +72,9 @@ export const GET: RequestHandler = async ({ url, locals }) => {\n const csvRows = [headers.join(',')];\n \n result.rows.forEach((row: any) => {\n- const csvRow = [\n- row.session_id,\n- row.start_time,\n- row.end_time || '',\n- escapeCsvField(JSON.stringify(row.preferences)),\n- row.question_id || '',\n- escapeCsvField(row.problem || ''),\n- row.topic || '',\n- row.difficulty || '',\n- escapeCsvField(row.user_steps || ''),\n- escapeCsvField(row.user_answer || ''),\n- row.steps_correct || '',\n- row.answer_correct || '',\n- escapeCsvField(row.steps_analysis || ''),\n- escapeCsvField(row.answer_analysis || ''),\n- row.attempt_time || ''\n- ].map(field => `\"${field}\"`);\n+ const csvRow = `\"${row.session_id}\",\"${row.start_time}\",\"${row.end_time || ''}\",\"${escapeCsvField(JSON.stringify(row.preferences))}\",\"${row.question_id || ''}\",\"${escapeCsvField(row.problem || '')}\",\"${row.topic || ''}\",\"${row.difficulty || ''}\",\"${escapeCsvField(row.user_steps || '')}\",\"${escapeCsvField(row.user_answer || '')}\",\"${row.steps_correct || ''}\",\"${row.answer_correct || ''}\",\"${escapeCsvField(row.steps_analysis || '')}\",\"${escapeCsvField(row.answer_analysis || '')}\",\"${row.attempt_time || ''}\"`;\n \n- csvRows.push(csvRow.join(','));\n+ csvRows.push(csvRow);\n });\n \n const csvContent = csvRows.join('\\n');", "status": "modified"}], "message": "perf(export): optimize CSV loop mapping and joining\n\nReplaced intermediate array allocation, string mapping, and joining inside the main CSV loop of `src/routes/api/export/+server.ts` with direct template string construction, drastically improving generation speed and lowering memory allocations.", "sha": "7ebe76d70af968fb59a03223f1ebbd9efda8ef1c"}], "post_review_commits": ["042d52be42942b820ab64c01c7dfe1f09e6676d8", "6084603f72264c56088ebd35978065ef0e9294d9"], "pr_author": "IamCoder18", "pr_title": "⚡ Optimize array allocation in CSV export loop", "repo_name": "IamCoder18/aaravlabs-old"}, "repo": "IamCoder18/aaravlabs-old", "snapshot": "snapshots/30d3f595d64737348bebfecdab63c81a45a7492dfd5d2dca94f18f49033e14c3.pack", "split": "rl", "task_id": "58ad111173b8ead06039c713f1e4dee1c6d4d5cb7d520842ba130b74b39632c3"} {"base_sha": "8f55b981df266f193c693bd82e472c06ef8347c4", "cohort": null, "context": {"canonical_pr_url": "https://github.com/kubeply/rudolint/pull/291", "id": "5a79740e59a217097a42221d9944df1f77554d5d5d12eaadcd7b1062c1a2277c", "preparation_mode": "source-only", "snapshot": {"base_ref": "8f55b981df266f193c693bd82e472c06ef8347c4", "base_sha": "8f55b981df266f193c693bd82e472c06ef8347c4", "body": "", "head_ref": "be7892eb73e53957e5456162a04c6b4f59ad44f7", "head_sha": "be7892eb73e53957e5456162a04c6b4f59ad44f7", "name": "rudolint", "number": 291, "owner": "kubeply", "pr_url": "https://github.com/kubeply/rudolint/pull/291", "title": ""}}, "head_sha": "be7892eb73e53957e5456162a04c6b4f59ad44f7", "metadata": {"group_id": "7b5d33dd8eb74dfbe9de659fad37269ab157450dfb6bf3e48a7078c3ac28f3ac", "snapshot": {"base_sha": "8f55b981df266f193c693bd82e472c06ef8347c4", "external_requirements": [], "head_sha": "be7892eb73e53957e5456162a04c6b4f59ad44f7", "objects": 730, "objects_sha256": "992c1886dce9730319cc9bef9b9bc14b4f2a9b12072222440aaf4447b6e9cb7e", "patch_sha256": "bdb1f8dda34b6a9faf3f9cfe30f04382e1a480dba9ea7f309768049a7b25e339"}}, "pr_number": 291, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "88c636d64596", "description": "Variable-expanded stage references could match an alias whose trailing literal appeared anywhere in the remaining alias, rather than at its end. This could incorrectly infer an inherited WORKDIR and suppress a DL3045 warning.", "file_path": "crates/rudolint-rules/src/compat/mod.rs"}, {"action_id": "A2", "action_type": "improvement", "category": "other", "commit_sha": "88c636d64596", "description": "The DL3045 fixture lacked a second no-WORKDIR stage matching the variable-expanded `no-workdir-mode-${MODE}` reference, so it did not cover inheritance when multiple possible stages have the same WORKDIR state.", "file_path": "fixtures/rules/DL3045.copy-relative-without-workdir/Dockerfile"}], "commits_under_review": [{"author": "chainyo", "date": "2026-05-30T11:19:17Z", "files": [{"additions": 66, "deletions": 1, "filename": "crates/rudolint-rules/src/compat/mod.rs", "patch": "@@ -1622,7 +1622,13 @@ impl Rule for CopyRelativeWithoutWorkdir {\n .as_ref()\n .and_then(|stage| stage_workdir.get(stage))\n .copied()\n- .unwrap_or_default();\n+ .unwrap_or_else(|| {\n+ inherited_workdir_from_variable_stage_reference(\n+ &from.image,\n+ &alias_to_stage,\n+ &stage_workdir,\n+ )\n+ });\n \n let stage_key = format!(\"__stage_{stage_idx}\");\n stage_workdir.insert(stage_key.clone(), workdir_set);\n@@ -1664,6 +1670,65 @@ impl Rule for CopyRelativeWithoutWorkdir {\n }\n }\n \n+fn inherited_workdir_from_variable_stage_reference(\n+ image: &str,\n+ alias_to_stage: &BTreeMap,\n+ stage_workdir: &BTreeMap,\n+) -> bool {\n+ let image = image.to_ascii_lowercase();\n+ if !image.contains('$') {\n+ return false;\n+ }\n+\n+ let mut matching_states = alias_to_stage\n+ .iter()\n+ .filter(|(alias, _)| variable_stage_reference_could_match(&image, alias))\n+ .filter_map(|(_, stage)| stage_workdir.get(stage).copied());\n+\n+ let Some(first_state) = matching_states.next() else {\n+ return false;\n+ };\n+\n+ matching_states.all(|state| state == first_state) && first_state\n+}\n+\n+fn variable_stage_reference_could_match(reference: &str, alias: &str) -> bool {\n+ let mut remaining = alias;\n+ let mut literal = String::new();\n+ let mut chars = reference.chars().peekable();\n+\n+ while let Some(character) = chars.next() {\n+ match character {\n+ '$' => {\n+ if !literal.is_empty() {\n+ let Some(index) = remaining.find(&literal) else {\n+ return false;\n+ };\n+ remaining = &remaining[index + literal.len()..];\n+ literal.clear();\n+ }\n+\n+ if matches!(chars.peek(), Some('{')) {\n+ chars.next();\n+ for variable_character in chars.by_ref() {\n+ if variable_character == '}' {\n+ break;\n+ }\n+ }\n+ } else {\n+ while matches!(chars.peek(), Some(next) if *next == '_' || next.is_ascii_alphanumeric())\n+ {\n+ chars.next();\n+ }\n+ }\n+ }\n+ _ => literal.push(character),\n+ }\n+ }\n+\n+ literal.is_empty() || remaining.contains(&literal)\n+}\n+\n rule_metadata!(\n UseraddNoLogInit,\n \"DL3046\",", "status": "modified"}, {"additions": 32, "deletions": 0, "filename": "crates/rudolint-rules/tests/snapshots/rule_fixtures__dl3045_copy_relative_without_workdir_fixture.snap", "patch": "@@ -50,5 +50,37 @@ expression: \"serde_json::to_value(&findings).expect(\\\"findings should serialize\\\n \"start_line\": 30\n },\n \"severity\": \"warning\"\n+ },\n+ {\n+ \"code\": \"DL3045\",\n+ \"help\": null,\n+ \"labels\": [],\n+ \"message\": \"`COPY` to a relative destination without `WORKDIR` set\",\n+ \"path\": \"\",\n+ \"primary_span\": {\n+ \"end_byte\": 797,\n+ \"end_column\": 14,\n+ \"end_line\": 48,\n+ \"start_byte\": 784,\n+ \"start_column\": 1,\n+ \"start_line\": 48\n+ },\n+ \"severity\": \"warning\"\n+ },\n+ {\n+ \"code\": \"DL3045\",\n+ \"help\": null,\n+ \"labels\": [],\n+ \"message\": \"`COPY` to a relative destination without `WORKDIR` set\",\n+ \"path\": \"\",\n+ \"primary_span\": {\n+ \"end_byte\": 940,\n+ \"end_column\": 14,\n+ \"end_line\": 56,\n+ \"start_byte\": 927,\n+ \"start_column\": 1,\n+ \"start_line\": 56\n+ },\n+ \"severity\": \"warning\"\n }\n ]", "status": "modified"}, {"additions": 23, "deletions": 0, "filename": "fixtures/rules/DL3045.copy-relative-without-workdir/Dockerfile", "patch": "@@ -31,3 +31,26 @@ COPY app.py relative/\n \n FROM 3 AS numeric-inherited\n COPY app.py src/\n+\n+FROM alpine:3.20 AS dev-mode-false\n+WORKDIR /workspace\n+\n+FROM dev-mode-false AS dev-mode-true\n+\n+FROM dev-mode-${MODE} AS dev-base\n+\n+FROM dev-base AS dev\n+COPY app.py .\n+\n+FROM alpine:3.20 AS no-workdir-mode-false\n+\n+FROM no-workdir-mode-${MODE} AS no-workdir-base\n+COPY app.py .\n+\n+FROM alpine:3.20 AS mixed-mode-false\n+WORKDIR /mixed\n+\n+FROM alpine:3.20 AS mixed-mode-true\n+\n+FROM mixed-mode-${MODE} AS mixed-base\n+COPY app.py .", "status": "modified"}], "message": "fix: inherit workdir through variable stages", "sha": "be7892eb73e53957e5456162a04c6b4f59ad44f7"}], "post_review_commits": ["88c636d64596f167b44bfeae92d3355371c2e40f"], "pr_author": "chainyo", "pr_title": "fix: inherit WORKDIR through variable stages", "repo_name": "kubeply/rudolint"}, "repo": "kubeply/rudolint", "snapshot": "snapshots/7b5d33dd8eb74dfbe9de659fad37269ab157450dfb6bf3e48a7078c3ac28f3ac.pack", "split": "rl", "task_id": "5a79740e59a217097a42221d9944df1f77554d5d5d12eaadcd7b1062c1a2277c"} {"base_sha": "e49df0900ed4cec6153c474d2d5bbad44dedbc7a", "cohort": null, "context": {"canonical_pr_url": "https://github.com/SidhuK/Glyph/pull/504", "id": "5a9beffe7ef37a6e0bdea57a288fa2983389b5ff32688cedb2673a26eab418be", "preparation_mode": "source-only", "snapshot": {"base_ref": "e49df0900ed4cec6153c474d2d5bbad44dedbc7a", "base_sha": "e49df0900ed4cec6153c474d2d5bbad44dedbc7a", "body": "", "head_ref": "f1c8d30c48fed58fae3a07801a49e721d9ec4465", "head_sha": "f1c8d30c48fed58fae3a07801a49e721d9ec4465", "name": "Glyph", "number": 504, "owner": "SidhuK", "pr_url": "https://github.com/SidhuK/Glyph/pull/504", "title": ""}}, "head_sha": "f1c8d30c48fed58fae3a07801a49e721d9ec4465", "metadata": {"group_id": "5a0883c73d1507cbac71dec80393e3c9427729e750bdb266b9e8b38348afed3f", "snapshot": {"base_sha": "e49df0900ed4cec6153c474d2d5bbad44dedbc7a", "external_requirements": [], "head_sha": "f1c8d30c48fed58fae3a07801a49e721d9ec4465", "objects": 1060, "objects_sha256": "b401448a16091bc05c8d30f0c8b9ae5c05e10b6b1e507cfad486bb84befe0534", "patch_sha256": "145e315819a33f2fae6b330af2e3646a517e99dce0636bf6a8cc39626fd20cda"}}, "pr_number": 504, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "57f812e45459", "description": "For large notes in a non-plain mode, the mode bubble was forced open even after blur or mouse leave, so users could not dismiss it.", "file_path": "src/components/editor/EditorViewModeSwitch.tsx"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "57f812e45459", "description": "Keyboard focus could make the mode bubble visible through CSS while the trigger still reported aria-expanded=\"false\"; focus now updates the component's open state instead.", "file_path": "src/components/editor/EditorViewModeSwitch.tsx"}, {"action_id": "A3", "action_type": "cleanup", "category": "style", "commit_sha": "57f812e45459", "description": "The external markdown stylesheet redundantly declared the bubble's top offset, which was already supplied by the base rule and the external switch's CSS variable.", "file_path": "src/styles/app/47-external-markdown.css"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "e719fc413167", "description": "In the external markdown window, the mode bubble was centered on a right-edge switch, causing its rightmost button to be clipped by the window.", "file_path": "src/styles/app/47-external-markdown.css"}], "commits_under_review": [{"author": "SidhuK", "date": "2026-08-16T07:29:03Z", "files": [{"additions": 38, "deletions": 21, "filename": "src/components/editor/EditorViewModeSwitch.tsx", "patch": "@@ -4,6 +4,7 @@ import {\n \tEyeIcon,\n \tPencilEdit02Icon,\n } from \"@hugeicons/core-free-icons\";\n+import { useState } from \"react\";\n import { useTranslation } from \"react-i18next\";\n import type { EditorViewMode } from \"../../lib/editorMode\";\n \n@@ -33,25 +34,48 @@ export function EditorViewModeSwitch({\n \tlargeNote = false,\n }: EditorViewModeSwitchProps) {\n \tconst { t } = useTranslation(\"editor\");\n+\tconst [isPinnedOpen, setIsPinnedOpen] = useState(false);\n+\tconst activeMode = VIEW_MODES.find((item) => item.id === mode);\n+\n+\tif (!activeMode) return null;\n+\n+\tconst activeLabel = t(activeMode.labelKey);\n+\tconst shouldShowBubble = isPinnedOpen || (largeNote && mode !== \"plain\");\n \treturn (\n \t\t {\n+\t\t\t\tconst nextFocus = event.relatedTarget;\n+\t\t\t\tif (\n+\t\t\t\t\tnextFocus instanceof Node &&\n+\t\t\t\t\tevent.currentTarget.contains(nextFocus)\n+\t\t\t\t) {\n+\t\t\t\t\treturn;\n+\t\t\t\t}\n+\t\t\t\tsetIsPinnedOpen(false);\n+\t\t\t}}\n+\t\t\tonMouseLeave={() => setIsPinnedOpen(false)}\n \t\t>\n-\t\t\t{VIEW_MODES.map((item) => {\n-\t\t\t\tconst label = t(item.labelKey);\n-\t\t\t\tconst isActive = mode === item.id;\n-\t\t\t\tconst showLargeNoteHint = largeNote && item.id !== \"plain\";\n-\t\t\t\tconst hint = showLargeNoteHint ? t(\"mode.largeNoteHint\") : label;\n+\t\t\t setIsPinnedOpen((open) => !open)}\n+\t\t\t>\n+\t\t\t\t\n+\t\t\t\n+\t\t\t
\n+\t\t\t\t{VIEW_MODES.map((item) => {\n+\t\t\t\t\tconst label = t(item.labelKey);\n+\t\t\t\t\tconst isActive = mode === item.id;\n \n-\t\t\t\treturn (\n-\t\t\t\t\t\n+\t\t\t\t\treturn (\n \t\t\t\t\t\t\n \t\t\t\t\t\t\t\n \t\t\t\t\t\t\n-\t\t\t\t\t\t\n-\t\t\t\t\t\t\t{hint}\n-\t\t\t\t\t\t\n-\t\t\t\t\t\n-\t\t\t\t);\n-\t\t\t})}\n+\t\t\t\t\t);\n+\t\t\t\t})}\n+\t\t\t
\n \t\t
\n \t);\n }", "status": "modified"}, {"additions": 2, "deletions": 1, "filename": "src/components/preview/MarkdownEditorPane.test.tsx", "patch": "@@ -27,6 +27,7 @@ vi.mock(\"react-i18next\", () => ({\n \t\t\t\t\"mode.raw\": \"Raw\",\n \t\t\t\t\"mode.rich\": \"Rich\",\n \t\t\t\t\"mode.preview\": \"Preview\",\n+\t\t\t\t\"toolbar.info\": \"Info\",\n \t\t\t};\n \t\t\treturn labels[key] ?? options?.defaultValue ?? key;\n \t\t},\n@@ -407,7 +408,7 @@ describe(\"MarkdownEditorPane\", () => {\n \t\t});\n \n \t\tconst infoButton = Array.from(container.querySelectorAll(\"button\")).find(\n-\t\t\t(button) => button.getAttribute(\"aria-label\") === \"Open info\",\n+\t\t\t(button) => button.getAttribute(\"aria-label\") === \"Info\",\n \t\t);\n \t\texpect(infoButton).not.toBeNull();\n \t\tawait act(async () => {", "status": "modified"}, {"additions": 6, "deletions": 16, "filename": "src/components/preview/MarkdownEditorPane.tsx", "patch": "@@ -4,6 +4,7 @@ import {\n \tLayoutAlignRightIcon,\n } from \"@hugeicons/core-free-icons\";\n import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\n+import { useTranslation } from \"react-i18next\";\n import {\n \tuseAISidebarContext,\n \tuseEditorRegistration,\n@@ -162,6 +163,7 @@ export function MarkdownEditorPane({\n \textractToNoteActions,\n \tactive = true,\n }: MarkdownEditorPaneProps) {\n+\tconst { t } = useTranslation(\"editor\");\n \tconst [infoPanelText, setInfoPanelText] = useState(\"\");\n \tconst preferredEditorModeRef = useRef(null);\n \tconst initialText = initialDoc?.text ?? peekCachedMarkdownDoc(relPath) ?? \"\";\n@@ -552,20 +554,8 @@ export function MarkdownEditorPane({\n \t\t\t\t\t\t\t\tsetInfoPanelOpen(() => false);\n \t\t\t\t\t\t\t\tsetAiPanelOpen((open) => !open);\n \t\t\t\t\t\t\t}}\n-\t\t\t\t\t\t\taria-label={\n-\t\t\t\t\t\t\t\taiEnabled\n-\t\t\t\t\t\t\t\t\t? aiPanelOpen\n-\t\t\t\t\t\t\t\t\t\t? \"Close AI panel\"\n-\t\t\t\t\t\t\t\t\t\t: \"Open AI panel\"\n-\t\t\t\t\t\t\t\t\t: \"Open AI settings\"\n-\t\t\t\t\t\t\t}\n-\t\t\t\t\t\t\ttitle={\n-\t\t\t\t\t\t\t\taiEnabled\n-\t\t\t\t\t\t\t\t\t? aiPanelOpen\n-\t\t\t\t\t\t\t\t\t\t? \"Close AI panel\"\n-\t\t\t\t\t\t\t\t\t\t: \"Open AI panel\"\n-\t\t\t\t\t\t\t\t\t: \"Open AI settings\"\n-\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\taria-label={t(\"toolbar.aiPanel\")}\n+\t\t\t\t\t\t\ttitle={t(\"toolbar.aiPanel\")}\n \t\t\t\t\t\t\taria-pressed={aiEnabled ? aiPanelOpen : undefined}\n \t\t\t\t\t\t>\n \t\t\t\t\t\t\t\n@@ -575,8 +565,8 @@ export function MarkdownEditorPane({\n \t\t\t\t\t\t\tclassName=\"markdownEditorToolbarBtn\"\n \t\t\t\t\t\t\tdata-active={infoPanelOpen || undefined}\n \t\t\t\t\t\t\tonClick={toggleInfoPanel}\n-\t\t\t\t\t\t\taria-label={infoPanelOpen ? \"Close info\" : \"Open info\"}\n-\t\t\t\t\t\t\ttitle={infoPanelOpen ? \"Close info\" : \"Open info\"}\n+\t\t\t\t\t\t\taria-label={t(\"toolbar.info\")}\n+\t\t\t\t\t\t\ttitle={t(\"toolbar.info\")}\n \t\t\t\t\t\t\taria-pressed={infoPanelOpen}\n \t\t\t\t\t\t>\n \t\t\t\t\t\t\t bool:\n+ details = f\"{error} {error.body or ''}\".casefold()\n+ return any(marker in details for marker in CONTEXT_OVERFLOW_MARKERS)\n+\n \n async def chat(\n client: AsyncOpenAI, model: str, messages: list[dict], tools: list[dict]\n@@ -181,7 +196,14 @@ async def main() -> None:\n elif args.prompt:\n messages.append({\"role\": \"user\", \"content\": args.prompt})\n while True:\n- message = await chat(client, args.model, messages, tools)\n+ try:\n+ message = await chat(client, args.model, messages, tools)\n+ except BadRequestError as error:\n+ # Context exhaustion is a budget limit, not a crash: this harness has no\n+ # compaction, so end the run cleanly with what the conversation holds.\n+ if not is_context_overflow(error):\n+ raise\n+ return\n messages.append(message.model_dump(exclude_none=True))\n if not message.tool_calls:\n break", "status": "modified"}, {"additions": 3, "deletions": 3, "filename": "verifiers/v1/rollout.py", "patch": "@@ -409,9 +409,9 @@ async def step(self, messages: Messages | None = None) -> bool:\n 0.0, self._agent_time_remaining - (loop.time() - segment_start)\n )\n self.deadline_at = None\n- if self._session.error is not None:\n- self.fail(self._session.error)\n- return False\n+ # A harness that completes cleanly after a failed model call handled it (e.g. it\n+ # ends its run on context overflow); the failure stays recorded on the call. A\n+ # harness that dies on it surfaces the stashed error through the except above.\n # A segment that committed nothing can't be waiting on the user; treating\n # it as continuable would consult the user against a conversation that\n # never moved, forever.", "status": "modified"}, {"additions": 4, "deletions": 4, "filename": "verifiers/v1/session.py", "patch": "@@ -131,10 +131,10 @@ class RolloutSession:\n `register` (one server-owned client per distinct endpoint config), so every rollout it\n multiplexes shares one keepalive connection pool instead of opening its own.\"\"\"\n error: \"RolloutError | None\" = None\n- \"\"\"The latest unresolved model-call failure. The harness only sees it as an HTTP error\n- (and may swallow it, or exit non-zero), so the rollout re-raises this original error once the\n- harness returns — recording the real `ProviderError` instead of a secondary `HarnessError`.\n- Reset before each model turn, so a successful retry clears it.\"\"\"\n+ \"\"\"The latest unresolved model-call failure. The harness only sees it as an HTTP error, so\n+ when its program dies on it the rollout records this original error instead of a secondary\n+ `HarnessError`. A harness that completes cleanly after the failure handled it. Reset before\n+ each model turn, so a successful retry clears it.\"\"\"\n idempotent_requests: dict[str, IdempotentRequest] = field(default_factory=dict)\n \"\"\"Explicit keys or marked SDK retries mapped to their replay state.\"\"\"\n released: bool = False", "status": "modified"}], "message": "end the null harness cleanly on context overflow\n\nThe null harness has no compaction, so a relayed overlong prompt\nerror killed its program and failed the rollout. Catch the overflow\nand return instead, ending the run with what the conversation\nholds. For the trace to stay ok the rollout must trust that exit:\nstop re-raising a stashed model-call error after a clean harness\ncompletion - a program that dies on it still surfaces the original\nerror through the harness exception path, and the failed call\nstays recorded on the trace either way.\n\nCo-Authored-By: Claude Fable 5 ", "sha": "814a3418a13faac66eae89105b14723711d7e3dc"}, {"author": "mikasenghaas", "date": "2026-08-27T21:32:19Z", "files": [{"additions": 22, "deletions": 6, "filename": "verifiers/v1/harnesses/null/program.py", "patch": "@@ -17,14 +17,30 @@\n MCP_CALL_ATTEMPTS = 6\n MCP_TIMEOUT = 600.0\n \n+# Overflow wording by provider, matched case-insensitively against the full error body.\n+# Each marker is attributed to the API that produces it; unattributable generics stay out\n+# (e.g. \"too many tokens\" also matches Bedrock throttling).\n CONTEXT_OVERFLOW_MARKERS = (\n- \"request entity too large\",\n- \"context_length\",\n- \"context length\",\n- \"context window\",\n+ # OpenAI error code \"context_length_exceeded\"; OpenRouter relays the raw body.\n+ \"context_length_exceeded\",\n+ # OpenAI Responses/Completions: \"Your input exceeds the context window of this model\".\n+ \"exceeds the context window\",\n+ # OpenAI chat: \"Input tokens exceed the configured limit of N tokens. Please reduce\n+ # the length of the messages.\"; Groq words it the same way.\n+ \"reduce the length of the messages\",\n+ # vLLM: \"This model's maximum context length is N tokens\"; the renderers pre-flight:\n+ # \"Prompt length (N) exceeds maximum context length (M)\"; Mistral uses the same words.\n+ \"maximum context length\",\n+ # Anthropic: \"prompt is too long: N tokens > M maximum\".\n \"prompt is too long\",\n- \"too many tokens\",\n- \"token limit exceeded\",\n+ # Anthropic byte-size overflow: HTTP 413 {\"type\": \"request_too_large\"}.\n+ \"request_too_large\",\n+ # HTTP proxies reject an oversized body with 413 \"Request Entity Too Large\".\n+ \"request entity too large\",\n+ # Google: \"The input token count (N) exceeds the maximum number of tokens allowed (M)\".\n+ \"exceeds the maximum number of tokens\",\n+ # xAI: \"This model's maximum prompt length is N but the request contains M tokens\".\n+ \"maximum prompt length is\",\n )\n \n ", "status": "modified"}], "message": "attribute overflow markers to their providers\n\nEach marker now names the API whose error wording it matches, and\nthe unattributable generics are gone - \"too many tokens\" also\nmatches Bedrock throttling, and bare \"context length\"/\"context\nwindow\" substrings matched more than they targeted.\n\nCo-Authored-By: Claude Fable 5 ", "sha": "426b36e78679579a068b9fe67bd359ca532a4eb2"}], "post_review_commits": ["f00bf5d9672763e342467731033b245712945952"], "pr_author": "mikasenghaas", "pr_title": "fix: end the null harness cleanly on context overflow", "repo_name": "PrimeIntellect-ai/verifiers"}, "repo": "PrimeIntellect-ai/verifiers", "snapshot": "snapshots/06e2c064a9530afeee7a2c76b6494843a69c07654fbe965aae5959e7e196b4e4.pack", "split": "rl", "task_id": "5c5e19ae7fdb7a5326a400ff3f6435614e6f38fd8b9bd1f0f234435984be0d17"} {"base_sha": "f823d33fd4b177713f2b756641fa4f8f1c52c5e8", "cohort": null, "context": {"canonical_pr_url": "https://github.com/oasisbaklawa2006/Oasis-Baklawa-Central/pull/236", "id": "5d23a331958b1141c8cfafb5989531109c7ee0449ec5f928652f57c8cd70b86e", "preparation_mode": "source-only", "snapshot": {"base_ref": "f823d33fd4b177713f2b756641fa4f8f1c52c5e8", "base_sha": "f823d33fd4b177713f2b756641fa4f8f1c52c5e8", "body": "", "head_ref": "aa2d99f60b58df2cc25ee195fb147d003eaf934a", "head_sha": "aa2d99f60b58df2cc25ee195fb147d003eaf934a", "name": "Oasis-Baklawa-Central", "number": 236, "owner": "oasisbaklawa2006", "pr_url": "https://github.com/oasisbaklawa2006/Oasis-Baklawa-Central/pull/236", "title": ""}}, "head_sha": "aa2d99f60b58df2cc25ee195fb147d003eaf934a", "metadata": {"group_id": "6dde624acef7eabc6250a4403acce721001f69e38e6cf40a6d7321e396420682", "snapshot": {"base_sha": "f823d33fd4b177713f2b756641fa4f8f1c52c5e8", "external_requirements": [], "head_sha": "aa2d99f60b58df2cc25ee195fb147d003eaf934a", "objects": 1755, "objects_sha256": "dcd8e8a71a2ad0e4e198691f1b72fef0fa8d33ae024a6e1e37f3beea93501a16", "patch_sha256": "7088d2a98f12f5746b6fa233559443427b299774c309f6b09f9a6673f604b083"}}, "pr_number": 236, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "c467d7376ef3", "description": "Inbound intake insertion ignored duplicates only on source_message_id; a conflict with another unique constraint could still fail the trigger instead of being tolerated.", "file_path": "supabase/migrations/20260718190000_wa_zero_loss_inbound_wiring.sql"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "c467d7376ef3", "description": "Inbound intake and its associated event lacked explicit sender, original-communicator, and commercial-customer attribution, leaving missing identities and unresolved customer status unrecorded.", "file_path": "supabase/migrations/20260718190000_wa_zero_loss_inbound_wiring.sql"}, {"action_id": "A3", "action_type": "improvement", "category": "other", "commit_sha": "101ab948bcdc", "description": "Migration tests did not guard against source-message-only conflict handling or verify that the identity triad is persisted without assigning an unverified commercial customer.", "file_path": "src/lib/wa-governance/tests/whatsappZeroLossInboundWiringMigration.test.ts"}], "commits_under_review": [{"author": "oasisbaklawa2006", "date": "2026-07-18T17:51:41Z", "files": [{"additions": 122, "deletions": 0, "filename": "supabase/migrations/20260718190000_wa_zero_loss_inbound_wiring.sql", "patch": "@@ -0,0 +1,122 @@\n+-- WhatsApp B2B zero-loss inbound wiring.\n+-- Canonical authority:\n+-- docs/WHATSAPP_CANONICAL_INTENT_AND_ZERO_LOSS_GOVERNANCE.md\n+-- docs/WHATSAPP_B2B_DOMAIN_BOUNDARY_AND_APP_PLACEMENT.md\n+-- Foundation migration:\n+-- 20260718173000_wa_zero_loss_intake_foundation.sql\n+--\n+-- Scope: every durable inbound WhatsApp message written to whatsapp_messages\n+-- receives exactly one governed intake record. This migration does not write\n+-- orders, order_items, sales_order_drafts, finance, dispatch, or inventory.\n+\n+create unique index whatsapp_business_intakes_source_message_unique\n+ on public.whatsapp_business_intakes(source_message_id)\n+ where source_message_id is not null;\n+\n+create or replace function public.capture_whatsapp_business_intake_from_message()\n+returns trigger\n+language plpgsql\n+security definer\n+set search_path = pg_catalog, public\n+as $$\n+declare\n+ normalized_content text := lower(coalesce(new.content, ''));\n+ inferred_kind text;\n+ inferred_state text;\n+ inferred_next_action text;\n+ created_intake_id uuid;\n+begin\n+ if new.direction is distinct from 'inbound' then\n+ return new;\n+ end if;\n+\n+ -- Noise and unsupported webhook events are filtered before whatsapp_messages.\n+ -- Any message that reaches this durable table must remain visible until classified.\n+ if\n+ normalized_content ~ '(order|need|send|want|box|boxes|carton|cartons|kg|pcs|pieces|rate|price|quote)'\n+ or normalized_content ~ '(sales order|purchase order|repeat order|same as before|previous order)'\n+ then\n+ inferred_kind := 'POTENTIAL_ORDER';\n+ inferred_state := 'RECEIVED';\n+ inferred_next_action := 'Review potential order and confirm customer, product, quantity, delivery, and commercial readiness.';\n+ elsif\n+ new.media_url is not null\n+ or coalesce(new.message_type, '') in ('image', 'document', 'audio', 'video')\n+ then\n+ inferred_kind := 'UNRESOLVED_RISK';\n+ inferred_state := 'AWAITING_CLASSIFICATION';\n+ inferred_next_action := 'Inspect inbound media and classify all business intents; preserve as unresolved risk until reviewed.';\n+ else\n+ inferred_kind := 'NON_ORDER_BUSINESS';\n+ inferred_state := 'AWAITING_CLASSIFICATION';\n+ inferred_next_action := 'Classify inbound WhatsApp message and route every identified business intent.';\n+ end if;\n+\n+ insert into public.whatsapp_business_intakes (\n+ business_domain,\n+ source_message_id,\n+ provider_message_id,\n+ intake_kind,\n+ lifecycle_state,\n+ disposition,\n+ assigned_team,\n+ next_action,\n+ reconciliation_status,\n+ metadata\n+ ) values (\n+ 'B2B',\n+ new.id,\n+ new.provider_message_id,\n+ inferred_kind,\n+ inferred_state,\n+ 'ACTIVE_PENDING',\n+ 'WHATSAPP_INTAKE',\n+ inferred_next_action,\n+ 'ACCOUNTED',\n+ jsonb_build_object(\n+ 'capture_source', 'whatsapp_messages_after_insert_trigger',\n+ 'message_type', new.message_type,\n+ 'contact_id', new.contact_id,\n+ 'captured_at', now()\n+ )\n+ )\n+ on conflict (source_message_id) where source_message_id is not null\n+ do nothing\n+ returning id into created_intake_id;\n+\n+ if created_intake_id is not null then\n+ insert into public.whatsapp_business_intake_audit_log (\n+ intake_id,\n+ event_type,\n+ actor_user_id,\n+ event_data\n+ ) values (\n+ created_intake_id,\n+ 'INBOUND_CAPTURED',\n+ null,\n+ jsonb_build_object(\n+ 'source_message_id', new.id,\n+ 'provider_message_id', new.provider_message_id,\n+ 'intake_kind', inferred_kind,\n+ 'lifecycle_state', inferred_state,\n+ 'assigned_team', 'WHATSAPP_INTAKE'\n+ )\n+ );\n+ end if;\n+\n+ return new;\n+end;\n+$$;\n+\n+revoke all on function public.capture_whatsapp_business_intake_from_message() from public;\n+revoke all on function public.capture_whatsapp_business_intake_from_message() from anon;\n+revoke all on function public.capture_whatsapp_business_intake_from_message() from authenticated;\n+\n+drop trigger if exists trg_capture_whatsapp_business_intake on public.whatsapp_messages;\n+create trigger trg_capture_whatsapp_business_intake\n+after insert on public.whatsapp_messages\n+for each row\n+execute function public.capture_whatsapp_business_intake_from_message();\n+\n+comment on function public.capture_whatsapp_business_intake_from_message() is\n+ 'Captures every durable inbound WhatsApp message into the governed B2B zero-loss intake ledger. Never creates executable orders.';", "status": "added"}], "message": "feat(whatsapp): wire inbound messages to zero-loss intake ledger", "sha": "bfc6421fc537325dd96e325dc9dc444a67b56697"}, {"author": "oasisbaklawa2006", "date": "2026-07-18T17:52:03Z", "files": [{"additions": 84, "deletions": 0, "filename": "src/lib/wa-governance/tests/whatsappZeroLossInboundWiringMigration.test.ts", "patch": "@@ -0,0 +1,84 @@\n+import { readFileSync } from \"node:fs\";\n+import { join } from \"node:path\";\n+import { describe, expect, it } from \"vitest\";\n+\n+const REPO_ROOT = join(import.meta.dirname, \"../../../..\");\n+const MIGRATION_PATH = \"supabase/migrations/20260718190000_wa_zero_loss_inbound_wiring.sql\";\n+\n+function readMigration(): string {\n+ return readFileSync(join(REPO_ROOT, MIGRATION_PATH), \"utf8\");\n+}\n+\n+describe(\"WhatsApp zero-loss inbound wiring migration\", () => {\n+ const sql = readMigration();\n+\n+ it(\"traces to the canonical governance documents and foundation migration\", () => {\n+ expect(sql).toContain(\"docs/WHATSAPP_CANONICAL_INTENT_AND_ZERO_LOSS_GOVERNANCE.md\");\n+ expect(sql).toContain(\"docs/WHATSAPP_B2B_DOMAIN_BOUNDARY_AND_APP_PLACEMENT.md\");\n+ expect(sql).toContain(\"20260718173000_wa_zero_loss_intake_foundation.sql\");\n+ });\n+\n+ it(\"enforces exactly one intake per durable source message\", () => {\n+ expect(sql).toContain(\"whatsapp_business_intakes_source_message_unique\");\n+ expect(sql).toContain(\"on conflict (source_message_id) where source_message_id is not null\");\n+ expect(sql).toContain(\"do nothing\");\n+ });\n+\n+ it(\"captures only inbound whatsapp_messages rows\", () => {\n+ expect(sql).toContain(\"after insert on public.whatsapp_messages\");\n+ expect(sql).toContain(\"new.direction is distinct from 'inbound'\");\n+ });\n+\n+ it(\"keeps every captured message active, owned, and actionable\", () => {\n+ expect(sql).toContain(\"'ACTIVE_PENDING'\");\n+ expect(sql).toContain(\"'WHATSAPP_INTAKE'\");\n+ expect(sql).toContain(\"inferred_next_action\");\n+ expect(sql).toContain(\"'ACCOUNTED'\");\n+ });\n+\n+ it(\"treats order-like text as a potential order\", () => {\n+ expect(sql).toContain(\"inferred_kind := 'POTENTIAL_ORDER'\");\n+ expect(sql).toContain(\"inferred_state := 'RECEIVED'\");\n+ });\n+\n+ it(\"preserves media as unresolved risk until classification\", () => {\n+ expect(sql).toContain(\"inferred_kind := 'UNRESOLVED_RISK'\");\n+ expect(sql).toContain(\"inferred_state := 'AWAITING_CLASSIFICATION'\");\n+ expect(sql).toContain(\"Inspect inbound media and classify all business intents\");\n+ });\n+\n+ it(\"retains non-order business messages for governed classification\", () => {\n+ expect(sql).toContain(\"inferred_kind := 'NON_ORDER_BUSINESS'\");\n+ expect(sql).toContain(\"Classify inbound WhatsApp message and route every identified business intent\");\n+ });\n+\n+ it(\"writes an append-only audit event for each new intake\", () => {\n+ expect(sql).toContain(\"whatsapp_business_intake_audit_log\");\n+ expect(sql).toContain(\"'INBOUND_CAPTURED'\");\n+ });\n+\n+ it(\"does not expose the security-definer trigger function for direct invocation\", () => {\n+ expect(sql).toContain(\"security definer\");\n+ expect(sql).toContain(\"set search_path = pg_catalog, public\");\n+ expect(sql).toContain(\"revoke all on function public.capture_whatsapp_business_intake_from_message() from public\");\n+ expect(sql).toContain(\"revoke all on function public.capture_whatsapp_business_intake_from_message() from anon\");\n+ expect(sql).toContain(\"revoke all on function public.capture_whatsapp_business_intake_from_message() from authenticated\");\n+ });\n+\n+ it(\"never writes executable order, finance, dispatch, or inventory rows\", () => {\n+ for (const table of [\n+ \"orders\",\n+ \"order_items\",\n+ \"sales_order_drafts\",\n+ \"sales_order_draft_lines\",\n+ \"payments\",\n+ \"invoices\",\n+ \"dispatches\",\n+ \"inventory\",\n+ ]) {\n+ expect(sql).not.toMatch(new RegExp(`insert\\\\s+into\\\\s+public\\\\.${table}`, \"i\"));\n+ expect(sql).not.toMatch(new RegExp(`update\\\\s+public\\\\.${table}`, \"i\"));\n+ expect(sql).not.toMatch(new RegExp(`delete\\\\s+from\\\\s+public\\\\.${table}`, \"i\"));\n+ }\n+ });\n+});", "status": "added"}], "message": "test(whatsapp): cover zero-loss inbound wiring contract", "sha": "aa2d99f60b58df2cc25ee195fb147d003eaf934a"}], "post_review_commits": ["c467d7376ef3d0d80ab4afa78a0beeb54b032d0a", "101ab948bcdc262bb56be1b7146a0a89c8acb287"], "pr_author": "oasisbaklawa2006", "pr_title": "feat: wire inbound WhatsApp messages to zero-loss intake", "repo_name": "oasisbaklawa2006/Oasis-Baklawa-Central"}, "repo": "oasisbaklawa2006/Oasis-Baklawa-Central", "snapshot": "snapshots/6dde624acef7eabc6250a4403acce721001f69e38e6cf40a6d7321e396420682.pack", "split": "rl", "task_id": "5d23a331958b1141c8cfafb5989531109c7ee0449ec5f928652f57c8cd70b86e"} {"base_sha": "b74e3591a7dd439d1a30441110b403706adfba15", "cohort": null, "context": {"canonical_pr_url": "https://github.com/cargotapan-collab/tac-express/pull/101", "id": "5d25972a30e701c66b68c44d8fa8227b668768860bc1ec1ce3ab57b56a556a75", "preparation_mode": "source-only", "snapshot": {"base_ref": "b74e3591a7dd439d1a30441110b403706adfba15", "base_sha": "b74e3591a7dd439d1a30441110b403706adfba15", "body": "", "head_ref": "c9db88e2fa7107c09ff13bbca3a7e9e078bfab5d", "head_sha": "c9db88e2fa7107c09ff13bbca3a7e9e078bfab5d", "name": "tac-express", "number": 101, "owner": "cargotapan-collab", "pr_url": "https://github.com/cargotapan-collab/tac-express/pull/101", "title": ""}}, "head_sha": "c9db88e2fa7107c09ff13bbca3a7e9e078bfab5d", "metadata": {"group_id": "a4837f66e1743ac9f0902726484db022e82e3cfe56bc6cf858a349a74491fb43", "snapshot": {"base_sha": "b74e3591a7dd439d1a30441110b403706adfba15", "external_requirements": [], "head_sha": "c9db88e2fa7107c09ff13bbca3a7e9e078bfab5d", "objects": 1458, "objects_sha256": "b354f2c92ab7bcf01059d0a3502457061541441e569ac9c0d88fa9527d773a23", "patch_sha256": "8b258245594e5ef2250655f30ce7303644102bf371b1c5c981c31824dae77d63"}}, "pr_number": 101, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "documentation", "commit_sha": "ed18d1272628", "description": "The runbook incorrectly said production Sentry environment variables were not set and captureException was a no-op, contradicting verified production event delivery. The remaining gap was alert notifications, not telemetry wiring.", "file_path": "docs/PRODUCTION-RUNBOOK.md"}, {"action_id": "A2", "action_type": "improvement", "category": "security", "commit_sha": "ed18d1272628", "description": "The runbook embedded literal production Sentry DSNs, making rotation harder and setting a poor precedent for documenting credentials; it also lacked an explicit warning against committing a real SENTRY_AUTH_TOKEN.", "file_path": "docs/PRODUCTION-RUNBOOK.md"}, {"action_id": "A3", "action_type": "fix", "category": "documentation", "commit_sha": "ed18d1272628", "description": "The runbook repeated the alert-rule setup in two steps and did not clearly explain that the diagnostic smoke test uses the sentry_smoke_test tag, so it cannot verify an alert filtered to payment_response_lost.", "file_path": "docs/PRODUCTION-RUNBOOK.md"}], "commits_under_review": [{"author": "cargotapan-collab", "date": "2026-05-15T00:37:06Z", "files": [{"additions": 236, "deletions": 0, "filename": "docs/PRODUCTION-READINESS-REPORT-2026-05-15.md", "patch": "@@ -0,0 +1,236 @@\n+# TAC Express — Production-Readiness Report\n+\n+**Date:** 2026-05-15 \n+**Authored by:** Claude (CTO/PM mode) \n+**Audit scope:** Full monorepo — security, code health, CI/CD, ops, tests, docs \n+**Audit method:** Four parallel exploration agents + cross-validation against live production state\n+\n+---\n+\n+## TL;DR — where we stand\n+\n+**The good news:** TAC Express is in much better shape than this morning. The Path A migration reconciliation closed the P0 silent-divergence issue (#78), the advisor warnings dropped 48 → 13 (#79), Sentry is verified live (#22 closed earlier), and the CI migration gate is now load-bearing.\n+\n+**The honest news:** there are real production-readiness gaps that the recent firefighting masked. None are launch-blockers in the sense of \"production breaks tomorrow,\" but several would convert ANY incident into a multi-hour blind triage session because we'd lack the test coverage, observability, or runbook to recover quickly.\n+\n+**Top 5 immediate moves** (each ~1-3 hours of work):\n+\n+1. **Update PRODUCTION-RUNBOOK.md** — three load-bearing claims are stale (Sentry not wired, invoice_payments missing, two phantom migrations). Done in this PR.\n+2. **Add `/api/health` endpoint** — `proxy.ts` already whitelists it but no handler exists. ~10 LOC fix.\n+3. **Add unit tests for `payment.service.ts` + `record_invoice_payment` RPC** — financial code with zero tests is the single biggest correctness risk. Tests would have caught the OPERATOR role bug before it ever shipped.\n+4. **Fix the 5 production bugs Sentry surfaced (#93)** — three of them are `transformAlgorithm` recurrences on `/ops-console`, the other two are missing icon imports. Cheap fixes, real visible bugs.\n+5. **Wire Sentry alert rules (#94)** — events arrive in Sentry, but no rule fires a notification. If the dashboard breaks at 3am, no one knows.\n+\n+Detail below. Each finding cites file:line where applicable.\n+\n+---\n+\n+## Methodology\n+\n+I spawned four read-only exploration agents in parallel, each scoped to one dimension:\n+1. **Security** — secrets, auth surface, public APIs, signing, forbidden packages\n+2. **Code health** — dead code, type debt, orphaned components, duplicate patterns\n+3. **CI/CD + tests** — workflow health, soft-fails, test coverage by package, E2E gaps\n+4. **Ops + observability** — Sentry, logging, runbooks, background jobs, public surfaces\n+\n+Then I **cross-validated** their findings against current production state via Supabase MCP and direct file reads. This caught stale documentation pretending to be ground truth — see \"Validation deltas\" below.\n+\n+---\n+\n+## Validation deltas (audit vs. reality)\n+\n+The ops audit report was reading `docs/PRODUCTION-RUNBOOK.md` which **predates the May 14-15 reconciliation**. Three \"critical\" claims it surfaced are no longer true:\n+\n+| Stale runbook claim | Actual current state | Caught how |\n+|---|---|---|\n+| `invoice_payments` table does not exist | **Exists in production** — verified via `list_tables` and the live `record_invoice_payment` RPC | Path A baseline includes it; PR #97 + #100 deployed the corrective work |\n+| `record_invoice_payment` RPC does not exist | **Exists and works** — deployed via PR #97 + #100 | `has_function_privilege('authenticated', oid, 'EXECUTE')` returns true |\n+| `SENTRY_DSN` not yet set in production | **Set and verified** — Sentry receives events end-to-end | Issue #22 closed earlier this session with verification evidence |\n+| Migrations `20260501000001` + `20260501000002` need to be added | These filenames never existed; the work landed under different filenames | Path A consolidated baseline includes the table + RPC |\n+\n+These deltas are themselves a finding — runbooks rot fast. The runbook fix lands in this same PR.\n+\n+---\n+\n+## Section 1 — Security\n+\n+**Headline:** No critical vulnerabilities. Two sprint-worthy hardening items. Several patterns to praise (which is why I'm calling them out as \"this is correct, don't regress\").\n+\n+### 1.1 Critical findings\n+**None.**\n+\n+### 1.2 Sprint-worthy\n+- **`INVOICE_PDF_SIGNING_SECRET` validation is length-only** — accepts any 64-char string, including non-hex like `aaaaaaaa…`. A misconfigured operator could set a weak secret without warning.\n+ - File: [packages/services/src/pdf/invoice-pdf-token.ts:56-70](packages/services/src/pdf/invoice-pdf-token.ts:56)\n+ - Fix: add `if (!/^[0-9a-f]{64}$/i.test(secret)) throw …`\n+ - Effort: 5 minutes\n+- **WhatsApp rate-limit bucket scope undocumented** — risk of future endpoints colliding on the same bucket key.\n+ - File: [apps/dashboard/lib/rate-limit.ts:51-58](apps/dashboard/lib/rate-limit.ts:51)\n+ - Fix: JSDoc above each export listing its consumers\n+ - Effort: 10 minutes\n+\n+### 1.3 Patterns to preserve (don't regress these)\n+- `apps/dashboard/lib/public-origin.ts:41-95` — `isPubliclyReachableHttpUrl()` correctly blocks loopback / RFC1918 / IPv6-ULA / IPv4-mapped IPv6 bypasses. Keep this.\n+- ESLint forbidden-package gates work — zero `axios`/`moment`/`lodash` violations in the tree.\n+- `SUPABASE_SERVICE_ROLE_KEY` is correctly confined to Edge Functions only.\n+- Sentry replay integration masks all text + blocks all media + redacts Supabase URLs in breadcrumbs. Privacy-by-default.\n+\n+---\n+\n+## Section 2 — Code health\n+\n+**Headline:** TypeScript strictness is broadly good. The two real issues are: (1) `as unknown as` escape hatches that paper over real type bugs, and (2) ~10 orphaned components in `packages/ui` that confuse the canonical-pattern story.\n+\n+### 2.1 Critical (silent-failure risk)\n+- **`as unknown as` casts indicate type-contract drift** — these compile but break in production.\n+ - [apps/dashboard/app/api/public/invoice-pdf/route.ts:118](apps/dashboard/app/api/public/invoice-pdf/route.ts:118) — `headerBuffer` cast\n+ - [apps/dashboard/app/ops-console/finance/create/ops-create-invoice-live.tsx:88](apps/dashboard/app/ops-console/finance/create/ops-create-invoice-live.tsx:88) — `invoice as Record` (the type should already be correct)\n+ - [apps/dashboard/proxy.ts:21-22](apps/dashboard/proxy.ts:21) — middleware client cast (×2)\n+ - [apps/dashboard/app/track/[awb]/page.tsx](apps/dashboard/app/track/[awb]/page.tsx) — repeated `shipment as unknown as { serviceLevel?: string }` cast — the shipment type is missing `serviceLevel`, fix at the type definition\n+- **Action:** Sprint-sized cleanup PR. Each cast either reveals a missing type field or a real bug.\n+\n+### 2.2 Sprint-worthy\n+- **Orphaned UI components** (zero imports, not exported) — clutter that makes \"what's the canonical pattern?\" unclear:\n+ - `packages/ui/src/components/composed/dashboard-header.tsx`\n+ - `packages/ui/src/components/composed/lottie-hero.tsx`\n+ - `packages/ui/src/components/composed/marquee.tsx`\n+ - `packages/ui/src/components/composed/text-matrix-rain.tsx`\n+ - 7 dashboard cards in `packages/ui/src/components/composed/dashboard/`\n+ - **Action:** Either re-export with intent + docs, or move to `packages/ui/src/components/_archive/`\n+\n+- **Duplicate form variants** — both kept \"for fallback\" but no living doc says which is canonical:\n+ - `customer-form.tsx` vs `v7-customer-form.tsx`\n+ - `rate-card-form.tsx` vs `ops-rate-card-form.tsx`\n+ - **Action:** Pick a winner per domain in CLAUDE.md or archive the loser.\n+\n+### 2.3 Backlog\n+- A few `eslint-disable` comments without owner/issue links. Three locations, all in known-edge cases (realtime hooks, exhaustive-deps).\n+\n+---\n+\n+## Section 3 — CI/CD + Test coverage\n+\n+**Headline:** Workflow health is great post-#99. Test coverage has critical holes — `packages/auth` and `packages/database` have **zero unit tests**, and most domain services are untested.\n+\n+### 3.1 Critical\n+- **`packages/auth` has 0 unit tests** — session helpers, `withRole()`, role checks. A regression here means privilege escalation could ship without anyone noticing.\n+- **`packages/database` has 0 unit tests** — generated types + query helpers. Schema drift between repo and runtime would only surface in production.\n+- **`payment.service.ts` (12.8KB), `invoice.service.ts` (7.9KB), `shipment.service.ts` (9.2KB), `manifest.service.ts` (7.3KB)** — all untested. These are the financial + domain core. The OPERATOR role bug we fixed today (#97) would have been caught by a single test on `record_invoice_payment`.\n+- **No dependency vulnerability scanning** — no `pnpm audit` in CI, no Dependabot. The 18KB `whatsapp.service.ts` and the payment service depend on external SDKs with no SCA coverage.\n+\n+### 3.2 Sprint-worthy E2E gaps\n+Critical user flows not covered end-to-end:\n+- ❌ **Payment recording happy path** — wizard renders but POST + assert not exercised\n+- ❌ **Full shipment creation** (steps 2-4) — only step 1 covered\n+- ❌ **Manifest with bulk shipment selection** — only step 1 covered\n+- ❌ **Role-based RLS isolation** — no E2E proves WAREHOUSE user can't see other hubs' data\n+- ❌ **Exception lifecycle** — create / escalate / resolve untested\n+\n+### 3.3 Workflow health (good)\n+- ✅ `migrations-fresh-apply` is now load-bearing (PR #99)\n+- ✅ All actions on v4+ (no deprecated versions)\n+- ✅ Architecture gates run on PR + push to main\n+- ✅ Path filters scoped correctly\n+\n+---\n+\n+## Section 4 — Operations + observability\n+\n+**Headline:** The plumbing is good. The runbook is stale and there are gaps in failure-mode coverage that would slow incident response.\n+\n+### 4.1 Critical (validated)\n+- **No `/api/health` endpoint handler exists** — `proxy.ts:29` whitelists it as public but there's no route. Load balancers and external monitors can't health-check the app.\n+ - File needed: `apps/dashboard/app/api/health/route.ts` (~10 LOC)\n+- **WhatsApp has no delivery audit table or retry path** — kill-switch exists, but if WPBox returns 200 with `wamid: null` (silent rejection), the message is lost forever and ops have no way to know.\n+ - Recommended: add `whatsapp_sends` audit table + scheduled poll job\n+- **Sentry alert rules not wired** — events arrive (verified) but no rule fires a notification. Tracked separately as #94. **THIS is the #22 carve-out** that's still open.\n+\n+### 4.2 Sprint-worthy\n+- **Console-only logging** in route handlers and server actions — no structured logger, no request-correlation IDs. Triage requires raw substring grep.\n+ - Locations: `apps/dashboard/app/api/whatsapp/send-invoice/route.ts:426,432,443,473,506,530`, `apps/dashboard/app/api/diagnostics/sentry/route.ts:59,67`, `apps/dashboard/app/api/public/invoice-pdf/route.ts:55,123`\n+- **Edge function cron registration not documented** — `scheduled-sla-monitor` exists but the runbook doesn't say how it's scheduled or how to verify it runs\n+- **No PITR / restore playbook** — runbook mentions PITR but has no \"database lost — restore\" procedure\n+- **No Upstash outage scenario** — if Redis is down, rate-limit fails open. No runbook mentions this.\n+\n+### 4.3 Backlog\n+- No on-call schedule or escalation policy in runbook\n+- No live links to Sentry / Vercel / Supabase / Upstash dashboards in the runbook\n+- No audit trail table for destructive ops (invoice cancellation, payment deletion)\n+\n+### 4.4 Stale runbook entries (fixed in this PR)\n+- Lines 195-209 of `PRODUCTION-RUNBOOK.md` claim `invoice_payments` and `record_invoice_payment` don't exist — both are live in production as of today\n+- Lines 224-232 claim `SENTRY_DSN` is not set in production — verified set, events flow end-to-end\n+- Lines 205-206 reference migration filenames `20260501000001`/`20260501000002` that never existed; the actual work landed under the consolidated Path A baseline\n+\n+---\n+\n+## Section 5 — Documentation hygiene\n+\n+- ✅ `CLAUDE.md` is current and well-maintained\n+- ✅ ADR Decision 8 captures the Path A pivot\n+- ✅ Migration drift catalog documents the divergence in detail\n+- ❌ `PRODUCTION-RUNBOOK.md` had three stale load-bearing claims (fixed in this PR)\n+- ❌ No `RELEASE-CHECKLIST.md` documenting the release process\n+- ❌ No `DATABASE-RESTORE.md` for PITR scenarios\n+- ❌ Several files in `docs/` without clear ownership (likely candidates for archive: `AUDIT-FIXES-PLAN-2026-05-14.md`, `NEXT-SESSION-HANDOFF.md`, `SESSION-RETRO-2026-05-14.md` — these were session-scratchpads, not living docs)\n+\n+---\n+\n+## Section 6 — Action plan\n+\n+### Immediate (this PR or next, ~1-3 hours each)\n+- [x] Update `PRODUCTION-RUNBOOK.md` — done in this PR\n+- [ ] Add `/api/health` endpoint\n+- [ ] Fix the 5 production bugs Sentry surfaced (#93)\n+- [ ] Add `INVOICE_PDF_SIGNING_SECRET` hex-format validation\n+\n+### Sprint 1 (~1 week)\n+- [ ] Unit tests for `payment.service.ts`, `record_invoice_payment` RPC, `invoice.service.ts`\n+- [ ] Unit tests for `packages/auth` (session + withRole + RBAC helpers)\n+- [ ] Wire Sentry alert rules + notification action (#94)\n+- [ ] Fix `as unknown as` casts (cleanup PR)\n+- [ ] Add `pnpm audit --production` job to architecture-gates.yml\n+- [ ] Enable Dependabot for monorepo\n+\n+### Sprint 2 (~1 week)\n+- [ ] E2E coverage for payment recording happy path\n+- [ ] E2E coverage for full shipment creation (steps 2-4)\n+- [ ] E2E coverage for full manifest creation with bulk select\n+- [ ] Unit tests for `shipment.service.ts`, `manifest.service.ts`, `whatsapp.service.ts`\n+- [ ] WhatsApp audit table + scheduled delivery poll\n+- [ ] Structured logger (pino) across route handlers\n+\n+### Backlog (track but no committed sprint)\n+- [ ] Archive orphaned UI components or document their purpose\n+- [ ] Pick canonical form variant per domain (v7 vs v6) and archive the loser\n+- [ ] PITR restore playbook\n+- [ ] Upstash outage runbook entry\n+- [ ] On-call schedule + escalation policy\n+- [ ] Live monitoring dashboard links in runbook\n+- [ ] `audit_logs` table for destructive operations\n+\n+---\n+\n+## Section 7 — What's not in this report (out of scope)\n+\n+- **Performance audit** — bundle size CI gate exists; Lighthouse scores not measured\n+- **A11y audit** — `e2e/a11y.spec.ts` runs AXE; no comprehensive WCAG conformance review\n+- **i18n** — single-locale today; no i18n infrastructure\n+- **Mobile / responsive audit** — VRT covers desktop only at this point\n+- **Cost optimization** — no review of Supabase / Vercel / Upstash spend curves\n+\n+These are legitimate areas but outside this audit's scope. Track separately if/when they become priority.\n+\n+---\n+\n+## How to use this report\n+\n+1. **Owner reviews** the immediate-section action items, prioritizes top 3-5\n+2. **Each remaining item gets its own GitHub issue** — referenced from a single tracking issue (created alongside this PR)\n+3. **Re-audit cadence:** Recommend running this same parallel-agent audit at the end of every major project phase (e.g., after Phase 5 / Phase 6) to catch drift early\n+\n+The biggest correctness risk on this list is the **0% test coverage on financial services**. Everything else has a workaround; financial bugs cost real money and are nearly impossible to detect post-fact.\n+\n+---\n+\n+*Generated 2026-05-15 from a clean main (post-PR #100). Re-run by spawning the same four Explore agents — prompts saved in this session's transcript.*", "status": "added"}, {"additions": 20, "deletions": 25, "filename": "docs/PRODUCTION-RUNBOOK.md", "patch": "@@ -110,8 +110,8 @@ EWAYBILL_PASSWORD=\n ### D. Observability\n \n - [ ] **Sentry Next.js project created** in `tapan-cargo-az` org (audited 2026-05-08: only `react-native` exists — wrong runtime; create a separate `tac-express-dashboard` project before relying on captures)\n-- [ ] **`SENTRY_DSN` + `NEXT_PUBLIC_SENTRY_DSN` set in production env** — without these, every `Sentry.captureException()` call (including the `payment_response_lost` capture in `apps/dashboard/app/(dashboard)/finance/[id]/invoice-detail-client.tsx`) is a SILENT NO-OP\n-- [ ] **Alert rule configured**: filter `tags[kind]:payment_response_lost` → notify ops within 5 min. This is the trigger condition the route handler tags for; without it, lost-payment-confirmation events land in Sentry but nobody sees them\n+- [x] **`SENTRY_DSN` + `NEXT_PUBLIC_SENTRY_DSN` set in production env** — verified 2026-05-15 via `mcp__sentry__search_issues` (real production events flowing)\n+- [ ] **Alert rule configured** — Sentry events arrive but no notification rule yet. Tracked in #94. Filter on `tags[kind]:payment_response_lost` → notify ops within 5 min once configured.\n - [ ] Sentry alert rules: any error in production tagged `level: error`\n - [ ] Sentry source maps uploaded per release (`SENTRY_RELEASE` env var on every deploy)\n - [ ] Sentry replay budget set — see `sentry.client.config.ts` (5% session sample, 100% on error)\n@@ -190,39 +190,34 @@ EWAYBILL_PASSWORD=\n 3. If stuck: clear failed items from the scan queue UI on `/scanning`, ask driver to re-capture.\n 4. Storage bucket `shipment-docs/pod/` quota — confirm available space.\n \n-### Payment recording broken in production (known, tracked: #9)\n+### Payment recording (RESOLVED 2026-05-15)\n \n-**Symptom:** Operator clicks \"Record Payment\" on an invoice → sees red toast: \"Payment recording is unavailable: the `invoice_payments` table has not been deployed yet. Apply migration 20260501000002.\"\n+> Historical entry preserved for audit trail. Originally tracked as #9 + the `invoice_payments` migration backlog.\n \n-**State as of PR #8 merge (2026-05-08):**\n-- The `invoice_payments` table does NOT exist in the deployed schema.\n-- The `record_invoice_payment` RPC does NOT exist in the deployed schema.\n-- Payments cannot be recorded. The error message is clear, not silent — `recordPayment()` throws on every call.\n-- `usePaymentsForInvoice()` returns `[]` silently (the UI shows \"no payments\" which is correct since none can exist).\n-- No `ALLOW_PAYMENT_FALLBACK` env var should be set in production. The gate code that read that variable was reverted; the var is now meaningless. If you find it set, remove it.\n+**State (current):** ✅ Live in production via the Path A baseline (#96) + #97 + #100.\n+- `public.invoice_payments` table exists with RLS policies\n+- `public.record_invoice_payment(...)` RPC exists, granted to `authenticated`\n+- Authorized roles: `SUPER_ADMIN, ADMIN, MANAGER, INVOICE, FINANCE_STAFF` (the `OPERATOR` typo bug discovered in the 2026-05-15 audit was fixed in #97)\n+- `function_search_path_mutable` advisor warning closed (#98)\n+- `EXECUTE` privilege correctly REVOKEd from `PUBLIC` and re-granted to `authenticated` only (#100)\n \n-**Resolution:** Issue **#9** — single small PR that adds:\n-1. `supabase/migrations/20260501000001_add_invoice_payments_table.sql` — table + indexes + RLS policies\n-2. `supabase/migrations/20260501000002_add_record_invoice_payment_rpc.sql` — RPC body with `SELECT ... FOR UPDATE` inside a transaction (`SECURITY DEFINER`)\n+**If a user reports \"payment recording fails\":**\n+1. Check `mcp__supabase__get_advisors` — should show ≤ 13 warnings\n+2. Check `has_function_privilege('authenticated', 'public.record_invoice_payment'::regprocedure, 'EXECUTE')` — should be `true`\n+3. Check the user's `profiles.role` — must be in `(SUPER_ADMIN, ADMIN, MANAGER, INVOICE, FINANCE_STAFF)`\n+4. Check Sentry for the actual error (DSN is wired and verified)\n \n-Both must land in one deploy. Once verified live for ≥ 7 days, a follow-up ≤50 LoC PR deletes the JS-layer fallback (which carries the documented two-step race) so the only remaining path is the atomic RPC.\n+### Sentry telemetry — wiring + prod env verified (issue #22 closed 2026-05-15)\n \n-**Priority:** P1 — feature is non-functional. Owner + ETA owed in #9 before merging PR #8 into main, or as the very next change after.\n-\n-**Operator workaround until #9 lands:** record payments via the Supabase SQL editor manually. No UI path exists.\n-\n-### Sentry telemetry — wiring landed, prod-env vars + alert rule still pending (tracked: #22)\n-\n-**State as of 2026-05-08 (PR #33 merged):**\n+**State (current, verified 2026-05-15):**\n - ✅ Sentry project exists: `tapan-cargo-az/javascript-nextjs` on `de.sentry.io`\n-- ✅ Code wiring complete — all four hooks active when DSN is set:\n+- ✅ Code wiring complete — all four hooks active:\n - `apps/dashboard/sentry.{client,server,edge}.config.ts` — runtime init with logs + release support\n - `apps/dashboard/instrumentation.ts` — exports `onRequestError = Sentry.captureRequestError` for App Router server-component coverage\n - `apps/dashboard/app/global-error.tsx` — captures React render-time errors\n - `apps/dashboard/next.config.mjs` — wrapped with `withSentryConfig` for source map uploads + ad-blocker tunnel via `/sentry-tunnel`\n-- ✅ Local dev DSN set in `apps/dashboard/.env.local`\n-- ❌ **Production env vars NOT YET set** — `SENTRY_DSN` and `NEXT_PUBLIC_SENTRY_DSN` need to be configured in Vercel (or wherever the dashboard deploys). Until then, prod captures remain silent.\n-- ❌ **Alert rule for `tags[kind]:payment_response_lost` NOT YET configured** — without it, lost-payment-confirmation events land in Sentry but nobody gets paged.\n+- ✅ Production DSN is set — Sentry receives events end-to-end (verified via `mcp__sentry__search_issues`, 9 unresolved issues from real production traffic in last 30d as of 2026-05-15)\n+- ⚠️ **Alert rule still pending** — events arrive in Sentry but no rule fires a notification when a new error appears. Tracked in **#94**.\n \n **To fully close #22 (manual UI steps):**\n ", "status": "modified"}], "message": "docs: production-readiness audit (2026-05-15) + fix stale runbook claims\n\nComprehensive CTO-mode audit run via four parallel exploration agents\n(security, code health, CI/CD + tests, ops + observability) followed by\ncross-validation against current production state.\n\n## What lands\n\n1. **docs/PRODUCTION-READINESS-REPORT-2026-05-15.md** — full audit report\n with TL;DR, validated findings by category, and a prioritized action\n plan (immediate → sprint 1 → sprint 2 → backlog).\n\n2. **docs/PRODUCTION-RUNBOOK.md updates** — three load-bearing claims\n were stale. Corrected:\n - Payment-recording feature: marked RESOLVED with verification steps\n for future incidents (was claiming `invoice_payments` table doesn't\n exist; it's been live since the Path A baseline #96 + #97 + #100)\n - Sentry section: marked DSN as verified set in production\n (was claiming \"NOT YET set\" — actually verified end-to-end via\n `mcp__sentry__search_issues` showing 9 unresolved real prod events)\n - Observability checklist: Sentry DSN line now [x] checked\n\n## Headline findings\n\n| Area | Critical | Sprint-worthy | Backlog |\n|---|---|---|---|\n| Security | 0 | 2 (PDF secret format, rate-limit docs) | several patterns to preserve |\n| Code health | 4 (`as unknown as` casts) | 2 (orphaned components, dup forms) | minor lint comments |\n| CI/CD + tests | 4 (auth/db/payment 0% coverage, no SCA) | 5 (E2E gaps in core flows) | misc |\n| Ops | 3 (no /api/health, no WhatsApp audit, no alert rules) | 4 (logging, cron docs, PITR, Upstash) | on-call, dashboards |\n| Docs | 1 (runbook drift — fixed here) | 0 | session-scratchpad cleanup |\n\n## Top 5 immediate moves (each ~1-3h)\n\n1. Update PRODUCTION-RUNBOOK.md (DONE in this PR)\n2. Add /api/health endpoint (~10 LOC)\n3. Add unit tests for payment.service.ts + record_invoice_payment RPC\n4. Fix the 5 production bugs Sentry surfaced (#93)\n5. Wire Sentry alert rules (#94)\n\n## Why this audit caught more than the day-of-incident fixes\n\nThe Path A reconciliation work was reactive — closing concrete bugs as\nthey surfaced. This audit was proactive — spawning fresh agents on a\nclean deck with no context of recent fights, then validating their\nclaims against live production state. The cross-validation step caught\nthe stale-runbook problem that would otherwise have misled the next\nincident responder.\n\nA tracking issue with all action items (each becomes its own future PR)\nis opened alongside this PR.\n\nCo-Authored-By: Claude Opus 4.7 ", "sha": "c9db88e2fa7107c09ff13bbca3a7e9e078bfab5d"}], "post_review_commits": ["ed18d12726288f51ec3aa924cc898cff63dc7421"], "pr_author": "cargotapan-collab", "pr_title": "docs: production-readiness audit (2026-05-15) + fix stale runbook claims", "repo_name": "cargotapan-collab/tac-express"}, "repo": "cargotapan-collab/tac-express", "snapshot": "snapshots/a4837f66e1743ac9f0902726484db022e82e3cfe56bc6cf858a349a74491fb43.pack", "split": "rl", "task_id": "5d25972a30e701c66b68c44d8fa8227b668768860bc1ec1ce3ab57b56a556a75"} {"base_sha": "869789b4edd7ff71ed717feb1dc1935aef36e5ad", "cohort": null, "context": {"canonical_pr_url": "https://github.com/pingdotgg/t3code/pull/1865", "id": "5da01372194c40cb51ea034cc7354e97d04c412145b9834d7d91c0555334b6f6", "preparation_mode": "source-only", "snapshot": {"base_ref": "869789b4edd7ff71ed717feb1dc1935aef36e5ad", "base_sha": "869789b4edd7ff71ed717feb1dc1935aef36e5ad", "body": "", "head_ref": "36b481ff7c78240c90bd6eaa740800ea8af894f5", "head_sha": "36b481ff7c78240c90bd6eaa740800ea8af894f5", "name": "t3code", "number": 1865, "owner": "pingdotgg", "pr_url": "https://github.com/pingdotgg/t3code/pull/1865", "title": ""}}, "head_sha": "36b481ff7c78240c90bd6eaa740800ea8af894f5", "metadata": {"group_id": "11ae9c9a3ac51975ad19284f742cf3e1ee88dee5a349e8fc4236d568cc214a29", "snapshot": {"base_sha": "869789b4edd7ff71ed717feb1dc1935aef36e5ad", "external_requirements": [], "head_sha": "36b481ff7c78240c90bd6eaa740800ea8af894f5", "objects": 856, "objects_sha256": "3d178e86a8937652ed0008433d35b0788c15efb4a90393548929ab2548e793c9", "patch_sha256": "19cbe15f4a0567d47fb4039ae1aeb5eacd56b28ee9b0c1a838ba09a724bec2cb"}}, "pr_number": 1865, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "style", "commit_sha": "68b734828070", "description": "The runtime mode trigger lacked the medium font weight needed to match the updated composer footer control styling.", "file_path": "apps/web/src/components/chat/ChatComposer.tsx"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "9f4dfbdc3b92", "description": "The composer independently derived a locked provider even when none was passed in, introducing an unrelated change to provider-selection behavior.", "file_path": "apps/web/src/components/chat/ChatComposer.tsx"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "91a2e92533b1", "description": "Settings panel test fixtures used session and pairing-link expiry dates close to the test date, making the tests time-dependent and prone to failure after those dates passed.", "file_path": "apps/web/src/components/settings/SettingsPanels.browser.tsx"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "91a2e92533b1", "description": "The settings panel test required the pairing-link button to say “Copy,” although the valid UI can instead say “Show link.”", "file_path": "apps/web/src/components/settings/SettingsPanels.browser.tsx"}], "commits_under_review": [{"author": "Julius Marminge", "date": "2026-04-09T23:41:13Z", "files": [{"additions": 8, "deletions": 2, "filename": "apps/web/src/components/chat/ChatComposer.tsx", "patch": "@@ -39,7 +39,7 @@ import {\n expandCollapsedComposerCursor,\n replaceTextRange,\n } from \"../../composer-logic\";\n-import { deriveComposerSendState, readFileAsDataUrl } from \"../ChatView.logic\";\n+import { deriveComposerSendState, readFileAsDataUrl, threadHasStarted } from \"../ChatView.logic\";\n import {\n type ComposerImageAttachment,\n type DraftId,\n@@ -542,12 +542,18 @@ export const ChatComposer = memo(\n const selectedProviderByThreadId = composerDraft.activeProvider ?? null;\n const threadProvider =\n activeThreadModelSelection?.provider ?? activeProjectDefaultModelSelection?.provider ?? null;\n+ const hasThreadStarted = threadHasStarted(activeThread);\n+ const sessionProvider = activeThread?.session?.provider ?? null;\n+ const computedLockedProvider: ProviderKind | null = hasThreadStarted\n+ ? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)\n+ : null;\n+ const effectiveLockedProvider = lockedProvider ?? computedLockedProvider;\n \n const unlockedSelectedProvider = resolveSelectableProvider(\n providerStatuses,\n selectedProviderByThreadId ?? threadProvider ?? \"codex\",\n );\n- const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider;\n+ const selectedProvider: ProviderKind = effectiveLockedProvider ?? unlockedSelectedProvider;\n \n const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({\n threadRef: composerDraftTarget,", "status": "modified"}], "message": "Address PR review feedback", "sha": "e9b7693f4561abc266a0e396d1cc21e239c4a9e0"}, {"author": "Julius Marminge", "date": "2026-04-09T23:41:14Z", "files": [{"additions": 10, "deletions": 6, "filename": "apps/web/src/components/chat/ChatComposer.tsx", "patch": "@@ -39,7 +39,11 @@ import {\n expandCollapsedComposerCursor,\n replaceTextRange,\n } from \"../../composer-logic\";\n-import { deriveComposerSendState, readFileAsDataUrl, threadHasStarted } from \"../ChatView.logic\";\n+import {\n+ deriveComposerSendState,\n+ deriveLockedProvider,\n+ readFileAsDataUrl,\n+} from \"../ChatView.logic\";\n import {\n type ComposerImageAttachment,\n type DraftId,\n@@ -542,11 +546,11 @@ export const ChatComposer = memo(\n const selectedProviderByThreadId = composerDraft.activeProvider ?? null;\n const threadProvider =\n activeThreadModelSelection?.provider ?? activeProjectDefaultModelSelection?.provider ?? null;\n- const hasThreadStarted = threadHasStarted(activeThread);\n- const sessionProvider = activeThread?.session?.provider ?? null;\n- const computedLockedProvider: ProviderKind | null = hasThreadStarted\n- ? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)\n- : null;\n+ const computedLockedProvider = deriveLockedProvider({\n+ thread: activeThread,\n+ selectedProvider: selectedProviderByThreadId,\n+ threadProvider,\n+ });\n const effectiveLockedProvider = lockedProvider ?? computedLockedProvider;\n \n const unlockedSelectedProvider = resolveSelectableProvider(", "status": "modified"}], "message": "Fix remaining composer review feedback", "sha": "7807f6e5e65dd6e46b55aa98d11c81a60e93f33e"}, {"author": "juliusmarminge", "date": "2026-04-09T23:41:14Z", "files": [{"additions": 1, "deletions": 0, "filename": "apps/web/index.html", "patch": "@@ -8,6 +8,7 @@\n \n \n \n+ \n \n \n \n