Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript
50.7 KB
Raw Blame
{
  "schema": "gstack-detector-corpus/v1",
  "case": "plan-ceo-section-loading",
  "detector": "test/helpers/ceo-stale-fill-decision.ts#hasApprovedStaleFillDecision || test/helpers/ceo-section-loading-fixture.ts#hasStaleFillRaceFinding",
  "series_identity": "c040a0214e4f3172",
  "source": {
    "run": "37179171083",
    "sha": "db91607a7fd9419592eb63e036149920304e32b5",
    "lane": "periodic",
    "artifact": "paid-slice-6-a1",
    "path": "shards/skill-e2e-plan-ceo-review-section-loading/_partial-e2e.json#/tests/0/output"
  },
  "census_outcome": "passed",
  "census_error": "",
  "expected": "pass",
  "justification": "Genuine pass: approved R1 ledger row with a stale-fill currentDecision, and the prose finding also matches; both witnesses agree.",
  "input": {
    "report": "# Plan: cache profile summaries in one process\n\n## Measured problem and accepted scope\nThe existing profile-summary service has one active process. A one-week trace\nshows repeated reads of about 900 hot keys: DB CPU is 70%, with read p95 120 ms.\nAdd a process-local LRU wrapper to the existing repository. Acceptance targets\nare at least 60% cache hits, DB CPU below 50%, and read p95 below 60 ms, with the\nexisting error-rate and correctness SLOs unchanged. This is an internal backend\nchange with no UI, API, schema, pricing, or developer onboarding change.\n\n## Existing contracts retained\n- All reads and writes use this repository in the same process; there are no\n  external DB writers. Multi-process operation remains unsupported and startup\n  rejects that configuration while caching is enabled.\n- These surrounding contracts are accepted fixture facts, supplied by the\n  existing repository, cache adapter and rollout controller. Preserve them;\n  review the new wrapper ordering below against them.\n- Authentication and authorization run before repository access. Keys encode\n  the authenticated tenant ID and validated profile ID without ambiguity.\n  Values are immutable profile-summary DTOs; secrets and cache keys are never\n  logged. Cached results cannot bypass authorization.\n- The existing LRU adapter supports 1000 entries, a 16 MiB byte cap, and a\n  30-second TTL. Recorded hot data fits those limits. repository.read returns\n  an immutable absent-result DTO for a missing record, never undefined. The\n  adapter recognizes that DTO in cache.set, stores an internal sentinel with a\n  10-second TTL, and cache.get decodes it back to the same absent-result DTO.\n  The internal sentinel cannot escape the adapter; undefined means a cache miss.\n- Cache operations are synchronous and atomic in the single JS event loop.\n  On any cache failure the existing adapter bypasses the cache until an empty\n  cache is reinitialized; repository errors keep the current typed API error\n  mapping. The existing per-key single-flight wrapper sits inside\n  repository.read, coalesces simultaneous store reads and releases on failure.\n  A committed repository.write retires that key's old read cohort before its\n  promise resolves. A later repository.read starts a fresh cohort; a rejected\n  write leaves the cohort unchanged. Already-started readers may finish with\n  their earlier snapshot. This admission rule does not inspect cache fills.\n- The repository uses an in-process transactional store, with no network\n  transport between this wrapper and the store. repository.write is atomic:\n  a resolved promise means committed, and every\n  rejected promise guarantees no commit; its transaction rolled back before\n  rejection. Existing contract tests exercise that guarantee.\n- Consistency is measured at the public wrapper boundary. A write completes\n  when writeProfile's promise fulfills after cache.delete, not when\n  repository.write commits or resolves. A read begins when readProfile is\n  invoked. Reads that overlap an unfinished writeProfile may return an earlier\n  snapshot, including reads begun after the store commit but before the wrapper\n  promise fulfills. Every read begun after that write completes must\n  observe the committed version. TTL expiry is not a substitute for this rule.\n\n## Proposed wrapper integration\nKeep the current read-through repository interface and shared adapters. These\nare the complete new read/write ordering rules; no additional version checks or\ncoordination between a cache fill and a write are proposed in the original draft. **Amended by CEO review decision R1 (D1 → A):** the wrapper MUST NOT install a cache fill from a read that began before a write to the same key committed and whose writeProfile has since run (or is running). Required guarantee: at fill time the wrapper synchronously checks a per-key write generation (or equivalent) recorded while the miss is in flight; if any write to that key committed since the miss began, the fill is skipped, the value is still returned to the caller, and the skipped fill is counted. Coordination state is bounded by in-flight misses and removed when the last in-flight miss for the key settles. Exact data structures and function bodies are left to engineering planning. The original draft below is retained as the baseline being amended:\n\n```javascript\nasync function readProfile(key) {\n  const cached = cache.get(key);\n  if (cached !== undefined) return cached;\n  const value = await repository.read(key);\n  cache.set(key, value);\n  return value;\n}\n\nasync function writeProfile(key, update) {\n  const saved = await repository.write(key, update);\n  cache.delete(key);\n  return saved;\n}\n```\n\n## Verification and rollout\nExisting repository contract tests cover tenant isolation, key validation,\nabsence, DB failures, authorization, and startup rejection of multi-process\noperation while caching is enabled. New wrapper tests cover hit/miss,\neviction and byte limits, TTL, adapter-failure fallback, successful-write\ninvalidation, failed-write preservation, and concurrent-miss coalescing.\n**Added by R1 (D1 → A), deterministic scenarios on the existing contract test\nharness with pause/release points:** (S1) read misses and pauses inside\nrepository.read; write commits and writeProfile fulfills; read resumes with the\nearlier snapshot: assert no fill installed, a fresh read observes the committed\nversion, suppressed-fill count +1. (S2) same but the read resumes BEFORE the write\ncommits and fills: assert writeProfile's cache.delete removes it and the next read\nobserves the committed version. (S3) missing record: read obtains the absent DTO,\ncreate commits and completes, read resumes: assert no absent sentinel installed\nand the next read observes the created record. (S4) overlapping writes W1, W2 with\na read in flight: assert the next read after both complete observes W2's version.\n(S5) rejected read leaves cache untouched; rejected write leaves cache and\ngeneration unchanged. (S6) controller instance swap during an in-flight miss:\nold read cannot fill the new instance (existing contract) and the new instance\nserves the committed version. The suppressed-fill branch is recorded through the\nexisting telemetry on the current dashboard with no key labels; no new alert or\nmetric project.\nThe rollout uses the existing runtime feature flag: enable for 10% of keys,\nthen 50%, then all keys after one healthy hour at each stage. Monitor hit/miss,\neviction, cache bytes, fallback errors, DB CPU, and read p95 without raw IDs.\nThe existing controller uses one shared key-selection predicate for reads and\nwrites. On any enable, disable or percentage change, it stops admitting work,\nawaits every admitted old-instance write, then publishes a new wrapper/cache\ninstance with a fresh single-flight cohort before admitting new work. Old reads\nretain their old instance and cannot fill the new one. Disabled instances\nbypass the cache on both paths. Tests cover the old-writer/new-reader ordering,\nall those transitions and predicate parity. This lifecycle isolation does not coordinate\nan ordinary DB write with a cache fill in the same active instance.\nExisting dashboards and runbooks cover these metrics. Before each stage, verify\nthat alerts page the service owner on any correctness/error-SLO breach, read\np95 above 120 ms for five minutes, or cache bypass persisting for one minute.\nHit rate is hits / (hits + misses) among requests admitted to the cache path;\nflag-excluded or adapter-bypassed requests are tracked separately, not as misses.\nDB CPU and read p95 are service-wide metrics, including bypassed requests.\nAt the 10% and 50% stages, a healthy hour requires at least 60% admitted-request\nhits, unchanged correctness/error SLOs, no alerts, and aggregate DB CPU/read p95\nno worse than their 70%/120 ms pre-rollout baselines. At 100%, the original\nabsolute acceptance targets (DB CPU below 50%, read p95 below 60 ms, hits at\nleast 60%) must all hold with unchanged correctness/error SLOs and no alerts.\nAny breach disables the flag immediately; the runbook records the incident,\nrollback and criteria for resuming. These are existing\nrollout-controller and telemetry contracts, not proposed wrapper additions.\nCold starts remain within the existing DB capacity. The service owner monitors\nthe rollout and records the results against the acceptance targets.\n\n## Out of scope\nDistributed caching, cross-process coherence, prewarming, changing consistency\nsemantics, or adding new product surfaces. The repository interface preserves a\nfuture replacement path without introducing a general cache framework now.\n\n## Author's review and acceptance requirements\nThis is a full CEO scope and feasibility review. The author has approved the\nretained contracts, limits, rollout and acceptance targets above. Evaluate the\nproposed wrapper against them; the wrapper itself remains unapproved. An actual\ncontradiction or missing proof must be reported and resolved, not assumed away.\nFor a demonstrated gap, amend the plan with the required guarantee, a feasible\nremedy, its tradeoffs and deterministic regression scenarios. Those repairs\nand their required verification are within the requested scope. The exact data\nstructures, full function bodies and executable test code belong to subsequent\nengineering planning; do not select or implement them during this review when\nthe required behavior and feasibility can already be established.\n\nUse the existing deterministic repository-contract test harness. Required wrapper\nacceptance includes both completion orders of overlapping reads and writes,\nmissing-record creation, rejected reads/writes, overlapping writes, and isolation\nacross controller instance changes. Use existing telemetry to record any added\nbranch on the current dashboard with no key labels; no new alert threshold or metric\nproject is requested. These are future acceptance requirements, not tests already\nimplemented or passing. Preserve all 11 review outcomes, required registries,\ndiagrams, tasks, completion summary and the full GSTACK REVIEW REPORT.\n\n---\n\n# CEO REVIEW (plan-ceo-review, HOLD SCOPE) — 2026-10-04\n\n## Step 0: setup, ledger and scope challenge\n\n**Review depth:** implementation-ready at the wrapper codepath level (readProfile /\nwriteProfile, adapter, controller). Per the author's acceptance requirements, exact\ndata structures, full function bodies and executable test code are reserved for\nengineering planning; this review names required guarantees, codepaths, rescue\nbehavior and regression scenarios only.\n**Storage policy:** working plan = this file (requested output). Appends for new\nreview content, scoped Edits for plan amendments. gstack state/log/telemetry\nwrites are out of this run's scope (hermetic fixture); such fields are shown\n**not persisted**. System audit, environment setup and telemetry skipped per run\ninstructions. Outside review: `codex_reviews: disabled` in\n`.gstack-section-state-b2PTft/config.yaml`.\n**Stated limits recorded:** LRU 1000 entries; 16 MiB byte cap; 30 s value TTL;\n10 s absent-sentinel TTL; targets hits >= 60% (admitted requests), DB CPU < 50%,\nread p95 < 60 ms at 100%; stage baselines 70% CPU / 120 ms p95; alerts: p95 > 120 ms\nfor 5 min, bypass persisting 1 min, any correctness/error-SLO breach; one healthy\nhour per stage at 10% / 50% / 100%. Deliverables counted against scope: 1 wrapper\nmodule (new), 1 wrapper test file (new), controller wiring reuse (unchanged).\nEstimated changed files: 2-3 (estimate).\n\n### Decision ledger (continued through all sections)\n\n| ID and owner | Contract and evidence | Current | Proposed | Status | Exact approval and scope |\n|---|---|---|---|---|---|\n| R1 — Section 1 (Architecture), carried to Section 4 | PLAN.md \"Existing contracts retained\": every read begun after writeProfile fulfills must observe the committed version; TTL is not a substitute. PLAN.md \"Proposed wrapper integration\": `cache.set(key, value)` after `await repository.read` with no fill/write coordination; fixture fact \"already-started readers may finish with their earlier snapshot\" and \"this admission rule does not inspect cache fills\". | Wrapper as proposed: unconditional fill after read resolves. | A: suppress fills that overlap a committed write; B: install then delete; C: keep as proposed (rejected: weakens retained contract). | approved | D1 auto-decided → A under the run's author policy (\"authorize complete remedies and required verification that restore its retained contracts ... use the recommended option\"). Scope: wrapper fill-time guard with bounded in-flight state, suppressed-fill count on existing dashboard (no key labels), scenarios S1–S6 on the existing harness. Not approved: adapter/repository/controller changes, new metrics projects, data-structure or test-code selection. |\n\n### 0A. Premise Challenge\nReal problem: ~900 hot profile-summary keys are re-read so often that one DB\ncarries 70% CPU and 120 ms read p95. Target outcome: >= 60% of admitted reads served\nfrom process memory, DB CPU < 50%, read p95 < 60 ms, SLOs unchanged. Do-nothing\ncost: DB stays near saturation; any traffic growth pushes p95 and error rate up.\nThe plan attacks the pain directly (fewer repeated store reads), not a proxy.\nPremise holds under HOLD SCOPE; one consistency contract (R1) is at risk and is\nreviewed, not assumed away.\n\n### 0B. Existing Code Leverage\n| Sub-problem | Reused existing code | Note |\n|---|---|---|\n| Bounded in-memory storage, TTL, absent sentinel, failure bypass | existing LRU cache adapter | fixture fact; no rebuild |\n| Coalescing concurrent misses | per-key single-flight inside repository.read | fixture fact; does not inspect fills |\n| Atomic commit / rollback | repository.write on in-process transactional store | fixture fact |\n| Staged rollout, instance isolation, metrics | existing rollout controller + telemetry + dashboards | fixture fact |\n| New: read-through ordering + write invalidation | new wrapper (readProfile/writeProfile) | the only new code |\nNo rebuild is proposed; refactoring the existing path is not needed.\n\n### 0C. Dream State Mapping\n```\n  CURRENT STATE                      THIS PLAN                         12-MONTH IDEAL\n  single process, every read   --->  process-local LRU in front  --->  same single-process service,\n  hits the store; DB CPU 70%,        of repository; >=60% hits,        read-through boundary stable\n  read p95 120 ms                    DB CPU <50%, p95 <60 ms,          enough that a later replacement\n                                     consistency contract intact       (if ever needed) is a swap\n                                                                       behind the same interface\n```\nThe plan moves toward the ideal without adding a cache framework. Distributed\ncaching stays out of scope by author decision.\n\n### 0D. Alternatives\nNo approach choice was required at Step 0: the requested approach (local LRU\nwrapper over the existing repository) is retained. 0D is used later for R1.\n\n### 0E. Mode Selection\nExplicit user choice: HOLD SCOPE (\"Hold the current scope (HOLD SCOPE mode)\").\nSteps 2-3 skipped. Mode handoff: `Mode: HOLD SCOPE; approved decisions: none.`\nApplication: preserve scope, maximum rigor on failures, edge cases, error paths,\ntests and observability; repairs needed to meet retained invariants are in scope.\nProvenance: explicit user instruction; no question asked, no question log.\nNo new approach decision was needed.\n\n### 0G. HOLD SCOPE checks\n1. Complexity: 2-3 changed files, 1 new module, 0 new services. Below the\n   8-file / 2-service threshold. No fewer-moving-parts alternative exists; the\n   wrapper is the minimum.\n2. Minimum change for the goal: the two wrapper functions plus tests. Nothing in\n   the accepted scope is deferrable without blocking acceptance (the contract\n   tests, rollout stages and alerts are launch scope under Prime Directive 5).\n3. Invariants and acceptance criteria kept as stated; any repair required to meet\n   them (R1) is in scope.\nDeferral menu: no item proposed for deferral; nothing to ask.\n\n### 0I. Temporal Interrogation\n```\n  HOUR 1 (foundations):    implementer needs the retained contracts verbatim (absent DTO,\n                           sentinel TTL, single-flight cohort rule, write-completion boundary).\n  HOUR 2-3 (core logic):   ambiguity: what happens to a fill from a read that began before a\n                           write committed and resolves after writeProfile fulfilled (R1).\n  HOUR 4-5 (integration):  surprise: controller instance swaps isolate old readers, but do\n                           NOT coordinate a fill and a write inside one active instance.\n  HOUR 6+ (polish/tests):  wish they had planned pause/release harness hooks for both\n                           completion orders of overlapping reads and writes, and for\n                           missing-record creation under the absent sentinel.\n```\nEffort: human ~2-3 days / CC+gstack ~1-2 h for wrapper + tests (tests ~50x ratio).\nFeasibility blockers: R1 (resolved below before the sections proceed). Pending\nchoices: none other than R1.\n\n## Review Sections\n\n**Current scope (published before Section 1):** Mode HOLD SCOPE (explicit user\ninstruction). Governing rows: R1 unresolved (pending below). Accepted work: the\nplan as written above. Deferred: none. Rejected: none. Pending: R1.\n\n### Section 1: Architecture Review\nDependency graph (new component marked *):\n```\n  caller --> rollout controller (predicate, instance swap)\n                 |\n                 v\n         *wrapper {readProfile, writeProfile}\n             |              |\n             v              v\n      LRU cache adapter   repository.read / repository.write\n      (1000 / 16 MiB /      |  (single-flight cohort inside read)\n       30 s, sentinel 10 s) v\n                       in-process transactional store\n```\nData flow, readProfile:\n```\n  happy : get(key) hit -> return DTO            | miss -> await read -> set -> return DTO\n  nil   : record missing -> read returns absent DTO -> set stores sentinel (10 s) -> get decodes to absent DTO\n  empty : key validation runs before repository access (fixture); empty/invalid key never reaches wrapper\n  error : read rejects -> no set, cache untouched -> typed API error (existing mapping)\n          adapter failure -> adapter bypasses cache until reinit -> read goes to store\n```\nData flow, writeProfile:\n```\n  happy : await write (commit) -> delete(key) -> fulfill   (write \"completes\" at fulfill)\n  error : write rejects (rolled back) -> no delete -> reject with typed error; cache preserved (correct)\n  adapter failure on delete -> adapter bypass (fixture); write already committed; wrapper fulfills\n```\nCoupling: wrapper depends on adapter + repository only; controller owns lifecycle.\nJustified; no new cross-module coupling. Scaling: 10x load keeps the hot set at\n~900 keys < 1000 entries; 100x load with the same key set is served from memory;\na key set beyond 1000 entries thrashes the LRU and the hit target fails loudly on\nthe dashboard (no silent failure). SPOF: unchanged (single process, single DB).\nSecurity: no new endpoint or mutation surface; auth precedes repository access\n(fixture). Rollback: flag disable -> controller publishes a disabled instance\n(bypass both paths); seconds.\n\n**Production failure scenario (CRITICAL GAP, row R1):** a read misses, awaits\nrepository.read and obtains snapshot v0; a write commits v1, cache.delete runs\n(no entry yet), writeProfile fulfills; the read then resolves with v0 and\n`cache.set(key, v0)` installs a stale entry. A read begun after the write\ncompleted hits v0 for up to 30 s (or 10 s for an absent sentinel after a create).\nThis violates the retained contract \"every read begun after that write completes\nmust observe the committed version\". Evidence: the plan states no fill/write\ncoordination; the fixture cohort rule explicitly lets already-started readers\nfinish with their earlier snapshot and does not inspect fills; controller\nisolation only applies across instance swaps. This is a contract-level\ncontradiction, not an unavailable-implementation guess.\n\nOther outcome: **OK** on boundaries, coupling, scaling, SPOF, security, rollback.\n**Decision gate:** Resolve path 1 (new choice). 0D plan-decision route, row R1.\n\n## currentDecision (R1)\nCommitment comparison:\n```text\nCommitment                                   | Source/approval or pending        | Current (plan as written)        | A                                        | B                                              | C\nReads after a completed write see committed  | PLAN.md retained contracts (fixed) | violated by stale fill (gap)     | met: fill suppressed when a write to key | met: fill suppressed by re-deleting key after | not met: contract would be weakened\nversion                                      |                                    |                                  | committed during the in-flight miss      | every fill whose read overlapped a write      | (not authorizable in this review)\nWrapper ordering rules                       | pending (R1)                       | get -> await read -> set         | add synchronous per-key write-generation | add per-key \"write-seen\" flag consulted after | unchanged\n                                             |                                    |                                  | check at fill time (in wrapper instance) | set to delete; still momentarily installs     |\nMemory for coordination state                | pending (R1)                       | none                             | bounded by in-flight misses (entries     | bounded by in-flight misses                  | none\n                                             |                                    |                                  | removed when last miss settles)          |                                               |\nAdapter / repository / controller contracts  | fixture facts (fixed)              | unchanged                        | unchanged                                | unchanged                                     | unchanged\nRegression scenarios (both completion orders,| author acceptance reqs (fixed)     | listed as required, not yet      | deterministic pause/release scenarios    | same scenarios                                | same scenarios, but one must be\nmissing-record create, rejected ops,         |                                    | specified against R1             | specified below; fill-suppressed branch  |                                               | changed to expect stale data\noverlapping writes, instance isolation)      |                                    |                                  | asserted                                 |                                               | (forbidden)\nTelemetry for added branch                   | author acceptance reqs (fixed)     | n/a                              | count suppressed fills on existing       | same                                          | n/a\n                                             |                                    |                                  | dashboard, no key labels                 |                                               |\nChanged files                                | estimate                           | 2-3                              | 2-3 (same files)                         | 2-3 (same files)                              | 2-3\n```\n\nQuestion: D1 — R1: How should the wrapper stop a stale cache fill from a read that began before a write committed?\nProject/branch/task: main branch, PLAN.md \"cache profile summaries in one process\", CEO review in HOLD SCOPE.\nELI10: A reader asks the database for a profile, and while it waits, a writer saves a newer profile and clears the cache. The reader's old answer then arrives and gets stored in the cache, so everyone after sees the old profile for up to 30 seconds. The plan promises that never happens, so the wrapper needs a rule that refuses to store an answer that is older than a write that already finished.\nStakes if we pick wrong: users read a profile they just updated and see the previous version; the correctness SLO breaks; the rollout trips its alert and rolls back.\nRecommendation: A because a synchronous fill-time check against a per-key write generation is the smallest explicit mechanism that satisfies the contract in a single event loop, with bounded state and one testable branch (explicit over clever).\nCompleteness: A=10/10, B=7/10, C=3/10\nPros / cons:\nA) Suppress fills that overlap a committed write (recommended)\n  ✅ Meets the retained contract in both completion orders without touching the adapter, repository or controller.\n  ✅ Adds one synchronous branch with bounded state; the suppressed-fill count is observable on the existing dashboard.\n  ❌ A hot key under constant writes may rarely fill, so its reads keep going to the store (visible as lower hit rate, not as incorrectness).\nB) Install the fill, then delete it when a write overlapped\n  ✅ Also keeps the adapter and repository unchanged and reuses cache.delete.\n  ✅ Simple to reason about: every overlapped fill is removed before the reader returns.\n  ❌ The stale entry exists for a moment between set and delete; a concurrent synchronous get in that window is impossible, but the design relies on strict ordering inside one function and is harder to prove and test than never installing.\nC) Keep the wrapper as proposed and accept TTL-bounded staleness\n  ✅ Zero implementation work beyond the plan as written (effort S, no new state).\n  ✅ Simplest code path.\n  ❌ Contradicts the retained consistency contract and the \"TTL is not a substitute\" clause; not authorizable by this review.\nNet: A pays a tiny amount of bounded in-process state to make the contract hold by construction; B pays the same but with a weaker proof; C is not an option under the retained requirements.\n\nHeader: R1 stale cache fill\nA) Suppress fills that overlap a committed write (recommended)\nEffort S, risk low. Reuse: existing adapter, repository and controller unchanged; one new synchronous check in the wrapper instance keyed by the same cache key, tracking a per-key write generation (or equivalent) only while a miss is in flight, removed when the last in-flight miss for that key settles. Verification coverage: both completion orders of overlapping read/write, missing-record creation under the absent sentinel, overlapping writes, rejected reads/writes, instance isolation, suppressed-fill branch asserted and counted. ✅ Meets the retained contract in both completion orders without touching the adapter, repository or controller. ✅ Adds one synchronous branch with bounded state; the suppressed-fill count is observable on the existing dashboard. ❌ A hot key under constant writes may rarely fill, so its reads keep going to the store (visible as lower hit rate, not as incorrectness).\nB) Install the fill, then delete it when a write overlapped\nEffort S, risk medium. Reuse: adapter, repository and controller unchanged; wrapper installs the value, then calls cache.delete when a per-key write flag was raised during the miss. Verification coverage: same scenarios as A plus an ordering assertion that no get can observe the entry between set and delete. ✅ Also keeps the adapter and repository unchanged and reuses cache.delete. ✅ Simple to reason about: every overlapped fill is removed before the reader returns. ❌ The stale entry exists for a moment between set and delete; a concurrent synchronous get in that window is impossible, but the design relies on strict ordering inside one function and is harder to prove and test than never installing.\nC) Keep the wrapper as proposed and accept TTL-bounded staleness\nEffort S, risk high; zero implementation work. Reuse: everything as written. Verification coverage: would require changing a required scenario to expect stale data, which the retained contract forbids. ✅ Zero implementation work beyond the plan as written (effort S, no new state). ✅ Simplest code path. ❌ Contradicts the retained consistency contract and the \"TTL is not a substitute\" clause; not authorizable by this review.\n\n**D1 answer record (R1):** Auto-decided D1 → A (authority: this run's author policy\nauthorizes the recommended complete remedy restoring retained contracts; no human\npresent). Applied: \"Proposed wrapper integration\" amended with the required\nguarantee; \"Verification and rollout\" amended with scenarios S1–S6 and the\nsuppressed-fill telemetry branch; ledger row R1 → approved. Residual risk: a key\nunder constant writes may rarely fill (visible as lower hit rate, not stale data).\n\n### Section 2: Error & Rescue Map\n```\n  METHOD/CODEPATH            | WHAT CAN GO WRONG                          | EXCEPTION CLASS\n  ---------------------------|--------------------------------------------|---------------------------\n  readProfile#cache.get      | adapter failure                            | adapter internal (bypass)\n  readProfile#repository.read| store read fails / rejects                 | existing typed repository error\n                             | record missing                             | none (absent DTO, not an error)\n                             | stale snapshot resolves after completed    | none (logic gap) -> R1 guard\n                             | write                                      |\n  readProfile#cache.set      | adapter failure / byte cap exceeded        | adapter internal (bypass / evict)\n  writeProfile#repository.write | write rejects (rolled back)             | existing typed repository error\n  writeProfile#cache.delete  | adapter failure after commit               | adapter internal (bypass)\n  controller swap            | in-flight old reads during swap            | none (isolation contract)\n  ---------------------------|--------------------------------------------|---------------------------\n\n  EXCEPTION / CONDITION         | RESCUED?        | RESCUE ACTION                         | USER SEES\n  ------------------------------|-----------------|---------------------------------------|------------------\n  adapter failure (any op)      | Y (adapter)     | bypass cache until empty reinit;      | normal result, slower;\n                                |                 | bypass alert at 1 min                 | owner paged\n  typed repository read error   | Y (existing map)| re-raise via existing API mapping;    | existing API error\n                                |                 | no fill                               |\n  typed repository write error  | Y (existing map)| re-raise; cache untouched (no commit) | existing API error\n  absent record                 | n/a             | absent DTO; sentinel 10 s             | not-found result\n  stale fill after write (R1)   | Y after R1      | skip fill, return value, count branch | committed version\n```\nNo catch-alls proposed; the wrapper adds no new exception classes. **Outcome:**\n1 GAP (R1) mapped and resolved by D1 → A; otherwise OK. Decision gate: path 2\n(R1 exact answer cited); no new choice.\n\n### Section 3: Security & Threat Model\n| Threat | Likelihood | Impact | Mitigated |\n|---|---|---|---|\n| Cross-tenant cache read via key collision | Low | High | Yes: keys encode authenticated tenant + validated profile ID unambiguously (fixture); authz precedes repository access |\n| Cached result bypassing authorization | Low | High | Yes: fixture contract; cache sits below the authz boundary |\n| Key or secret leakage in logs/metrics | Low | Med | Yes: no raw IDs in metrics; the R1 suppressed-fill counter must carry no key labels (author requirement) |\n| Memory exhaustion via unbounded coordination state | Low | Med | Yes by R1 scope: state bounded by in-flight misses |\n| Cache poisoning via mutable DTO | Low | High | Yes: values are immutable DTOs (fixture) |\nNo new endpoint, input, dependency or background job. **Outcome:** No issues\nfound (0 High-severity open). Decision gate: no choice needed.\n\n### Section 4: Data Flow & Interaction Edge Cases\nData flow with shadow paths:\n```\n  INPUT key -> VALIDATION (upstream authz/key validation) -> TRANSFORM (get / read) -> PERSIST (set / delete) -> OUTPUT DTO\n    nil/empty key ........ rejected upstream before wrapper (fixture)            tested: existing contract tests\n    invalid DTO .......... impossible; immutable DTO from repository              n/a\n    exception/timeout .... read rejects -> no set -> typed error                  tested: rejected reads (S5)\n    conflict/dup ......... overlapping writes -> last committed wins (S4)         tested: S4\n    stale/partial ........ stale snapshot fill -> R1 guard skips fill (S1)        tested: S1-S3\n```\nAsync ordering, boundary = \"read begun after writeProfile fulfills observes the\ncommitted version\":\n```\n  t | readProfile R (miss)              | writeProfile W                   | cache[key]      | gen[key]\n  --|-----------------------------------|----------------------------------|-----------------|---------\n  1 | get -> miss; record gen=g0; await |                                  | empty           | g0\n  2 |   (paused in repository.read, v0) | await write -> commit v1         | empty           | g0\n  3 |                                   | gen++ ; delete(key); fulfill     | empty           | g1\n  4 | read resolves v0; gen g1 != g0    |                                  | empty (skipped) | g1\n  5 | return v0 to R's caller (allowed: R began before W completed)        |                 |\n  6 | fresh read R2: miss -> read v1 -> gen unchanged -> set v1           | v1              | g1\n```\nOrder 2 (read resolves before commit): t2 read resolves v0, gen==g0, set v0;\nt3 W commits, gen++, delete(key) removes v0; R2 reads v1. Both orders satisfy the\nboundary with the R1 guard; without it, order 1 leaves v0 cached (violation).\nThe excluded schedule \"get observes an entry between set and delete\" is prevented\nby synchronous atomic cache ops in one event loop (fixture). Regression proof:\nS1 (order 1), S2 (order 2), S3 (absent sentinel), S4 (overlapping writes), S6\n(instance swap), with controlled pause/release points on the existing harness.\nInteraction edge cases: no user-visible interaction changes (backend only).\n**Outcome:** 5 edge cases mapped, 0 unhandled after R1. Decision gate: path 2\n(cites R1).\n\n### Section 5: Code Quality Review\nTwo small functions fit the existing read-through repository pattern. No\nduplicated behavior: invalidation and fill live only in the wrapper. Naming\n(readProfile/writeProfile) describes outcome. Error handling delegates to\nexisting typed mapping and adapter bypass (Section 2). The R1 guard adds one\nbranch; readProfile stays well under 5 branches. Not over-engineered: no\nframework, no version column, no adapter change. Under-engineering risk was the\nunconditional fill (R1, resolved). Require an ASCII comment above the wrapper\ndescribing the fill/write ordering (engineering preference: ASCII comments for\ncomplex state). **Outcome:** 1 issue (R1, resolved); comment requirement is a\ntask (T2). Decision gate: no new choice.\n\n### Section 6: Test Review\n```\n  NEW THING                        | TEST TYPE   | HAPPY                      | FAILURE                        | EDGE\n  ---------------------------------|-------------|----------------------------|--------------------------------|-----------------------------\n  readProfile hit/miss             | unit        | hit returns cached DTO     | read rejects -> typed error    | absent DTO -> sentinel decode\n  readProfile fill guard (R1)      | unit/harness| S2 fill then delete        | S1 stale fill suppressed       | S3 absent sentinel suppressed\n  writeProfile invalidation        | unit        | commit -> delete -> fulfil | rejected write preserves cache | S4 overlapping writes\n  adapter failure fallback         | unit        | bypass, results correct    | bypass persists -> alert       | failure on delete after commit\n  eviction / byte cap / TTL        | unit        | LRU evicts oldest          | over-cap value not stored      | 1000th vs 1001st entry\n  controller swap isolation        | integration | new instance fresh cohort  | old reader cannot fill new     | S6 swap mid-miss\n  suppressed-fill telemetry        | unit        | counter +1 on S1           | no key labels asserted         | zero when no overlap\n```\nAssertion check: every row maps to a retained contract or to R1's approved scope;\nS1–S6 are the exact scenarios the author required (both orders, missing-record\ncreation, rejected ops, overlapping writes, instance isolation). Existing contract\ntests cover tenant isolation, key validation, absence, DB failures, authz,\nmulti-process rejection. 2am test: S1. Hostile QA: S4 plus swap mid-miss (S6).\nChaos: adapter failure injected mid-fill while a write commits (bypass must win).\nPyramid: mostly unit, few integration, no E2E (correct for backend). Flakiness:\nTTL tests must use the harness's controlled clock, not wall time. Load: existing\nrollout stages serve as the load test; no separate load test requested.\n**Outcome:** diagram produced, 0 gaps after R1 (TTL-clock note is a task, T3).\nDecision gate: path 2 (R1) and settled proof reuse; no new choice.\n\n### Section 7: Performance Review\nN+1: none (point reads). Memory: <= 1000 entries / 16 MiB adapter cap plus R1\nstate bounded by in-flight misses (hundreds of entries at most). Indexes: no new\nqueries. Caching: this is the caching. Jobs: none. Slow paths: cold miss = store\nread (today's p95 120 ms); hit = sub-millisecond; suppressed fill = store read on\nthe next read of that key. Floor: 900 hot keys / 30 s TTL >= 30 store reads/s\nplus suppressed fills on write-hot keys; within existing DB capacity (fixture:\ncold starts remain within capacity). Connection pools: unchanged. **Outcome:** No\nissues found; residual note: write-hot keys lower the hit rate, surfaced on the\ndashboard. Decision gate: no choice.\n\n### Section 8: Observability & Debuggability Review\nMetrics (existing telemetry): hit, miss, eviction, cache bytes, fallback/bypass\nerrors, DB CPU, read p95, plus the R1 suppressed-fill count on the current\ndashboard with no key labels (author requirement; not a new metric project).\nLogging: adapter failure already logs without keys/secrets; the wrapper adds no\nkey logging. Alerts: existing (SLO breach, p95 > 120 ms for 5 min, bypass > 1 min);\nno new threshold requested. Debuggability: a stale-read report three weeks later is\nreconstructable from suppressed-fill and bypass counters plus the flag stage\ntimeline. Runbook: existing; it must name \"suppressed fills climbing\" as expected\non write-hot keys, not an incident (task T4, documentation only). **Outcome:** 1\ngap (runbook note), resolved as a documentation task within existing runbook\nscope. Decision gate: no choice (no new observability project).\n\n### Section 9: Deployment & Rollout Review\nNo migration. Feature flag: existing runtime flag, 10% -> 50% -> 100% with one\nhealthy hour each and defined criteria (plan). Rollout order: deploy wrapper\ndisabled, then raise percentage. Rollback: disable flag -> controller stops\nadmitting, drains old writes, publishes disabled instance; seconds; runbook\nrecords incident. Deploy-time risk window: one process, so no mixed versions; the\ncontroller swap contract covers in-flight work. Environment parity: stage runs\nunder the same harness; first 5 minutes watch bypass and hit rate; first hour\nwatch the healthy-hour criteria. Smoke: hit/miss counters moving, zero bypass.\n**Outcome:** 0 risks flagged beyond the plan's existing controls. Decision gate:\nno choice.\n\n### Section 10: Long-Term Trajectory Review\nDebt: small (one guard with bounded state, one ASCII comment, runbook note).\nPath dependency: none; the repository interface preserves a replacement path.\nKnowledge: the ordering diagram in Section 4 belongs in the wrapper comment (T2).\nReversibility: 5/5 (flag off or delete two functions). Ecosystem fit: uses the\nexisting adapter and harness. 1-year question: obvious, provided the comment\nexplains why fills are suppressed. **Outcome:** reversibility 5/5, debt items 2\n(comment, runbook note). Decision gate: no choice.\n\n### Section 11: Design & UX Review\n`SKIPPED (no UI scope)` — internal backend change, no UI, API or user-visible state.\n\n## Closing sequence\n\n### Outside Voice\n`codex_reviews: disabled` (`.gstack-section-state-b2PTft/config.yaml`). Codex\nreview skipped (codex_reviews disabled). Re-enable: `gstack-config set\ncodex_reviews enabled`. No prompt, outside process or native fallback. Disabled\ncoverage record (`gstack-review-log` codex-plan-review, status skipped,\noutside_status disabled): **not persisted** (state writes out of this run's scope).\n\n### Resolve remaining TODO choices\nNone remain. HOLD SCOPE: no evidenced gap is deferred; every finding is in\naccepted scope (R1) or a same-branch task.\n\n### Approval readiness\nChecked rows: R1 — approved via D1 auto-decision (authority: run author policy;\nrecommended option A). Plan applies only that scope (wrapper guard, bounded state,\nS1–S6, suppressed-fill count on the existing dashboard). No declined, deferred or\nunanswered changes in accepted work. Option C declined and kept out.\n`Approval readiness: PASS` (R1 → D1/A).\n\n## Required Outputs\n\n### Review facts\nMode HOLD SCOPE; 1 critical gap found (R1) and resolved; 0 unresolved choices;\n0 critical gaps open; scope proposals 0 / accepted 0 / deferred 0; outside\ncoverage: codex disabled, no completed external review. Status: `clean`.\n\n### NOT in scope\nDeferred: none. Rejected: D1 option C \"keep the wrapper as proposed and accept\nTTL-bounded staleness\" — contradicts the retained consistency contract. Author's\nout-of-scope list retained: distributed caching, cross-process coherence,\nprewarming, consistency-semantics changes, new product surfaces.\n\n### What already exists\nSee 0B: LRU adapter (limits, TTL, sentinel, bypass), single-flight cohort in\nrepository.read, atomic repository.write, rollout controller with instance\nisolation, telemetry/dashboards/runbooks, contract test harness. All reused.\n\n### Dream state delta\nSee 0C. After this plan the service meets its DB CPU / p95 targets with the\nconsistency contract intact and a stable read-through boundary; the 12-month\nideal needs no further caching work unless the key set outgrows 1000 entries.\n\n### Error & Rescue Registry\nSee Section 2 tables (7 codepath rows, 1 GAP → resolved by R1; 0 CRITICAL GAPS).\n\n### Failure Modes Registry\n```\n  CODEPATH                    | FAILURE MODE                 | RESCUED?     | TEST?      | USER SEES?          | LOGGED?\n  ----------------------------|------------------------------|--------------|------------|---------------------|---------------------\n  readProfile#cache.get/set   | adapter failure              | Y (bypass)   | Y          | slower, correct     | Y (no keys)\n  readProfile#repository.read | store error                  | Y (typed)    | Y          | existing API error  | Y (existing)\n  readProfile#repository.read | record missing               | n/a          | Y          | not-found result    | n/a\n  readProfile fill            | stale snapshot after write   | Y (R1 guard) | Y (S1,S3)  | committed version   | Y (suppressed count)\n  writeProfile#repository.write| write rejected              | Y (typed)    | Y (S5)     | existing API error  | Y (existing)\n  writeProfile#cache.delete   | adapter failure after commit | Y (bypass)   | Y          | correct, slower     | Y (no keys)\n  controller swap             | in-flight miss during swap   | Y (isolation)| Y (S6)     | committed version   | Y (existing)\n  LRU                         | hot set > 1000 / 16 MiB      | Y (evict)    | Y          | lower hit rate      | Y (eviction metric)\n```\n8 rows, 0 CRITICAL GAPS.\n\n### Diagrams\n1. System architecture: Section 1. 2. Data flow with shadow paths: Sections 1\nand 4. 3. State machine: cache entry per key —\n```\n  [absent] --fill(gen unchanged)--> [value v, TTL 30s] --write commit+delete--> [absent]\n  [absent] --fill(absent DTO)-----> [sentinel, TTL 10s] --create commit+delete--> [absent]\n  [absent] --fill(gen changed)----> [absent]  (suppressed; impossible: stale value installed after completed write)\n  [value]  --TTL expiry/evict-----> [absent]\n  any      --adapter failure------> [bypass] --empty reinit--> [absent]\n```\n4. Error flow: Section 2. 5. Deployment sequence:\n```\n  deploy wrapper (flag off) -> 10% keys, 1 healthy hour -> 50%, 1 healthy hour -> 100%, acceptance targets\n```\n6. Rollback flowchart:\n```\n  breach/alert -> disable flag -> controller stops admitting -> await old writes -> publish disabled instance -> runbook incident record -> resume criteria\n```\n\n### Stale Diagram Audit\nNo existing ASCII diagrams in files this plan touches (new module). 0 stale.\n\n## Implementation Tasks\nSynthesized from this review's findings. Each task derives from a specific\nfinding above. Run with Claude Code or Codex; checkbox as you ship.\n\n- [ ] **T1 (P1, human: ~1 day / CC: ~30min)** — wrapper — Implement the R1 fill guard (skip fills whose read overlapped a committed write; bounded in-flight state) and scenarios S1–S6 on the existing harness\n  - Surfaced by: Section 1 / Section 4 — R1 stale fill after completed write (D1 → A)\n  - Files: to be determined (new wrapper module and its test file)\n  - Verify: S1–S6 pass deterministically with pause/release points; S1 asserts no fill and suppressed-fill count +1\n- [ ] **T2 (P2, human: ~1h / CC: ~5min)** — wrapper — Add the fill/write ordering ASCII comment (Section 4 schedule) above the wrapper\n  - Surfaced by: Section 5 / Section 10 — knowledge concentration\n  - Files: to be determined (wrapper module)\n  - Verify: comment present and matches Section 4 schedule in review\n- [ ] **T3 (P2, human: ~1h / CC: ~5min)** — tests — Drive TTL and sentinel-expiry tests from the harness's controlled clock\n  - Surfaced by: Section 6 — flakiness risk\n  - Files: to be determined (wrapper test file)\n  - Verify: TTL tests pass repeatedly with no wall-clock sleeps\n- [ ] **T4 (P2, human: ~30min / CC: ~5min)** — runbook — Add the note that rising suppressed fills on write-hot keys is expected, with the existing bypass/p95 alerts unchanged\n  - Surfaced by: Section 8 — runbook coverage of the new branch\n  - Files: to be determined (existing runbook)\n  - Verify: runbook reviewed by service owner before the 10% stage\n_No new tasks from Sections 3, 7, 9, 11._\nTask JSONL for /autoplan: **not persisted** (state writes out of this run's scope).\nRatios assumed: bug fix with regression ~20x, docs ~10x.\n\n### Completion Summary\n```\n  +====================================================================+\n  |            MEGA PLAN REVIEW — COMPLETION SUMMARY                   |\n  +====================================================================+\n  | Mode selected        | HOLD SCOPE                                  |\n  | System Audit         | skipped per run rules (fixture)             |\n  | Step 0               | HOLD SCOPE; R1 approved (D1 → A)            |\n  | Section 1  (Arch)    | 1 issue found (R1, resolved)                |\n  | Section 2  (Errors)  | 7 error paths mapped, 1 GAP (resolved)      |\n  | Section 3  (Security)| 0 issues found, 0 High severity             |\n  | Section 4  (Data/UX) | 5 edge cases mapped, 0 unhandled            |\n  | Section 5  (Quality) | 1 issue found (R1; comment task T2)         |\n  | Section 6  (Tests)   | Diagram produced, 0 gaps (T3 note)          |\n  | Section 7  (Perf)    | 0 issues found                              |\n  | Section 8  (Observ)  | 1 gap found (runbook note, T4)              |\n  | Section 9  (Deploy)  | 0 risks flagged                             |\n  | Section 10 (Future)  | Reversibility: 5/5, debt items: 2           |\n  | Section 11 (Design)  | SKIPPED (no UI scope)                       |\n  +--------------------------------------------------------------------+\n  | NOT in scope         | written (1 rejected, 0 deferred)            |\n  | What already exists  | written                                     |\n  | Dream state delta    | written                                     |\n  | Error/rescue registry| 7 rows, 0 CRITICAL GAPS                     |\n  | Failure modes        | 8 total, 0 CRITICAL GAPS                    |\n  | TODOS.md updates     | 0 items proposed                            |\n  | Scope proposals      | 0 proposed, 0 accepted (HOLD SCOPE)         |\n  | CEO plan             | skipped by mode                             |\n  | Outside voice        | codex disabled (no completed review)        |\n  | Lake Score           | 1/1 recommendations chose complete option   |\n  | Diagrams produced    | 6 (arch, data flow, state, error, deploy,   |\n  |                      | rollback)                                   |\n  | Stale diagrams found | 0                                           |\n  | Unresolved decisions | 0                                           |\n  +====================================================================+\n```\nReview Log / decision log / dashboard read: **not persisted / not run** (state\nwrites and gstack history are out of this run's scope; no write attempted).\nNo durable learnings this session.\n\n### Unresolved Decisions\nNone. D1 was resolved by authorized auto-decision (A).\n\n## GSTACK REVIEW REPORT\n\n| Review | Trigger | Why | Runs | Status | Findings |\n|--------|---------|-----|------|--------|----------|\n| CEO Review | `/plan-ceo-review` | Scope & strategy | 1 (not persisted) | CLEAR | mode: HOLD SCOPE, 0 critical gaps |\n| Outside Review | codex (`codex_reviews: disabled`) | Independent 2nd opinion | 0 | DISABLED | disabled by config; no completed external review |\n| Eng Review | `/plan-eng-review` | Architecture & tests (required) | 0 | — | not run |\n| Design Review | `/plan-design-review` | UI/UX gaps | 0 | — | not run (no UI scope) |\n| DX Review | `/plan-devex-review` | Developer experience gaps | 0 | — | not run |\n\n**OUTSIDE COVERAGE:** provider codex, phase plan-review, disabled by `codex_reviews: disabled`; no outside process or native fallback ran; no findings; disabled record not persisted.\n**VERDICT:** CEO CLEARED (HOLD SCOPE; R1 resolved by D1 → A) — eng review required\n\nNO UNRESOLVED DECISIONS\n"
  }
}