Compare commits

..
12 Commits
Author SHA1 Message Date
kiskaadee 919a194eb2 docs(planning): close CW-01 and advance sequence to S2-01
- Mark CW-01 COMPLETED (USER_EXPLICIT, 2026-11-16; CW-01a–CW-01e closed and map approved) in planning/issue-4-follow-through.md

- Reference resulting artifact [Supporting System Map](../.internal/cw-01-supporting-system-map.md)

- Advance S2-01 to READY (CW-01 approved; S2-01 not started)
2026-11-16 20:16:56 -05:00
kiskaadee 4c1e1846c7 chore(git): ignore .internal directory 2026-11-16 19:35:33 -05:00
kiskaadee c4914926a7 docs(planning): close Stage 1 (S1-18) and advance sequence to CW-01
- Update planning/issue-4-decision-ledger.md preamble and Section 3 header to reflect 17/17 resolved USER_EXPLICIT Stage 1 decisions
- Mark S1-18 COMPLETED (USER_EXPLICIT, 2026-11-15) in planning/issue-4-follow-through.md
- Advance CW-01 to READY (CW-01a–CW-01e CLOSED; Supporting System Map & Stage 2 gate awaiting start)
2026-11-15 16:38:04 -05:00
kiskaadee 50edeae282 docs(planning): record verified Stage 1 decisions S1-01 through S1-17
- Apply R-01b BL-03 wording clarification distinguishing questionnaire_hash (Hq) from ADR-0007 publication_intent expected_sha256
- Record USER_EXPLICIT dispositions for B2.4 contract versioning and boundaries (S1-01–S1-05) and B2.5 hash/canonical persistence (S1-06–S1-07)
- Record USER_EXPLICIT disposition for C2 legacy attempt.json rejection (S1-08)
- Record USER_EXPLICIT dispositions for Cluster D repository, workspace/error taxonomy, registration lifecycle, startup readiness, liveness inspection, CLI schema_version, and key/backup gates (S1-09–S1-15)
- Record USER_EXPLICIT dispositions for Cluster E staging slots, derived pre-debrief reconciliation, and bundle-bound consolidation (S1-16–S1-17)
- Update S1-01–S1-17 statuses in planning/issue-4-follow-through.md while leaving S1-18 closure and CW-01 pending explicit authorization
2026-11-15 08:01:16 -05:00
kiskaadee 49a76ef70d docs(architecture): establish issue #4 discovery baseline
Preserve the verified architectural invariants, accepted decisions,
decision provenance, and pending Stage 1 recommendations.

Introduce the decision ledger and follow-through tracker as the
authoritative planning artifacts for the next architectural phase.
2026-11-13 17:30:02 -05:00
kiskaadee a4eeccf304 docs(architecture): reconcile physical and structural answer-leakage boundaries in Issue 7
- Narrow runtime guarantee to physical exclusion of private evaluation data from live-quiz.
- Mandate recursive Pydantic extra='forbid' across all nested public-contract models.
- Specify context-isolated post-hoc evaluation boundary following successful terminal publication.
- Clarify that prompt semantic quality and cross-question clues are authoring QA concerns.
- Explicitly reject automated semantic leakage pipelines and artificial navigation restrictions.
- Reconcile ADR-0004 problem statement, consequences, and threat model.
2026-11-11 23:31:15 -05:00
kiskaadee e71f7e5d46 docs(architecture): reconcile server-authoritative dual-clock timing and temporal edge cases in Issue 6
- Specify active assessment budget via CLOCK_MONOTONIC and pause grace keepalive via CLOCK_BOOTTIME.
- Mandate BOOTTIME-aware pause-grace watchdog evaluation upon system wake.
- Persist immutable attempt time_limit_ns at session initialization.
- Enforce commit-before-anchor advancement invariant for in-memory monotonic checkpoints.
- Establish strict serialized mutation admission rule under BEGIN IMMEDIATE write boundary.
- Require FastAPI autonomous watchdog for background timeout initiation.
- Document Suspend Gap Detection via clock delta comparison and session_intervals audit table.
- Reconcile ADR-0002 pause-grace deadline semantics with boot_id verification.
- Specify browser presentation-only countdown, visibility lifecycle resync, and formative threat model.
2026-11-11 22:40:44 -05:00
kiskaadee 434b2ec7bb docs(architecture): reconcile publication transaction boundary, projection versioning, and cleanup separation in Issue 5
- Enforce BEGIN IMMEDIATE write-serialization boundary prior to response snapshot assembly.
- Atomically commit final submission, COMPLETED status, and publication intent in Path A.
- Version export projections in publication intent and validate reconstructed hashes.
- Decouple Phase 1 read-only extraction from Phase 2 post-verification writable WAL checkpointing.
- Mandate explicit closure of Phase 1 connection before opening Phase 2 cleanup.
- Enforce dual advisory locking (per-attempt and destination) and atomic no-replace publication.
- Decouple operational exit codes: separate EXPORT_IO_ERROR from CLEANUP_PENDING and conflicts.
2026-11-11 21:46:25 -05:00
kiskaadee 5f3295b948 docs(architecture): define draft preservation, recovery paths, and terminal export contracts in Issue 4
- Establish the response state triad (SUBMITTED, DRAFT, UNANSWERED) in attempt.json.
- Decouple interaction submission status from demonstrated cognitive attainment.
- Mandate valid lifecycle combinations: COMPLETED requires all SUBMITTED; CLOSED_EARLY and TIMED_OUT require at least one DRAFT or UNANSWERED.
- Enforce generalized server-side serialization with strictly absorbing terminal states.
- Commit final required response submission and transition to COMPLETED atomically.
- Delineate nonterminal recovery (live resume) from terminal export recovery (retry publication without reopening session).
- Define evaluator rules across response states: evaluate drafts without penalty; report no evidence for UNANSWERED without negative knowledge inference.
- Clarify that drafts require learner-generated modifications; untouched initial fields remain UNANSWERED.
2026-11-11 14:45:46 -05:00
kiskaadee b28ed51026 docs(architecture): reconcile canonical objective registry boundary and skills integration in Issue 3
- Delineate engine integration boundary: live-quiz provides structural traceability without semantic registry awareness.
- Explicitly state that engine performs no registry queries, identity resolution, or longitudinal history management.
- Update architecture diagram to show feedback path from quiz-evaluator through tutor into Learner History.
- Mandate deterministic objective mapping for evaluators in data contracts and architecture specifications.
- Phrase attempt schema validation normatively in ADR-0007 while keeping exact schema layout open.
- Update ADR-0009 reference skills to depend on an abstract external registry and longitudinal history capability.
- Preserve Socratic debrief protocol, exposure vs. mastery distinctions, and external open design questions.
2026-11-11 12:48:25 -05:00
kiskaadee 2280595c33 docs(adr): qualify SQLite durability guarantees and crash recovery in ADR-0006
- Specify commit-before-ack ordering for answer submissions and draft updates.
- Mandate SQLite WAL mode with synchronous=FULL and persistent XDG state storage.
- Clarify that journal set includes companion -wal and -shm files for recovery.
- Define recovery scope: acknowledged transactions restored; unacknowledged input excluded.
- Bound active-time recovery: restore last committed ~1s checkpoint; exclude process downtime.
2026-11-11 09:18:05 -05:00
kiskaadee 8e0adb3248 docs(adr): decouple process termination from assessment completion in ADR-0002 and ADR-0006
- ADR-0002: Establish that process exit does not equal assessment completion.
  Define structured lifecycle outcome on stdout (FINALIZED, SUSPENDED, ERROR).
  Add sequence diagram showing in-browser pause/resume vs 2-hour grace period exit.
- ADR-0006: Define Pause as a durable transaction committed to SQLite before ACK.
  Establish a 2-hour configurable pause grace period allowing seamless in-browser
  resumption without CLI or agent intervention.
  Add state diagram for assessment states (RUNNING, PAUSED, COMPLETED, CLOSED_EARLY, TIMED_OUT).
2026-11-11 08:02:00 -05:00
10 changed files with 907 additions and 110 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
.internal/
+178 -67
View File
@@ -16,46 +16,52 @@ Conversational AI tutoring in typical chat interfaces lacks a stable, invariant
[ Learning Context / Instruction ]
│
▼
Objective Ledger (in context)
• Flat objectives with `enables` edges
• Cumulative coverage observations
• Active / Deferred disposition
│
▼ (Assessment Milestone & Learner Consent)
Assessment Brief
│
▼
`quiz-designer` Skill
│
┌────────────────┴────────────────┐
▼ ▼
`questionnaire.json` `rubric.json`
(Public Presentation) (Private Evaluation)
[ External Learning System ]
┌───────────────────────────────────────────────────────┐
│ • Canonical Catalog (Competencies, Objectives, IDs) │
│ • Learner History (Observations, Contexts, Evidence) │◄────────────┐
└───────────────────────────────────────────────────────┘ │
│ │
▼ │
[ `live-quiz` Engine ] │
• Standalone Local Web App │
• Zero LLM at runtime │
• Ephemeral SQLite Journal │
• Authoritative Server Timer │
• Active time vs Pause tracking │
`learning-objectives` / `tutor` │
(Candidate search & contextual scoping) │
│ │
│ (Atomic Export attempt.json) │
▼ ▼
`attempt.json` ──────────────► [ `quiz-evaluator` Skill ]
│
▼
`evaluation.json`
│
▼
[ `tutor` Skill ]
(3-Stage Socratic Debrief)
│
▼
[ Cognitive Consolidation ]
(Selective Project Docs Only)
▼ (Assessment Milestone & Learner Consent) │
Assessment Brief │
│ │
▼ │
`quiz-designer` Skill │
│ │
┌────────────────┴────────────────┐ │
▼ ▼ │
`questionnaire.json` `rubric.json` │
(Public Presentation (Private Evaluation │
+ Canonical Objective Refs) + Deterministic Obj Mappings) │
│ │ │
▼ │ │
[ `live-quiz` Engine ] │ │
• Standalone Local Web App │ │
• Zero LLM at runtime │ │
• Ephemeral SQLite Journal │ │
• Authoritative Server Timer │ │
• Structural Traceability of Obj Refs │ │
│ │ │
│ (Atomic Export attempt.json) │ │
▼ ▼ │
`attempt.json` ──────────────► [ `quiz-evaluator` Skill ] │
(Preserves Question-to-Objective │ (Deterministic │
Response Mappings Verbatim) ▼ Correlation) │
`evaluation.json` │
│ │
▼ │
[ `tutor` Skill ] │
(3-Stage Socratic Debrief) │
│ │
┌────────────────┴────────────────┐ │
▼ ▼ │
[ Cognitive Consolidation ] (Logs Observations │
(Selective Project Docs Only) & Evidence) ───────┘
```
---
## 2. System Responsibilities & Boundaries
@@ -68,11 +74,11 @@ The repository distributes two decoupled products:
| Component | Responsibility | Inputs | Outputs | Core Invariants |
| :--- | :--- | :--- | :--- | :--- |
| **`learning-objectives`** | Formulates observable, assessable competencies from learning goals. | Topic / Goals / Context | Objectives & evidence criteria | Does not assume mastery; separates intention from demonstration. |
| **`quiz-designer`** | Compiles an approved Assessment Brief into public and private contracts. | Assessment Brief | `questionnaire.json`, `rubric.json` | Max 3-question chains; hermetic context or independent rubrics; no answer leakage. |
| **`live-quiz` Engine** | Ephemeral web server executing the assessment and capturing evidence. | `questionnaire.json`, CLI flags | `attempt.json`, session status | Never receives `rubric.json`; zero runtime LLM; authoritative server clock. |
| **`quiz-evaluator`** | Context-isolated post-hoc evaluation of attempt against frozen rubric. | `rubric.json`, `attempt.json` | `evaluation.json` | Fresh context; purely evaluates $f(\text{rubric}, \text{attempt})$ without chat history. |
| **`tutor`** | Facilitates learning, proposes assessment scope, leads debrief. | Learner dialogue, context | Learning interactions | Does not force assessments; leads Socratic debrief before solution reveal. |
| **`learning-objectives`** | Formulates observable, assessable competencies; searches external catalog to propose new records and relationships. | Topic / Goals / Context, Registry candidates | Proposed objectives & evidence criteria | Does not assume mastery; canonical identity established by registry; separates intention from demonstration. |
| **`quiz-designer`** | Compiles an approved Assessment Brief into public and private contracts. | Assessment Brief, Learner history | `questionnaire.json`, `rubric.json` | Max 3-question chains; hermetic context or independent rubrics; keeps the private rubric outside the public questionnaire and runtime contracts; rejects undeclared evaluation properties; prompt semantic quality is an authoring responsibility; history informs difficulty without equating exposure to mastery. |
| **`live-quiz` Engine** | Ephemeral web server executing assessment, capturing evidence, and preserving objective references. | `questionnaire.json`, CLI flags | `attempt.json`, session status | Never receives `rubric.json`; zero runtime LLM; authoritative server clock; structural traceability of objective references; zero semantic registry queries. |
| **`quiz-evaluator`** | Context-isolated post-hoc evaluation of attempt against frozen rubric. | `rubric.json`, `attempt.json` | `evaluation.json` | Fresh context; purely evaluates $f(\text{rubric}, \text{attempt})$ without chat history; associates evidence with canonical objective references. |
| **`tutor`** | Facilitates learning, proposes assessment scope, logs contextual observations against stable objective IDs, leads debrief. | Learner dialogue, context, Registry/History | Learning interactions, Contextual observations | Does not force assessments; leads Socratic debrief before solution reveal; preserves repeated encounters; exposure is not mastery. |
| **Project Repository** | Selective retention of project-specific technical findings or ADRs. | User / Tutor choice | Project docs / Git commits | No mandatory central vault; documentation follows project conventions. |
---
@@ -82,13 +88,26 @@ The repository distributes two decoupled products:
The system communicates strictly across four versioned JSON contracts:
1. **`questionnaire.json` (Public Presentation Contract):**
Consumed by `live-quiz`. Contains question IDs, markdown prompts, Mermaid diagrams, KaTeX equations, interaction types, option labels, and initial code stubs. *Physically excludes answers, rubrics, and misconceptions.*
Consumed by `live-quiz`. Contains question IDs, markdown prompts, Mermaid diagrams, KaTeX equations, interaction types, option labels, initial code stubs, and associated canonical objective references. The public contract is positively defined and enforces `extra="forbid"` recursively across root and all nested models (via shared strict base inheritance), rejecting undeclared evaluation properties such as answer-key fields, rubric criteria, and misconception signatures. This is structural validation and does not inspect prompt content for semantic answer leakage.
2. **`rubric.json` (Private Evaluation Contract):**
Retained by the calling agent workflow and supplied only to the evaluator. Contains learning objectives, observable criteria (Complete / Partial / Insufficient), categorical failure modes, and misconception signatures.
Retained by the calling agent workflow and supplied only to the evaluator. Contains learning objectives, observable criteria (Complete / Partial / Insufficient), categorical failure modes, misconception signatures, and explicit canonical objective references for each criterion (or a deterministic question-to-criterion mapping) to eliminate ambiguous natural-language inference.
3. **`attempt.json` (Durable Execution Evidence):**
Produced by `live-quiz` via atomic publication. Contains attempt identity, assessment/version hashes, workspace attribution, terminal status (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`), active and wall-clock durations, pause event logs, and submitted responses.
Produced by `live-quiz` via atomic publication. Must conform structurally to the versioned attempt schema contract (`attempt.schema.json`). Contains attempt identity, assessment/version hashes, workspace attribution, terminal lifecycle status (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`), active and wall-clock durations, pause event logs, and an array of responses preserving question-level canonical objective references verbatim. Every item in the responses array explicitly records its interaction state via the **Response State Triad**:
- `SUBMITTED`: Explicitly confirmed by the learner (including explicit blank submissions).
- `DRAFT`: Latest acknowledged autosave payload and receipt timestamp preserved at session termination, even if unsubmitted. A draft represents an acknowledged learner-generated modification (initial empty fields remain `UNANSWERED`). (Per-question active duration is provisional pending measurement definitions).
- `UNANSWERED`: Zero acknowledged learner input recorded (payload is null).
*Valid Lifecycle & Response Combinations:*
While interaction status and demonstrated criterion attainment remain independent dimensions, lifecycle outcomes constrain valid response combinations:
- `COMPLETED`: Strictly requires every questionnaire item to have `response_status: SUBMITTED` (explicit blank submissions qualify).
- `CLOSED_EARLY`: At least one response must be `DRAFT` or `UNANSWERED`, following an explicit learner termination action.
- `TIMED_OUT`: At least one response must be `DRAFT` or `UNANSWERED`, following authoritative timer expiration.
*Generalized Server-Side Serialization & Absorbing Terminal States:* All response mutations (autosaves and submissions) and terminal transitions (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`) are serialized server-side within SQLite transactions. The final required response submission and transition to `COMPLETED` must be committed atomically. Once any terminal lifecycle transition commits, its status is strictly immutable and absorbing: all subsequent response mutations and competing terminal transition attempts are rejected.
4. **`evaluation.json` (Diagnostic Assessment Report):**
Produced by `quiz-evaluator`. Contains criterion-level attainment ratings, failure-mode classifications (`CONCEPTUAL`, `LOGICAL`, `SYNTACTIC`, `OMISSION`, `REGRESSION`), misconception hypotheses with confidence levels, and discussion probes for debriefing.
Produced by `quiz-evaluator`. Contains criterion-level attainment ratings correlated deterministically to canonical objective references, failure-mode classifications (`CONCEPTUAL`, `LOGICAL`, `SYNTACTIC`, `OMISSION`, `REGRESSION`), misconception hypotheses with confidence levels, and discussion probes for debriefing.
*Evaluator Contract Across the Response State Triad:*
- Explicit Blank `SUBMITTED`: Evaluated as an intentional empty response against rubric criteria.
- `DRAFT`: Evaluated as available evidence of learning (identifying valid intermediate reasoning and progress) without automatic penalty for draft status. Discloses draft provenance, avoids hallucinating what the learner would have written with more time, and distinguishes demonstrated criteria from unestablished criteria.
- `UNANSWERED`: Reports that no response evidence exists. Must not infer a misconception or conclude that the learner lacks underlying competency solely because no response was recorded.
---
@@ -108,8 +127,19 @@ The frontend is packaged as a static single-page application built via Vite Plus
- **Context Sharing:** Questions may share an overarching technical scenario or stimulus.
- **Independent Rubrics:** Each question evaluates its own distinct learning objective. Later questions provide sufficient canonical context to remain answerable even if earlier questions were missed, strictly preventing compound penalization (double jeopardy).
### 4.3 Blind Pass Invariant
### 4.3 Blind Pass Invariant & Answer-Leakage Boundary
1. **Blind Pass Administration:**
The runtime provides **zero immediate correctness feedback, validation cues, or hints** during administration. The learner demonstrates unassisted performance against the frozen standard.
2. **Physical Runtime Separation:**
`questionnaire.json` is the only assessment-definition artifact accepted by `live-quiz`. No supported CLI option, configuration parameter, API endpoint, or runtime code path allows `rubric.json` or its contents to enter the engine.
3. **Recursive Structural Contract Separation & Pydantic Inheritance:**
Public and private contracts are maintained as disjoint Pydantic schemas. Because Pydantic v2 does not automatically propagate model configuration across nested model boundaries, every model at every nesting depth (root questionnaire, question objects, option structures, and input configurations) must inherit from a shared strict base model configured with `extra="forbid"` or declare it explicitly. Contract test suites must include negative validation tests asserting that unexpected evaluation properties are rejected at multiple nesting depths.
4. **Context-Isolated Post-Hoc Evaluation:**
`quiz-evaluator` receives `rubric.json` and `attempt.json` only after successful terminal publication. The evaluator operates in a fresh context, receiving zero conversational history, tutor notes, or learner-profile context. The Tutor uses `evaluation.json` during the subsequent debrief.
5. **Ergonomic Presentation & Explicit Non-Goals:**
`live-quiz` retains its standard one-question-at-a-time presentation for cognitive ergonomics, but does not impose navigation locking or anti-backtracking restrictions solely for security. The architecture explicitly rejects automated LLM semantic leakage detection and cross-question graph analysis; prompt semantic quality remains an authoring responsibility.
6. **Engineering Guarantee & Formative Threat Model:**
`live-quiz` guarantees physical exclusion of the private rubric artifact from the engine and structural rejection of undeclared evaluation properties in the public questionnaire. It does not guarantee that questionnaire content authored by an LLM or human is semantically free of answers, clues, or cross-question leakage. Host-level inspection of local files or process memory remains outside the formative assessment threat model.
---
@@ -124,35 +154,116 @@ The system explicitly separates:
### 5.2 Ephemeral SQLite Session Journal
During active assessment, `live-quiz` maintains state in a temporary SQLite database (`~/.local/state/live-quiz/sessions/<attempt-id>.sqlite3`):
- Server commits acknowledged draft updates, answer submissions, and timing events atomically to SQLite.
- Pausing commits state and **allows the server process to exit cleanly**, preventing idle background processes.
- Unexpected kills (`SIGKILL`, power failure) leave the journal intact.
- **Active-Time Representation:** Accumulated active time is tracked and persisted as an integer nanosecond scalar (`accumulated_active_ns`) in the session state table, converted to seconds only for UI display and `attempt.json` export.
- **In-Memory Anchor Advancement Invariant:**
$$\Delta t = t_{\text{monotonic now}} - t_{\text{last committed}}$$
$$\text{accumulated\_active\_ns}' = \text{accumulated\_active\_ns} + \Delta t$$
The in-memory anchor `last_committed_checkpoint_ns` advances strictly **after** the SQLite transaction commits successfully. If commit fails, the anchor does not advance.
- **Checkpoint Triggers & Durability Guarantee:** Checkpoints target approximately 1 second while `RUNNING`, with synchronous immediate checkpoints on pause, autosave, submission, timeout, and early close (all sharing the serialized write boundary `BEGIN IMMEDIATE`). Recovery resumes from the last successfully committed active-time checkpoint; uncommitted elapsed time is not guaranteed to be preserved under sudden process crashes or machine load.
- **Durable Pause Checkpoint & In-Browser Resume:** Clicking **Pause** commits state, freezes active time, records `status = PAUSED` in SQLite, and displays an in-browser Resume control.
- **Configurable Pause Grace Period (Default: 2 Hours):** The server remains alive and accessible in the browser during a 2-hour window (`--pause-grace-period 2h`). If resumed within this window, the assessment continues instantly in the browser.
- **Grace-Period Expiration & Boot Identity:** Pause grace is measured using Linux `CLOCK_BOOTTIME` (which advances across system sleep). Stored metadata includes `{ boot_id, pause_started_boottime_ns, pause_deadline_boottime_ns }`. If the 2-hour grace period expires without resumption on the same boot, the server process terminates cleanly to prevent zombie processes, retaining the journal with status `PAUSED` and emitting `outcome: SUSPENDED` on stdout. Across a machine reboot, the original in-browser server is dead, the persisted boottime deadline is never compared across different boot IDs, and the journal remains intact for manual CLI recovery.
- Unexpected kills (`SIGKILL`, power failure) leave the journal intact for recovery.
### 5.3 Atomic Publication & Journal Deletion
Upon reaching a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`):
1. The server serializes the final attempt payload.
2. Writes to a temporary file in the destination directory.
3. Validates the JSON structure and flushes/syncs to disk.
4. Atomically renames the file to the final destination (`attempt.json`).
5. Closes database handles and unlinks the temporary SQLite journal.
6. Exits with code 0.
### 5.3 Dual-Clock Timing Architecture & Temporal Edge Cases
1. **Definition of Active Assessment Time:**
Active assessment time is accumulated while the assessment is `RUNNING`, the engine is operational, and the host system is awake. It does not accumulate while `PAUSED`, the host is suspended, or the engine is terminated:
*Invariant:* The temporary journal is never deleted if export publication fails.
| Situation | Assessment State | Active Budget | Pause Grace Window |
| :--- | :--- | :--- | :--- |
| Learner answering questions | `RUNNING` | Decreases | Not applicable (not paused) |
| Browser tab hidden / backgrounded | `RUNNING` | Decreases | Not applicable (not paused) |
| Host system suspended (laptop lid closed) | `RUNNING` | **Frozen** | Not applicable (not paused) |
| Learner explicitly pauses | `PAUSED` | **Frozen** | Elapses toward deadline |
| Host system suspended while paused | `PAUSED` | **Frozen** | Elapses toward deadline |
| Engine crashes or terminates | Last persisted checkpoint | **Frozen** | In-browser server exited (persisted boottime deadline continues elapsing on same boot only if last persisted state was PAUSED) |
### 5.4 Explicit Recovery Command
To resume an interrupted or paused attempt:
```bash
live-quiz recover --from-path ~/.local/state/live-quiz/sessions/<attempt-id>.sqlite3
```
Recovery validates the journal, restores the authoritative clock, re-mounts drafts, and starts the server without altering the attempt identity.
2. **Dual-Clock System & Linux Platform Baseline:**
- **Active Assessment Budget (`CLOCK_MONOTONIC`):** Sampled via `time.monotonic_ns()`. Unaffected by discontinuous wall-clock shifts (manual time adjustments, NTP steps), though subject to gradual frequency adjustments (NTP slewing). Crucially, it halts during kernel suspend (ACPI S3/sleep), automatically freezing the assessment budget when a laptop lid closes without requiring OS D-Bus or `systemd-logind` hooks.
- **Operational Pause Grace Timer (`CLOCK_BOOTTIME`):** Sampled via `time.clock_gettime_ns(time.CLOCK_BOOTTIME)`. Advances during kernel suspend, ensuring that laptop sleep elapses the in-browser keepalive window.
- **BOOTTIME-Aware Pause-Grace Watchdog:** Because Python's `asyncio` event loop schedules delayed timers via `loop.time()` (which uses `CLOCK_MONOTONIC` and halts during suspend), an ordinary `asyncio.sleep()` cannot reliably fire a boottime deadline. The pause-grace watchdog re-evaluates the persisted `CLOCK_BOOTTIME` deadline at the first post-wake watchdog execution (triggered when a suspend gap is detected or via a bounded periodic check), executing clean shutdown with `outcome: SUSPENDED` if the deadline has passed while asleep.
3. **Autonomous Watchdog, Immutable Time Limits & Serialized Admission:**
- **Immutable Attempt Time Limit (`time_limit_ns`):** The assessment duration budget is immutable for each attempt. It is persisted in SQLite session state at attempt initialization and traceable to the immutable questionnaire version. Recovery must never load altered CLI defaults or application configurations that silently mutate an existing attempt's time budget.
- An `asyncio` background watchdog in FastAPI monitors the remaining active budget. When the deadline is reached, it initiates the terminal transition to `TIMED_OUT` without waiting for client interaction.
- **Serialized Mutation Admission Rule:** Every mutation endpoint (`POST /api/response/autosave`, `POST /api/response/submit`) independently validates the deadline while holding the SQLite write-serialization boundary (`BEGIN IMMEDIATE`). Monotonic time is sampled *after* acquiring the write lock:
- $T_{\text{elapsed}} < T_{\text{limit}} \implies$ mutation accepted and checkpointed.
- $T_{\text{elapsed}} \ge T_{\text{limit}} \implies$ mutation rejected; endpoint commits `TIMED_OUT` and `publication_intent`.
- A delay in the background watchdog cannot allow late submissions to be accepted.
- **Overdue Recovery Guard:** If `live-quiz recover` inspects a journal where `accumulated_active_ns >= time_limit_ns`, the engine immediately terminalizes the attempt as `TIMED_OUT` and initiates atomic export before any interactive resume is permitted.
4. **System Suspend Gap Detection:**
- The engine periodically compares clock deltas:
$$T_{\text{suspended}} \approx \Delta T_{\text{BOOTTIME}} - \Delta T_{\text{MONOTONIC}}$$
- When a positive discrepancy exceeds a threshold (indicating the machine slept), the engine appends a `SUSPEND_GAP_DETECTED` event to the `session_intervals` audit table upon wake.
- `session_intervals` table uses `event_sequence INTEGER PRIMARY KEY AUTOINCREMENT` to guarantee strictly monotonic event ordering independently of wall-clock accuracy.
5. **Browser Presentation & Re-synchronization:**
- The browser UI is a presentation layer only. Countdown is calculated locally based on the latest server payload (`remaining_seconds`, `is_active`).
- When a tab is hidden, local visual updates halt to avoid burning CPU on throttled timers.
- The client listens to the Page Visibility API (`document.visibilityState === 'visible'`) and window reconnect events, issuing `GET /api/session` upon re-entry to resynchronize the countdown without continuous background polling.
6. **Threat Model & Trust Boundary:**
The timing architecture is **server-authoritative relative to the browser**, guarding against client clock tampering, background timer throttling, network latency games, and wall-clock skew. Host-level root or user tampering (e.g. modifying SQLite directly or patching the Python binary) is explicitly outside the threat model of a local, formative personal assessment tool.
### 5.4 Ten-Step Atomic Publication Pipeline & Durability Contract
Upon reaching a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`), publication executes through a strict 10-step durability pipeline protected by dual advisory locks (per-attempt and destination-level):
1. **Dual Advisory Concurrency Locks:** Acquire exclusive locks via `fcntl`/`flock` on:
- Per-attempt lock file (`~/.local/state/live-quiz/locks/attempt-<attempt-id>.lock`), coordinating publication and recovery.
- Destination-level lock file (`~/.local/state/live-quiz/locks/dest-<sha256_of_destination_path>.lock`), coordinating publications across different attempts targeting the same path.
Locks are retained throughout publication and cleanup, and are never unlinked while held.
2. **Transaction-Bounded Payload Preparation & Canonical Serialization:**
- Execute `BEGIN IMMEDIATE` on the writable SQLite connection to establish the write-serialization boundary before snapshot extraction.
- **Path A (Final Submission → `COMPLETED`):** The final question submission mutation (`status = SUBMITTED`), the transition to `COMPLETED`, the complete response snapshot, and `publication_intent` are constructed and committed within this single transaction. The final response is never acknowledged as submitted without atomically committing assessment completion.
- **Path B (Timeout / Early Close):** The transaction lock is established before extracting the snapshot (capturing current drafts and unanswered questions) and committing `TIMED_OUT` or `CLOSED_EARLY` alongside `publication_intent`.
- Validate payload structurally against target `attempt.schema.json`. Serialize the canonical payload using RFC 8785 Canonical JSON (deterministic key ordering, UTF-8, normalized numbers) and calculate `expected_sha256`.
3. **Atomic Terminal Commitment & Publication Intent:** Within the open transaction, atomically commit:
- Terminal lifecycle state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`).
- Final response snapshot (incorporating the final submission in Path A).
- Immutable `publication_intent`: `target_schema_version`, `export_projection_version: "1"`, `destination_path`, `canonicalization_version: "1"`, `expected_sha256`.
- Execute `COMMIT;`. Filesystem publication then proceeds using the already-determined canonical bytes.
4. **Destination Conflict Pre-Check:** Under the destination lock, inspect `destination_path`. If an artifact exists with a different `attempt_id`, abort immediately with `CONFLICT_DIFFERENT_ATTEMPT` (exit 2) without writing or renaming. Overwriting another attempt's artifact is strictly prohibited.
5. **Attempt-Specific Temporary File Write & Fsync:** Write canonical bytes to `.attempt.<attempt-id>.tmp` in the destination directory, flush, and `fsync` the file descriptor.
6. **Atomic Rename / Link:** Atomically rename `.attempt.<attempt-id>.tmp` to `attempt.json` (on Linux, using `renameat2(..., RENAME_NOREPLACE)` or atomic link/rename guarantees no race overwrites another attempt's artifact).
7. **Destination Directory Fsync:** Open parent directory descriptor and `fsync` directory metadata, guaranteeing rename persistence across power failures.
8. **Verified WAL Checkpoint:** Through the open writable connection, execute passive/truncate WAL checkpoint (`PRAGMA wal_checkpoint(TRUNCATE);`) and verify completion (`busy == 0, log == 0`).
9. **Clean Close & Ordered Journal Cleanup:** Close all database handles cleanly. SQLite removes/truncates `-shm` and `-wal`. Then verify companion removal (unlinking `-wal` and `-shm` explicitly if still present), and unlink the primary `.sqlite3` database file **last**.
10. **Structured Process Outcome:** Emit single-line JSON outcome packet on stdout and exit 0 (`SUCCESS_FINALIZED`).
*Operational Decoupling:*
- If publication fails during steps 1–7 (e.g. disk full, permission denied, destination conflict, directory sync failure), the process exits with `EXPORT_IO_ERROR` (code 1) or conflict codes (2, 3) and the complete journal file set remains intact.
- If publication succeeds through step 7 but checkpoint or journal cleanup (steps 8–9) fails, the process exits with `CLEANUP_PENDING` (code 6), signaling that `attempt.json` is durable and verified, but journal removal requires retry.
### 5.5 Two Distinct Recovery Paths & Idempotency Verification
Invoking `live-quiz recover --from-path <journal.sqlite3>` acquires the shared advisory locks (per-attempt and destination lock) and routes deterministically:
1. **Nonterminal Recovery (`RUNNING` or `PAUSED`):**
- Applies in-place transactional migrations if the internal journal schema version differs from the current engine.
- Restores the authoritative countdown clock, re-mounts acknowledged drafts, resumes the local HTTP server, and displays an in-browser resume control under the exact same `attempt_id`.
2. **Terminal Export Recovery (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`):**
- **Phase 1: Read-Only Historical Extraction & Reconstruction:**
- Opens SQLite with a read-only connection (`mode=ro`), reading existing `-wal` and `-shm` frames without mutating user tables or schema on disk.
- Reads persisted `publication_intent`. Legacy journals lacking `publication_intent` are explicitly rejected as unsupported (`UNSUPPORTED_SCHEMA_VERSION`, exit 5) because their target schema and reference hash cannot be verified deterministically.
- Reconstructs canonical bytes using the versioned export projection (`export_projection_version`). Before publishing, recovery calculates the SHA-256 digest of the reconstructed bytes and verifies that it strictly matches `expected_sha256`. If a mismatch occurs, recovery halts closed (`CONFLICT_INTEGRITY_MISMATCH`, exit 3) and preserves the journal.
- **Idempotency Verification against Persisted Hash:**
- *Artifact does not exist:* Publishes reconstructed canonical bytes via steps 4–7.
- *Artifact exists with matching `attempt_id` and matching `expected_sha256`:* Previous publication succeeded; advances directly to Phase 2 cleanup.
- *Artifact exists with different `attempt_id`:* Halts immediately, preserves journal, emits `CONFLICT_DIFFERENT_ATTEMPT`, and exits code 2.
- *Artifact exists with matching `attempt_id` but differing SHA-256:* Halts immediately, preserves journal, emits `CONFLICT_INTEGRITY_MISMATCH`, and exits code 3.
- **Phase 2: Post-Verification Writable Cleanup Connection:**
- Opened only after Phase 1's read-only connection and read transaction are closed cleanly, ensuring no lingering reader locks prevent checkpointing.
- Opened only after `attempt.json` has been durably published, verified against `expected_sha256`, and destination directory `fsync` has completed.
- Connects in writable mode solely to execute `PRAGMA wal_checkpoint(TRUNCATE);` with verified completion (`busy == 0, log == 0`). Schema migrations or table mutations are strictly prohibited on this connection.
- Closes connection cleanly, unlinks companion files (`-wal`, `-shm`), unlinks `.sqlite3` **last**, emits `SUCCESS_FINALIZED`, and exits 0. If checkpointing fails, journal is kept intact and process exits with `CLEANUP_PENDING` (code 6).
- **Partial Cleanup Invariant:** Because cleanup unlinks companion files first and `.sqlite3` last, orphaned `-wal` or `-shm` files without `.sqlite3` represent an unexpected anomaly. Recovery halts safely and reports an integrity error rather than silently deleting orphaned files.
---
## 6. Pedagogical Scoping & Debrief Protocol
### 6.1 Objective Ledger & Scoping
- **Representation:** Objectives are maintained in the Tutor's active context as a flat collection with directed `enables` edges.
- **Coverage Tracking:** Recorded as cumulative observations (`INTRODUCED`, `EXPLORED`, `PRACTICED`) alongside an active disposition (`ACTIVE` vs. `DEFERRED`).
- **Scoping Gate:** When an assessment milestone is reached, the Tutor compiles a candidate **Assessment Brief**. The learner explicitly reviews and approves the scope before authoring begins.
### 6.1 Canonical Objectives, Learning History & Assessment Scoping
- **Integration Boundary:** Learning workflows resolve competencies and objectives against a persistent external catalog, while learner interactions accumulate as contextual observations in a longitudinal learning history. `live-quiz` has no semantic awareness of the registry, performs no registry queries or identity resolution, and manages no longitudinal history; it merely provides structural traceability of objective references across questionnaire execution and attempt export.
- **Competencies vs. Contextualized Objectives:** The external catalog maintains a many-to-many relationship between broad, reusable competencies (e.g. *Reason about HTTP caching semantics*) and observable, contextualized learning objectives (e.g. *Explain how HTTP caching headers influence browser behavior*).
- **Objective Ledger as In-Context View:** Within active sessions, the Tutor maintains an in-context ledger referencing stable objective identities. Deferral (`ACTIVE` vs. `DEFERRED`) is an independent pedagogical disposition that does not erase or overwrite previous learning observations.
- **Exposure Informs Design, Not Mastery:** Prior observations (e.g. `INTRODUCED`, `EXPLORED`, `PRACTICED` as provisional examples) inform the Quiz Designer regarding familiarity and context novelty to avoid redundant introductory questioning. However, exposure is never equated to mastery: difficulty calibration must preserve distinctions between familiarity, task complexity, context novelty, assistance level, and demonstrated independent performance.
- **Scoping Gate via Assessment Brief:** Assessment readiness is never an intrinsic or permanent flag on an objective. It is determined dynamically when the Tutor compiles a candidate **Assessment Brief** (identifying selected canonical objectives, performance criteria, context, and intended difficulty), which the learner explicitly reviews and approves before authoring begins.
- **Deterministic Evaluator Mapping:** The assessment contract guarantees deterministic correlation between rubric criteria, question responses, and canonical objective identities without requiring `quiz-evaluator` to receive `questionnaire.json` or guess objective associations from similar wording.
- **Unresolved System Questions:** The exact structural schema mapping of objective references across `questionnaire.json`, `rubric.json`, and `attempt.json` remains to be finalized. Furthermore, detailed registry architecture—including the authoritative storage location and synchronization strategy for learner observations (e.g. interim session-local logfiles vs. centralized store), relationship semantics (e.g. refining `enables` beyond a prerequisite DAG), dynamic roles of terminal vs. enabling objectives, and concrete observation schemas—belongs to the broader learning-system architecture and remains explicitly open.
### 6.2 Three-Stage Socratic Debrief
1. **Results Overview:** High-level summary of overall attainment, demonstrated competencies, and friction points without revealing answers.
@@ -4,15 +4,53 @@
- Date: 2026-11-10
## Context
When an AI agent or skill invokes `live-quiz`, the execution must not block agent reasoning indefinitely, yet the agent must be notified when the assessment concludes. We needed a process coordination mechanism that works cleanly without tight coupling to proprietary agent harnesses.
When an AI agent or skill invokes `live-quiz`, the execution must not block agent reasoning indefinitely, yet the agent must be notified when the assessment concludes or suspends. We needed a process coordination mechanism that works cleanly without tight coupling to proprietary agent harnesses, while correctly distinguishing between process exit and assessment completion.
## Decision
Design `live-quiz` as a standard foreground UNIX process whose termination signals session conclusion. In agent environments that support managed asynchronous tasks (such as Antigravity background tasks), the agent launches `live-quiz start`, yields the URL to the user, and terminates its turn. When `live-quiz` reaches a terminal state, its process exits with code 0, naturally triggering reactive wakeup of the agent harness.
Design `live-quiz` as a standard foreground UNIX process whose termination signals that an execution cycle has ended, but **not necessarily that the assessment has concluded**:
1. **Independent Lifecycles:**
$$\text{Process State (Running / Exited)} \neq \text{Assessment State (RUNNING / PAUSED / COMPLETED)}$$
A process exit indicates only that the current HTTP execution cycle has ended.
2. **Structured Lifecycle Outcome:**
Upon process termination, `live-quiz` emits a machine-readable JSON outcome on stdout:
- **`FINALIZED`:** The assessment reached a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`). `attempt.json` was durably exported. Caller proceeds to evaluation.
- **`SUSPENDED`:** The assessment was paused and the server deliberately exits upon 2-hour grace period expiration. The pause grace period is measured using Linux `CLOCK_BOOTTIME` (advancing across system sleep) on the current host boot, distinct from the learner's active assessment budget (`CLOCK_MONOTONIC`). The SQLite journal is retained with status `PAUSED`. Caller does **not** invoke evaluation. Unexpected termination (`SIGKILL`, power failure) cannot guarantee a structured outcome packet; the caller must detect abnormal exit and offer manual recovery.
- **`ERROR`:** An operational error occurred. The SQLite journal is retained for recovery.
3. **Sequence Diagram:**
```mermaid
sequenceDiagram
autonumber
actor Learner
participant Browser
participant Server as live-quiz Server
participant SQLite as SQLite Journal
participant Caller as Agent / Harness
Learner->>Browser: Click Pause
Browser->>Server: POST /api/session/pause
Server->>SQLite: Commit drafts & transition status to PAUSED
SQLite-->>Server: Transaction committed
Server-->>Browser: 200 OK (Suspension confirmed)
Browser->>Learner: Display "Assessment Paused" + Resume button
alt Resumed within 2-hour grace period
Learner->>Browser: Click Resume
Browser->>Server: POST /api/session/resume
Server->>SQLite: Commit status RUNNING & unfreeze clock
Server-->>Browser: 200 OK
else Grace period (2h) expires without resume
Server->>Caller: Process exits (stdout: outcome=SUSPENDED)
Caller->>Caller: Inspect outcome: SUSPENDED (Do NOT invoke Evaluator)
end
```
## Alternatives Considered
- **Antigravity Sidecars and `agentapi`:** Rejected. Testing revealed that `agentapi` relies on Antigravity internal language server environment variables (`ANTIGRAVITY_LS_ADDRESS`, `ANTIGRAVITY_CSRF_TOKEN`), breaking execution when run outside the agent environment and introducing unnecessary daemon infrastructure.
- **Indefinite Synchronous Blocking Command:** Rejected. Fails over human time scales; if a learner pauses or steps away, long-running agent tool calls timeout or hang.
- **Polling Loop:** Rejected. Wastes tokens and agent execution turns polling local status endpoints.
- **Treating Every Process Exit as Assessment Completion:** Rejected. Conflating process termination with assessment finalization leads to evaluating incomplete paused attempts.
- **Immediate Process Exit on Pause:** Rejected. Turning an ordinary short interruption (e.g. 2-minute phone call) into an unrecoverable dead browser tab destroys UX.
- **Antigravity Sidecars and `agentapi`:** Rejected. Coupled to internal language server environment variables.
## Consequences
- **Positive:** Complete decoupling from harness internals; standard OS process semantics (`exit 0`); portable across Antigravity, Claude Code, terminal shells, and CI pipelines.
@@ -4,21 +4,48 @@
- Date: 2026-11-10
## Context
A core pedagogical invariant of the assessment model is the blind pass: the learner must not receive answer keys, expected solutions, or private evaluation criteria while completing the assessment. We needed an architectural mechanism to ensure this information cannot leak to the client.
A core pedagogical invariant of the assessment model is the blind pass: the learner must demonstrate unassisted performance against an invariant standard without receiving private evaluation criteria while completing the assessment. We needed an architectural mechanism to prevent private evaluation data from entering the learner-facing runtime.
## Decision
Enforce complete physical decoupling of the assessment specification at the filesystem level into two distinct artifacts:
Enforce complete physical and structural decoupling of the assessment specification at the filesystem and contract levels into two distinct artifacts:
1. `questionnaire.json`: The public presentation contract containing question IDs, markdown prompts, diagrams, options, and code stubs. Passed directly to `live-quiz`.
2. `rubric.json`: The private evaluation contract containing expected answers, observable criteria (Complete/Partial/Insufficient), failure mode diagnoses, and misconception signatures. Retained outside `live-quiz` and supplied exclusively to the post-hoc evaluator.
2. `rubric.json`: The private evaluation contract containing expected answers, observable criteria (Complete/Partial/Insufficient), failure mode diagnoses, and misconception signatures. Retained outside `live-quiz` and supplied exclusively to the post-hoc evaluator after terminal publication.
`live-quiz` never receives, loads, or serves `rubric.json`.
```mermaid
flowchart TD
QD["Quiz Designer"]
QD --> Q["questionnaire.json"]
QD --> R["rubric.json"]
Q --> LQ["live-quiz"]
LQ --> A["attempt.json"]
R --> E["Evaluator"]
A --> E
E --> EV["evaluation.json"]
style R stroke:#d97706
```
### Architectural Safeguards & Boundaries
1. **Physical Runtime Separation:**
`questionnaire.json` is the only assessment-definition artifact accepted by `live-quiz`. No supported CLI option, configuration parameter, API, or runtime code path allows `rubric.json` or its contents to enter the engine. Private evaluation data is never transmitted to the browser or exposed in the learner-facing tutoring context before assessment conclusion.
2. **Recursive Structural Contract Separation & Pydantic Inheritance:**
The public and private specifications are maintained as separate Pydantic models. Because Pydantic v2 does not automatically propagate `model_config = ConfigDict(extra="forbid")` across nested `BaseModel` boundaries, root-level configuration alone is insufficient. Every public-contract model at every nesting depth (including root questionnaire, question models, option objects, and input blocks) must explicitly inherit from a shared strict base model (e.g. `StrictBaseModel`) configured with `extra="forbid"` or declare `extra="forbid"` directly. Contract test suites must enforce negative validation tests asserting that unexpected evaluation properties are rejected at multiple nesting levels.
3. **Context-Isolated Post-Hoc Evaluation:**
`quiz-evaluator` operates purely as $f(\text{rubric.json}, \text{attempt.json}) \to \text{evaluation.json}$ and receives `rubric.json` and `attempt.json` only after successful terminal publication. The evaluator receives zero conversational history, tutor notes, or learner-profile context. The Tutor subsequently uses `evaluation.json` during the debrief.
4. **Ergonomic Presentation & Explicit Non-Goals:**
`live-quiz` retains its standard one-question-at-a-time presentation for cognitive ergonomics, but does not impose navigation locking or anti-backtracking mechanisms solely for security. Furthermore, the system explicitly rejects automated LLM-based semantic leakage detection or cross-question answer-leakage graph analysis; semantic prompt quality remains an authoring responsibility.
## Alternatives Considered
- **Single Unified Assessment JSON with Runtime Filtering:** Rejected. Passing a single file containing both questions and answer keys creates a severe risk of accidental solution leakage through permissive API routes, serialization bugs, or client-side inspection.
- **Automated Semantic Leakage Detection Pipelines:** Rejected. Introduces substantial LLM latency and coordination overhead for a personal formative assessment tool where prompt clarity is an authoring design concern.
## Consequences
- **Positive:** Physical impossibility of solution leakage via browser DevTools, network sniffing, or server memory inspection.
- **Scope Limitation / Boundary:** This architectural separation guarantees that `live-quiz` cannot leak the rubric. It does not protect against an authoring agent inadvertently embedding answers directly into the question prompt text; prompt quality remains an authoring verification concern.
- **Positive:** Physical exclusion of the private rubric artifact from the engine and structural rejection of undeclared evaluation properties in the public questionnaire; the runtime cannot expose private rubric data it never receives through browser DevTools, API inspection, or network monitoring (though this does not prevent semantically equivalent information from appearing in public questionnaire content); clean, testable separation between assessment execution and post-hoc grading.
- **Engineering Guarantee & Scope Boundary:** Physical separation guarantees that the `live-quiz` runtime does not receive or expose private evaluation data. It does not guarantee that public questionnaire content authored by an LLM or human is semantically free of answers, clues, or cross-question leakage. Host-level inspection of local files or process memory remains outside the formative assessment threat model.
## Related Decisions
- [ADR-0003: Static Code Challenges Without Runtime Execution](./0003-static-code-challenges.md)
@@ -8,10 +8,31 @@
## Decision
Implement `live-quiz` using:
- **Backend & CLI:** Python 3.11+, FastAPI, Pydantic v2, and managed via `uv`.
- **Backend & CLI:** Python 3.11+, FastAPI, Pydantic v2, and managed via `uv` on Linux (the supported runtime platform).
- **Static Analysis:** Pyright (type checking) and Ruff (linting/formatting).
- **Frontend & TypeScript Tooling:** Single-page application built via the Rust-powered Vite Plus (`vp`), with all third-party libraries (CodeMirror, Mermaid.js, KaTeX) fully bundled into static assets (`dist/`). FastAPI mounts and serves `dist/` directly.
### Temporal Architecture & Lifecycle Coordination
1. **Platform Clocks & Linux Runtime Baseline:**
The backend relies on Linux kernel clock facilities exposed via Python's standard library:
- `time.monotonic_ns()` (`CLOCK_MONOTONIC`) for active assessment time. It is unaffected by discontinuous wall-clock steps (e.g. manual time changes, NTP steps), though subject to gradual frequency adjustments (NTP slewing). Crucially, it halts during kernel suspend (ACPI S3/sleep), automatically freezing the assessment budget when a laptop lid closes.
- `time.clock_gettime_ns(time.CLOCK_BOOTTIME)` (`CLOCK_BOOTTIME`) for the operational pause-grace keepalive timer. It advances during kernel suspend, ensuring that laptop sleep consumes the server keepalive window.
- Host boot identity is verified via `/proc/sys/kernel/random/boot_id` so that persisted boottime deadlines are never compared across system reboots.
- **BOOTTIME-Aware Pause-Grace Watchdog:** Because Python's `asyncio` loop timers wrap `CLOCK_MONOTONIC` and halt during system sleep, standard `asyncio.sleep()` cannot accurately expire a boottime grace period. The server re-evaluates the persisted `CLOCK_BOOTTIME` deadline at the first post-wake watchdog execution (e.g. when a suspend gap is detected or via a bounded periodic watchdog), terminating cleanly with `outcome: SUSPENDED` if the deadline expired during sleep.
2. **FastAPI Autonomous Watchdog, Immutable Time Limits & Serialized Admission:**
- **Immutable Attempt Budget (`time_limit_ns`):** The effective duration budget is immutable for each attempt, persisted in SQLite session state at attempt initialization and validated against the frozen questionnaire version. Recovery must never load altered CLI defaults or application configurations that silently mutate an existing attempt's time budget.
- **Autonomous Watchdog:** An `asyncio` background task monitors remaining active budget. When elapsed active time reaches the budget, it triggers the terminal transition to `TIMED_OUT` without waiting for client interaction.
- **Serialized Mutation Admission Rule:** Every response mutation endpoint (`POST /api/response/autosave`, `POST /api/response/submit`) independently validates the deadline while holding the SQLite write-serialization boundary (`BEGIN IMMEDIATE`). Monotonic time is sampled *after* acquiring the lock:
- $T_{\text{elapsed}} < T_{\text{limit}} \implies$ mutation accepted and checkpointed.
- $T_{\text{elapsed}} \ge T_{\text{limit}} \implies$ mutation rejected; endpoint atomically commits `TIMED_OUT` and `publication_intent`.
- A delay or stall in the background watchdog cannot allow late submissions to be accepted.
3. **Vite Plus Frontend Client Timing Behavior:**
- **Presentation Only:** The browser treats server state as authoritative. Countdown is a local display projection based on the latest server payload (`remaining_seconds`, `is_active`).
- **Background Tab Throttling Mitigation:** When the browser tab is hidden or backgrounded, local visual updates halt to avoid burning CPU cycles against throttled timers.
- **Visibility Lifecycle Listener:** The client attaches a listener to the Page Visibility API (`document.visibilityState === 'visible'`) and window focus/reconnect events. Upon re-entering visibility, it immediately issues `GET /api/session` to resynchronize the displayed countdown without continuous polling.
4. **Threat Model & Trust Boundary:**
The timing architecture is **server-authoritative relative to the browser**, guarding against client clock tampering, background timer throttling, network latency games, and wall-clock skew. Host-level root or user tampering (e.g., modifying SQLite directly or patching the Python binary) is explicitly outside the threat model of a local, formative personal assessment tool.
## Alternatives Considered
- **Go Backend:** Rejected. While offering single-binary compilation, it introduces cognitive overhead and unfamiliar web/routing paradigms for the primary maintainer, diverting energy from core pedagogical features.
- **Node/TypeScript Backend:** Rejected. TypeScript is not the preferred backend language for this environment, and running Node on the server side adds unnecessary runtime dependencies.
@@ -9,27 +9,93 @@ During an assessment, the application must withstand interruptions (unexpected p
## Decision
Use a temporary, local SQLite database (`~/.local/state/live-quiz/sessions/<attempt-id>.sqlite3`) strictly as an ACID-compliant **write-ahead session journal** during active execution:
1. **Three Separated Lifecycles:**
- *Server Process:* Ephemeral (runs on demand, exits on terminal state or explicit pause).
- *Server Process:* Ephemeral (runs on demand, exits on finalization or pause grace-period expiration).
- *Assessment Instance:* Persistent concept identified by stable IDs and immutable questionnaire version hashes.
- *Assessment Attempt:* Persistent run representing a single pass against an immutable assessment version.
2. **Transactional State Journaling:**
2. **Transactional State Journaling, Monotonic Time & Durable Checkpoints:**
- Every acknowledged answer submission, draft update, and timing event is committed immediately to SQLite.
- Pausing commits state and **terminates the server process cleanly**, eliminating zombie processes.
3. **Journal Destruction Invariant:**
- Upon reaching a terminal state (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`), the server publishes `attempt.json`.
- The temporary SQLite journal is deleted **only after durable export publication succeeds**.
4. **Explicit Recovery Command:**
- If a process is killed unexpectedly or paused, the journal remains on disk.
- Running `live-quiz recover --from-path <journal.sqlite3>` validates the journal, restores the authoritative clock, reloads drafts, and resumes the server under the exact same `attempt_id`.
- *Recovery Idempotency:* If recovery is invoked on a journal whose `attempt.json` was already successfully published, it verifies the export, cleans up the journal, and exits cleanly.
- **Active-Time & Duration Limit Representation:** Accumulated active time is tracked and persisted as an integer nanosecond scalar (`accumulated_active_ns`) alongside the immutable assessment budget (`time_limit_ns`) in the session state table. Nanoseconds are converted to seconds only for UI display and `attempt.json` export. `time_limit_ns` is established at attempt initialization from the frozen questionnaire version; recovery must never allow changed CLI options or configuration defaults to alter an active attempt's time limit.
- **In-Memory Anchor Advancement Invariant:**
$$\Delta t = t_{\text{monotonic now}} - t_{\text{last committed}}$$
$$\text{accumulated\_active\_ns}' = \text{accumulated\_active\_ns} + \Delta t$$
The in-memory anchor `last_committed_checkpoint_ns` advances strictly **after** the SQLite transaction commits successfully. If commit fails, the anchor does not advance.
- **Checkpoint Triggers:**
- Periodic target: approximately 1 second while `RUNNING`.
- Synchronous immediate accounting on: pause, autosave, submission, timeout, and early close. All timing updates share the serialized SQLite write boundary (`BEGIN IMMEDIATE`).
- **Durable Pause Checkpoint & In-Browser Resume:** Clicking **Pause** commits pending drafts, freezes active time, records `status = PAUSED` in SQLite, and displays an in-browser Resume control.
- **Configurable Pause Grace Period (Default: 2 Hours):** The local server stays running during a 2-hour window (`--pause-grace-period 2h`). Resuming within this window is instant in the browser without CLI/agent interaction.
- **Boot Identity, Grace Deadline & Post-Wake Evaluation:** Pause grace is measured using Linux `CLOCK_BOOTTIME` (which advances during system sleep). When pausing, the journal persists:
```json
{
"boot_id": "...",
"pause_started_boottime_ns": 123456789,
"pause_deadline_boottime_ns": 123456789
}
```
Because `asyncio` delayed callbacks wrap `CLOCK_MONOTONIC` and halt during system sleep, the pause-grace watchdog re-evaluates the persisted `CLOCK_BOOTTIME` deadline at the first post-wake watchdog execution (e.g. when a suspend gap is detected or via a bounded periodic check). If the deadline passed while asleep, it triggers clean shutdown with outcome `SUSPENDED`. Across a machine reboot, the original server process is dead, in-browser resume is unavailable, and the persisted boottime deadline is never compared against a differing boot ID; the journal remains intact for manual CLI recovery.
- If the 2-hour grace window expires without resumption, the server terminates cleanly with outcome `SUSPENDED`, retaining the journal with status `PAUSED`.
- **Audit Trail (`session_intervals`):** An append-only table records lifecycle intervals with a strictly monotonic sequence:
```sql
CREATE TABLE session_intervals (
event_sequence INTEGER PRIMARY KEY AUTOINCREMENT,
event_type TEXT NOT NULL, -- 'STARTED', 'PAUSED', 'RESUMED', 'SUSPEND_GAP_DETECTED', 'CRASH_RECOVERED'
wall_timestamp_utc TEXT NOT NULL,
accumulated_active_ns INTEGER NOT NULL
);
```
`event_sequence` guarantees interval ordering independent of NTP wall-clock slewing or discontinuous steps.
- **Suspend Gap Detection:** By periodically comparing clock deltas ($T_{\text{suspended}} \approx \Delta T_{\text{BOOTTIME}} - \Delta T_{\text{MONOTONIC}}$), the engine detects when the host was asleep without requiring D-Bus or `systemd-logind` hooks, logging a `SUSPEND_GAP_DETECTED` event upon wake while active time remains frozen.
3. **Assessment State Machine:**
```mermaid
stateDiagram-v2
[*] --> RUNNING: Attempt started
RUNNING --> PAUSED: Learner clicks Pause\n(Durable commit in SQLite)
PAUSED --> RUNNING: Learner clicks Resume\n(In-browser within 2h grace period)
RUNNING --> COMPLETED: Final question submitted
RUNNING --> CLOSED_EARLY: Learner explicitly closes early
RUNNING --> TIMED_OUT: Active duration budget exhausted
note right of PAUSED
Server stays alive for up to 2 hours.
If grace period expires, server exits cleanly,
retaining journal with status PAUSED.
Resume via: live-quiz recover --from-path <db>
end note
```
4. **Durability Invariants, Journal Schema Versioning & Dual Advisory Locking:**
- **Commit-Before-Ack:** The HTTP server commits transactions to SQLite *before* returning a successful `200 OK` acknowledgement to the client for any submission or autosaved draft.
- **Engine Configuration:** SQLite runs in Write-Ahead Logging mode (`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;`). `synchronous=FULL` ensures SQLite performs the required WAL synchronization after each transaction commit under documented filesystem/storage assumptions.
- **Independent Journal Schema Versioning:** SQLite journals declare an internal schema version (`schema_version`), evolved independently from external `attempt.json` schemas. Historical nonterminal journals are migrated directly to the current internal version via version-dispatched adapters (V1→Vcurrent).
- **Storage Location & Journal File Set:** Journals reside on persistent local storage (`~/.local/state/live-quiz/sessions/`), never in volatile tmpfs. The journal file set consists of `<attempt-id>.sqlite3`, `<attempt-id>.sqlite3-wal`, and `<attempt-id>.sqlite3-shm`.
- **Dual Advisory Lock Scope:** All publication and recovery operations synchronize using exclusive advisory lock files in `~/.local/state/live-quiz/locks/` (per-attempt lock `attempt-<attempt-id>.lock` and destination lock `dest-<sha256_dest>.lock`), which are never unlinked while held.
- **Crash Recovery Scope & Timing Guarantees:** Recovery guarantees restoration of all *acknowledged* state. Active time resumes from the last successfully committed active-time checkpoint (`accumulated_active_ns`); uncommitted elapsed time is not guaranteed to be preserved under sudden termination, as the ~1-second interval is an operational target subject to system load. Process downtime while dead is excluded from the active budget and starts a fresh monotonic segment.
- **Overdue Recovery Guard:** If nonterminal recovery (`live-quiz recover`) inspects a journal where `accumulated_active_ns >= time_limit_ns`, the engine immediately terminalizes the attempt as `TIMED_OUT` and initiates atomic export before any interactive resume is permitted.
- **Clock Nuances & Platform Baseline:** Evaluated against Linux `CLOCK_MONOTONIC`. Immune to discontinuous wall-clock adjustments (manual time changes, NTP steps), though subject to NTP frequency slewing. Halts during system suspend.
5. **Atomic Terminal Commitment & Safe Ordered Destruction:**
- **Atomic Terminal Transaction & Path Distinction:** The SQLite write boundary is established before final snapshot extraction via `BEGIN IMMEDIATE`:
- *Path A (Final Submission → `COMPLETED`):* The response mutation to `SUBMITTED`, transition to `COMPLETED`, complete response snapshot, and `publication_intent` (`target_schema_version`, `export_projection_version: "1"`, `canonicalization_version: "1"`, `destination_path`, `expected_sha256`) are committed in one single atomic transaction. The final response is never acknowledged without atomically committing completion.
- *Path B (Timeout / Early Close):* The transaction lock is established before extracting the snapshot (capturing current drafts and unanswered questions) and committing `TIMED_OUT` or `CLOSED_EARLY` alongside `publication_intent`.
- **Safe Ordered Deletion:** The journal is destroyed only after publication durability (including directory `fsync`) is established: through an open writable connection execute verified WAL checkpoint (`PRAGMA wal_checkpoint(TRUNCATE);`) → close all database connections cleanly → verify companion removal (unlinking `-wal` and `-shm` explicitly if present) → unlink primary `.sqlite3` **last**.
- If cleanup fails after durable export, `live-quiz` exits with `CLEANUP_PENDING` (code 6), preserving `.sqlite3` for cleanup retry.
6. **Recovery Paths & Hash-Verified Idempotency:**
- **Nonterminal Recovery:** In-place transactional migration to current internal schema; live assessment resumed.
- **Terminal Export Recovery:** Decouples Phase 1 read-only extraction from Phase 2 post-verification writable cleanup:
- *Phase 1 (Read-Only):* Uses read-only connection (`mode=ro`) to read existing WAL frames without mutating database tables or schema; reconstructs export using `export_projection_version` and verifies against persisted `expected_sha256`. Legacy journals lacking `publication_intent` are rejected as unsupported (`UNSUPPORTED_SCHEMA_VERSION`, exit 5). Phase 1 read-only connection is closed cleanly before Phase 2.
- *Idempotency Verification:* Compares existing destination artifacts against persisted `expected_sha256`. Matching hash triggers Phase 2 cleanup; mismatch triggers an integrity conflict (exit 3); different `attempt_id` triggers artifact conflict (exit 2).
- *Phase 2 (Writable Cleanup):* Opened only after Phase 1 connection is closed and durable publication is established; executes verified WAL checkpoint without schema or table modifications, closes connection, and unlinks companions then `.sqlite3` last.
- **Orphan Anomaly Rule:** Orphaned `-wal` or `-shm` files without `.sqlite3` represent an unexpected anomaly; recovery halts safely and reports an integrity error without deleting files.
## Alternatives Considered
- **Permanent SQLite LMS Database:** Rejected. Burdening `live-quiz` with multi-workspace relational history, cross-project analytics, and long-term migrations creates severe scope creep. `live-quiz` is an assessment execution harness, not a full Learning Management System.
- **Flat-File JSON Appending:** Rejected. Subject to partial-write corruption during sudden process kills (`SIGKILL`) or power failures.
## Consequences
- **Positive:** Guarantees zero data loss for acknowledged submissions and drafts under crashes; allows pausing without running background processes; leaves zero state accumulation upon clean completion.
- **Negative / Trade-offs:** Requires an explicit recovery command (`live-quiz recover`) and managing temporary journal files in the XDG state directory.
- **Positive:** Guarantees reliable recovery of all acknowledged submissions and drafts across process termination (`SIGKILL`, application crash) under documented WAL mode assumptions; provides server-authoritative timing relative to the browser; prevents active-time budget leakage during crash downtime or host system suspension; allows in-browser pause without indefinite background processes; leaves zero state accumulation upon clean completion.
- **Negative / Trade-offs:** Requires an explicit recovery command (`live-quiz recover`) and managing temporary journal files (`.sqlite3`, `-wal`, `-shm`) in the XDG state directory; does not protect against unacknowledged client-side keystrokes that never completed an HTTP transaction; relies on Linux-specific clock interfaces (`CLOCK_BOOTTIME`). Host root/user manipulation is outside the formative assessment threat model.
## Related Decisions
- [ADR-0002: Harness-Agnostic Process Lifecycle](./0002-harness-agnostic-process-lifecycle.md)
@@ -8,16 +8,28 @@ When `live-quiz` concludes, it must hand off the assessment evidence to caller w
## Decision
Establish **`attempt.json` as a standardized, versioned JSON contract** published via an atomic file-replacement pattern:
1. **Atomic Publication Pipeline:**
- The final attempt data is serialized to JSON conforming to `attempt.schema.json`.
- Written to a temporary file (`.attempt.json.tmp`) within the target directory.
- Validated for structural correctness and flushed/fsynced to persistent storage.
- Atomically renamed to the final destination path (`attempt.json`).
- *Failure Guarantee:* If publication fails at any stage (e.g. disk full, permissions error), the temporary SQLite journal is retained, and the process exits with an error status.
2. **Reattempt vs. Recovery Semantics:**
- **Recovery (`live-quiz recover`):** Resumes an interrupted attempt, preserving the existing `attempt_id` and journal state.
1. **Ten-Step Atomic Publication Pipeline & Directory Durability:**
Publication follows a strict 10-step sequence protected by dual advisory locks (per-attempt lock `attempt-<attempt-id>.lock` and destination lock `dest-<sha256_dest>.lock`):
- Acquire exclusive advisory locks (never unlinked while held).
- Establish write-serialization boundary via `BEGIN IMMEDIATE`:
- *Path A (Final Submission → `COMPLETED`):* The response mutation to `SUBMITTED`, transition to `COMPLETED`, complete response snapshot, and `publication_intent` (`target_schema_version`, `export_projection_version: "1"`, `canonicalization_version: "1"`, `destination_path`, `expected_sha256`) are committed together in one atomic transaction.
- *Path B (Timeout / Early Close):* The transaction is established before reading the final response snapshot and committing terminal status (`TIMED_OUT`/`CLOSED_EARLY`) and `publication_intent`.
- Validate structurally and serialize canonical payload conforming to RFC 8785 Canonical JSON, computing `expected_sha256` prior to `COMMIT;`.
- Destination conflict check: under destination lock, verify destination does not hold a different `attempt_id` (prohibiting overwriting another attempt's artifact).
- Write canonical bytes to attempt-specific temporary file `.attempt.<attempt-id>.tmp` in destination directory, flush, and `fsync` file descriptor.
- Atomically link/rename `.attempt.<attempt-id>.tmp` to `attempt.json` (using atomic no-replace semantics e.g. `renameat2(..., RENAME_NOREPLACE)`).
- `fsync` the parent directory descriptor to guarantee rename durability across power failure.
- Verified WAL checkpoint through open writable connection (`PRAGMA wal_checkpoint(TRUNCATE);`).
- Clean close & ordered journal cleanup: close handles cleanly → unlink `-wal` → unlink `-shm` → unlink primary `.sqlite3` **last**.
- Emit machine-readable outcome on stdout and exit 0 (`SUCCESS_FINALIZED`).
2. **Reattempt vs. Recovery Semantics & Idempotency Verification:**
- **Reattempt (`live-quiz start`):** Launches a fresh execution against the *same* immutable assessment definition, generating a distinct new `attempt_id`.
3. **Contract Attributes:**
- **Nonterminal Recovery (`live-quiz recover`):** In-place transactional migration; resumes interrupted or paused live assessment under the existing `attempt_id`.
- **Terminal Export Recovery (`live-quiz recover`):**
- *Phase 1 (Read-Only):* Opens SQLite with read-only connection (`mode=ro`), reading existing WAL frames without mutating tables or schema; reconstructs export using `export_projection_version` and validates reconstructed hash against persisted `expected_sha256` (failing closed with exit 3 on mismatch). Legacy journals lacking `publication_intent` are explicitly rejected as unsupported (`UNSUPPORTED_SCHEMA_VERSION`, exit 5). Phase 1 read-only connection is closed cleanly before Phase 2.
- *Idempotency Verification:* If target exists and matches `attempt_id` and `expected_sha256`, advances directly to Phase 2 cleanup. If different `attempt_id`, exits code 2; if hash mismatch, exits code 3.
- *Phase 2 (Writable Cleanup):* Opened only after Phase 1 connection is closed and publication durability is established; executes verified WAL checkpoint without schema modifications, closes handles, and unlinks companions then `.sqlite3` last.
3. **Contract Attributes & Canonical Objective Traceability:**
Every exported attempt contains explicit provenance:
- `schema_version`
- `attempt_id`
@@ -25,7 +37,43 @@ Establish **`attempt.json` as a standardized, versioned JSON contract** publishe
- `workspace` locator
- `status` (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`)
- `timing` (active duration seconds, wall-clock duration seconds, pause intervals)
- `responses` array
- `responses` array preserving mappings to associated canonical objective references carried in the questionnaire.
*Structural vs. Semantic Validation Invariant:*
The exported payload must conform structurally to the versioned attempt schema contract (`attempt.schema.json`). However, the engine maintains zero semantic awareness of external registries: it does not validate, resolve, or query objective identifiers against external catalogs, preserving them verbatim for downstream evaluation. The exact schema layout for preserving question-to-objective response traceability remains open until the JSON schema contracts are formally authored.
4. **Response State Triad & Attainment Decoupling:**
Each item in `responses[]` represents its interaction state independently of the assessment lifecycle status (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`):
- `SUBMITTED`: Explicitly confirmed by the learner. Includes explicit blank submissions where the learner intentionally submitted an empty response.
- `DRAFT`: Autosaved input acknowledged by SQLite commit-before-ack but unsubmitted when session terminated. Represents an acknowledged learner-generated modification (initial empty fields remain `UNANSWERED`). The latest acknowledged draft payload and server-side receipt timestamp are preserved verbatim. (Per-question active duration is designated provisional pending formal measurement definitions).
- `UNANSWERED`: Zero acknowledged learner input recorded (payload is `null`).
*Valid Terminal/Response State Constraints:*
- `COMPLETED`: Strictly requires every questionnaire item to have `response_status: SUBMITTED` (explicit blank submissions qualify).
- `CLOSED_EARLY`: At least one response must be `DRAFT` or `UNANSWERED`, following an explicit learner termination action.
- `TIMED_OUT`: At least one response must be `DRAFT` or `UNANSWERED`, following authoritative timer expiration.
*Generalized Server-Side Serialization & Absorbing Terminal States:*
All response mutations (draft autosaves, explicit submissions) and terminal lifecycle transitions (`COMPLETED`, `CLOSED_EARLY`, `TIMED_OUT`) are serialized server-side within SQLite transactions. The final required response submission and transition to `COMPLETED` must be committed atomically. Once any terminal lifecycle transition commits, its status is strictly immutable and absorbing: all subsequent response mutations and competing terminal transition attempts are rejected.
*Attainment vs. Submission Independence:*
Submission status describes the user interaction, not the correctness or cognitive quality of the content. `quiz-evaluator` enforces evidence-first principles across the response triad:
- Explicit Blank `SUBMITTED`: Evaluated as an intentional empty response against rubric criteria.
- `DRAFT`: Evaluated as available evidence of learning without automatic penalty for draft status, disclosing draft provenance and reporting demonstrated vs. unestablished criteria.
- `UNANSWERED`: Reports that no response evidence exists; must not infer misconceptions or conclude that the learner lacks underlying knowledge solely due to absence of recorded input.
5. **Structured Process Outcomes & Exit Codes:**
Operational failures are strictly decoupled from assessment lifecycle outcomes. Standard output emits a single-line JSON result packet (`{"outcome": "...", "attempt_id": "...", ...}`), while standard error carries human-readable logs:
| Exit Code | Symbolic Name | Meaning | Journal Action |
| :---: | :--- | :--- | :--- |
| **`0`** | `SUCCESS_FINALIZED` | Export verified, directory synced, journal unlinked. | Deleted |
| **`0`** | `SUCCESS_SUSPENDED` | Pause grace period expired cleanly; resume available. | Preserved |
| **`1`** | `EXPORT_IO_ERROR` | Transient disk/write/sync failure during publication. | Preserved |
| **`2`** | `CONFLICT_DIFFERENT_ATTEMPT` | Destination occupied by a different `attempt_id`. | Preserved |
| **`3`** | `CONFLICT_INTEGRITY_MISMATCH` | Destination has matching ID but differing SHA-256 hash. | Preserved |
| **`4`** | `RECOVERY_CONCURRENCY_LOCKED` | Another process holds the advisory recovery lock. | Preserved |
| **`5`** | `UNSUPPORTED_SCHEMA_VERSION` | Journal or export schema version unsupported. | Preserved |
| **`6`** | `CLEANUP_PENDING` | Export durable and verified, but journal removal failed. | Preserved for retry |
## Alternatives Considered
- **Direct SQLite Database Querying by Evaluators / Future LMS:** Rejected. Exposing internal database tables couples external consumers to `live-quiz` schema migrations.
@@ -11,11 +11,11 @@ Provide an MVP collection of five modular, portable reference skills in the repo
| Skill | Role | Primary Input | Primary Output |
| :--- | :--- | :--- | :--- |
| **`learning-objectives`** | Formulates observable, assessable competencies from learning goals. | Topic / Goals / Context | Objectives & evidence criteria |
| **`quiz-designer`** | Compiles an approved Assessment Brief into public and private contracts. | Assessment Brief | `questionnaire.json`, `rubric.json` |
| **`live-quiz`** | Operational CLI wrapper executing and recovering assessments. | Questionnaire path, CLI flags | Browser session URL, `attempt.json` |
| **`quiz-evaluator`** | Context-isolated post-hoc evaluation of attempt against rubric. | `rubric.json`, `attempt.json` | `evaluation.json` |
| **`tutor`** | Orchestrates learning dialogue, proposes scope, and leads debrief. | Learner interaction | Consolidated learning experience |
| **`learning-objectives`** | Formulates observable, assessable competencies; searches external catalog to propose new records and relationships. | Topic / Goals / Context, Registry candidates | Proposed objectives & evidence criteria |
| **`quiz-designer`** | Compiles an approved Assessment Brief into public and private contracts; uses learning history to inform context and difficulty. | Assessment Brief, Learner history | `questionnaire.json`, `rubric.json` |
| **`live-quiz`** | Operational CLI wrapper executing and recovering assessments; structurally preserves canonical objective references. | Questionnaire path, CLI flags | Browser session URL, `attempt.json` |
| **`quiz-evaluator`** | Context-isolated post-hoc evaluation of attempt against rubric; evaluates submitted answers and drafts as learning evidence without automatic penalty; deterministically correlates evidence. | `rubric.json`, `attempt.json` | `evaluation.json` |
| **`tutor`** | Orchestrates learning dialogue, proposes scope, logs contextual observations against stable objective IDs, and leads debrief. | Learner interaction, Registry/History | Consolidated learning experience, Contextual observations |
### Architectural Invariants:
1. **Independent Usability:**
@@ -27,10 +27,15 @@ Provide an MVP collection of five modular, portable reference skills in the repo
2. **Harness Portability:**
- The reference skills operate as standard portable markdown instructions.
- They do not mandate Antigravity-specific subagent APIs (`invoke_subagent`). In single-agent environments (e.g. Claude Code, Cursor), they execute sequentially in the active agent context.
3. **Objective Modeling & Scoping:**
- Objectives are maintained as flat collections with directed `enables` relationships (a graph, not a nested tree).
- Coverage is tracked as cumulative observations (`INTRODUCED`, `EXPLORED`, `PRACTICED`) alongside an active disposition (`ACTIVE` vs. `DEFERRED`).
- Assessment readiness is evaluated contextually when the Tutor compiles the **Assessment Brief**, rather than as an intrinsic boolean flag in the ledger.
- Skills do not hardcode host filesystem layouts or private paths.
3. **Objective Modeling, Learning History & Scoping (Provisional Pedagogical Model):**
- **Persistent Catalog vs. In-Context Ledger:** Objectives and competencies are resolved against an external catalog with many-to-many relationships (avoiding rigid parent-child hierarchies or assumed prerequisite DAGs). `learning-objectives` proposes new records; canonical identity is established by the registry.
- **Contextual History vs. Single State:** Learner engagement is logged as longitudinal observations (e.g. `INTRODUCED`, `EXPLORED`, `PRACTICED` as provisional examples) associated with stable objective IDs. Repeated encounters are preserved rather than overwritten. Deferral (`ACTIVE` vs. `DEFERRED`) is an independent pedagogical disposition that does not erase past history.
- **Exposure vs. Mastery:** Prior exposure informs assessment design to avoid redundant introductory testing, but exposure is never equated to mastery. Difficulty calibration accounts for familiarity, task complexity, context novelty, assistance level, and demonstrated independent performance.
- **Scoping Gate:** Assessment readiness is evaluated contextually when the Tutor compiles the **Assessment Brief**, rather than as an intrinsic boolean flag in the catalog.
- **Deterministic Evaluation Correlation:** Evaluation evidence is correlated deterministically to canonical objective references using explicit mappings across rubric criteria and attempt responses, eliminating ambiguous natural-language guessing.
- **Evidence-First Evaluation Across Response States:** The evaluator evaluates available work in `DRAFT` responses (e.g. partial derivations, code approaches) against the rubric without penalizing draft status. It discloses draft provenance, distinguishes demonstrated criteria from unestablished criteria, and does not speculate on unwritten thoughts. For `UNANSWERED` questions, it reports that no response evidence exists without inferring misconceptions or concluding that the learner lacks underlying knowledge solely from missing input.
- **Abstract Capability Dependency:** Reference skills depend on an abstract registry and history capability (e.g. via CLI, local HTTP, or file protocols) rather than hardcoding specific storage implementations or database technologies. Detailed registry architecture, sync strategies, and exact schema mappings remain open design questions.
## Alternatives Considered
- **Single Monolithic "Mega-Prompt" Skill:** Rejected. Makes it impossible to customize or substitute individual stages (e.g. using a different evaluator or authoring tool).
+350
View File
@@ -0,0 +1,350 @@
# Issue #4 Authoritative Decision Ledger
**Project:** `live-quiz`
**Scope:** Authoritative provenance record, settled architectural baseline, accepted `B2` decisions, Stage 1 architectural decisions (`S1-01`–`S1-17`, `USER_EXPLICIT`), deferred implementation boundaries (`DEF-01`–`DEF-05`), and maintenance protocol for Original Issue #4.
**Repository Baseline:** `main` @ `a4eeccf` ([docs/architecture.md](../docs/architecture.md), [docs/decisions/0001`–`0009](../docs/decisions/README.md)).
**Companion Artifact:** [issue-4-follow-through.md](issue-4-follow-through.md) (authoritative for execution order, dependencies, and work status).
---
## Section 0 — Authority and Provenance Rules
This ledger governs **decision state and provenance** for Issue #4, while [issue-4-follow-through.md](issue-4-follow-through.md) governs **remaining work, sequencing, and completion conditions**. Together they provide a self-contained handoff baseline without requiring prior chat history.
### 0.1 Four Provenance Categories
1. **Explicitly Accepted User Decisions (`USER_EXPLICIT`):**
- Commitments explicitly approved or stipulated by the user in direct `USER_INPUT` turns (verified in `transcript_full.jsonl` at steps `820`, `825`, `827`, `829`, `845`, `847`, and `849`).
- **Rule:** Explicit user input is the sole source of decision authority. These commitments are locked and must not be re-opened unless the user explicitly asks to revise them.
2. **Previously Established Architectural Invariants:**
- The committed repository architecture on `main` @ `a4eeccf` ([docs/architecture.md](../docs/architecture.md) and [ADR-0001](../docs/decisions/0001-standalone-web-application.md) through [ADR-0009](../docs/decisions/0009-modular-portable-reference-skills.md), resolving Issues #1–#3 and #5–#8) together with the foundational Issue #4 handoff baseline (`steps 820–827`, recorded in Section 1 below).
- **Rule:** Downstream decisions must respect these invariants. Accepting a high-level architectural direction does **not** implicitly approve unreviewed sub-mechanisms or implementation details attached to it later.
3. **Originating Assistant Recommendations (`UNAPPROVED_RECOMMENDATION — step 850`, now resolved):**
- In `step 850` of the discovery transcript, a single assistant turn simulated synthetic user prompts and emitted a premature "Stage 1 Decision Closure Report" marking items `B2.4.1` through `E2` as `Accepted`.
- **Rule & Closure State:** A recommendation marked `Accepted` in that earlier assistant-generated closure report was **not** an approved decision. Each of the 17 atomic items (`S1-01`–`S1-17`, recorded in Section 3 below) was subsequently reviewed one-by-one and resolved with `USER_EXPLICIT` provenance on `2026-11-15` (`2` `ACCEPTED_AS_PROPOSED`, `15` `ACCEPTED_WITH_MODIFICATIONS`; zero `PENDING_USER_REVIEW` items remain).
4. **Deferred Implementation Decisions (`DEF-01`–`DEF-05`):**
- Concrete engineering specifications (exact JSON field names, library selection, CLI flag spellings, wire framing, systemd unit parameters, backup retention numbers) intentionally postponed until after Stage 3 acceptance criteria (`S3-01`).
- **Rule:** Deferred is not equivalent to decided. An architectural invariant can be accepted while its implementation mechanism remains open; deferred details must not be prematurely written into ADRs as settled architectural commitments.
---
## Section 1 — Settled Architectural Baseline
The following nine foundational commitments (`BL-01`–`BL-09`) are verified in `steps 820, 825, 827` (`USER_EXPLICIT`). Important qualifications are preserved so accepted principles are not broadened into commitments the user did not make.
| Baseline ID | Established Invariant & Scope | Rationale | Preserved Qualifications & Open Boundaries | Target ADR / Doc Destinations |
| :--- | :--- | :--- | :--- | :--- |
| **`BL-01`**<br>*(Cluster A)* | **Immutable Coordinated Assessment Pair & Flat `assessment_id`:**<br>An assessment definition is an immutable coordinated pair $A = (Q, R)$ (`questionnaire.json` + `rubric.json`) identified by a flat opaque `assessment_id` allocated by `learningctl`; modification of either member of the coordinated assessment pair requires registering a new `assessment_id`. Competency $\leftrightarrow$ Objective and Assessment $\leftrightarrow$ Objective relationships are M:N (Competency $\leftrightarrow$ Assessment is derived, never direct). The Tutor owns pedagogical reassessment decisions, performs an `AVAILABLE` artifact pre-flight check before offering reassessment, and requires explicit learner consent before registering a new assessment or starting a reassessment. | Prevents silent drift between questions and grading criteria, decouples assessment identity from curriculum taxonomy edits, and keeps pedagogical judgment in the Tutor rather than the quiz engine. | How mechanical schema up-converters (`clone-upgrade`) are restricted when contract versions change remains open under `S1-05` (`B2.4.5`). | [ADR-0004](../docs/decisions/0004-questionnaire-rubric-separation.md), [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md), [ADR-0009](../docs/decisions/0009-modular-portable-reference-skills.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
| **`BL-02`**<br>*(Cluster A)* | **No `assessment_version` or Version Lineage:**<br>`assessment_version`, revision chains, and parent/child lineage metadata are eliminated across all contracts. Modification of either member ($Q$ or $R$) requires registering a new `assessment_id` without exception. Longitudinal learner progress across assessments is tracked exclusively through shared `learning_objective_id` links. | Avoids version-graph complexity and invalid longitudinal comparisons across mutated assessments while preserving objective-level progress tracking. | Legacy `attempt.json` (`assessment_version`) schema rejection policy is tracked separately under `S1-08` (`C2`). | [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md), [ADR-0009](../docs/decisions/0009-modular-portable-reference-skills.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
| **`BL-03`**<br>*(Cluster B1)* | **`B1` Identity Binding & Hash Domain:**<br>Registered $Q$ and $R$ both embed `assessment_id`. $R$ embeds `expected_questionnaire_hash` ($H_q$). $H_q = \operatorname{SHA256}(\operatorname{JCS}(Q))$ is calculated over the complete validated public `questionnaire.json` (including `assessment_id` when present). `attempt.json` embeds `questionnaire_hash` ($H_q$) for assessment-definition identity. Separately, [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md) defines `expected_sha256` as a per-file integrity checksum stored in the SQLite journal's `publication_intent`, used to verify canonical export bytes during publication and recovery. Standalone execution (`live-quiz start --questionnaire <path>`) is supported without `assessment_id` or `workspace_id`. | Cryptographically binds $R \to Q$ and `attempt.json` $\to Q$ without exposing $R$ to `live-quiz` ([ADR-0004](../docs/decisions/0004-questionnaire-rubric-separation.md)), while preserving standalone CLI usability ([ADR-0001](../docs/decisions/0001-standalone-web-application.md)). | Component-level hash calculation/verification authority (`S1-06` / `B2.5.1`) and canonical byte storage (`S1-07` / `B2.5.2`) remain open. | [ADR-0004](../docs/decisions/0004-questionnaire-rubric-separation.md), [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
| **`BL-04`**<br>*(Cluster C1)* | **`C1` Self-Contained Journal Snapshot & Recovery Independence:**<br>Before serving any learner-facing HTTP route, `live-quiz` durably commits a complete, self-contained questionnaire snapshot and initial execution metadata (`attempt_id`, optional `assessment_id`, $H_q$, optional `workspace_id`, `time_limit_ns`) to the per-attempt SQLite journal. `live-quiz recover` reconstructs the session strictly from the journal snapshot without reading external questionnaire files or querying the Learning Registry. | Guarantees crash/restart self-sufficiency even after temporary materialized questionnaires are deleted or workspace files move. | Exact persisted snapshot format (`S1-07` / `B2.5.2`) and the startup readiness acknowledgment contract (`S1-12` / `D2b`) remain open. | [ADR-0006](../docs/decisions/0006-ephemeral-sqlite-session-journal.md), [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md), [docs/architecture.md](../docs/architecture.md) |
| **`BL-05`**<br>*(Cluster C2 partial)* | **Explicitly Accepted Portion of `C2` — No Historical Journal Migration:**<br>No backward-compatibility migration or fallback reconstruction path is needed for historical attempt journals lacking embedded questionnaire snapshots, because no prior deployment exists. | Eliminates dead migration complexity in a greenfield pre-implementation repository. | **Qualification:** Only journal migration is settled here. Legacy `attempt.json` (`assessment_version`) handling remains open under `S1-08` (`C2`). | [ADR-0006](../docs/decisions/0006-ephemeral-sqlite-session-journal.md), [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md) |
| **`BL-06`**<br>*(Cluster D baseline)* | **Foundational Learning Registry, Workspace, Encryption, Provisioning & Service-Boundary Invariants:**<br>• One OS-wide persistent encrypted Learning Registry serves all workspaces on the host.<br>• Workspaces are logical provenance resolved via nearest-ancestor `.learning-workspace` marker (`workspace_id`), explicitly rejecting Git root as workspace boundary.<br>• Host provisioning is separate from `learningctl init` (`init` registers a workspace and never silently recreates a missing global DB).<br>• Agents/skills invoke only `learningctl` (narrow domain CLI; black-box `learningctl.md`/`--help` contract) $\to$ private typed UDS IPC $\to$ `learning-registryd` (`learning-registry` OS user, systemd socket activation `Accept=no`, serialized mutations).<br>• Non-TPM default host key protection stored outside workspaces and separate from DB backups; `learning-registryd` owns Online Backup API encrypted-to-encrypted snapshots on schedule and before disruptive operations.<br>• `learningctl --json` responses carry per-command `schema_version` with additive/breaking compatibility semantics. | Preserves cross-topic learner state across directories, isolates secrets (`rubric.json`) and DB credentials from workspace files and agent shells, and prevents concurrent agent races against the encrypted registry. | **Qualifications:**<br>• `SQLCipher` remains a **candidate**, not a selected implementation.<br>• Exact `"<major>.<minor>"` CLI `schema_version` string syntax remains unverified (`S1-14` / `D3b`, flagged open at `step 827`).<br>• Repo ownership (`S1-09` / `D1a`), marker/error taxonomy (`S1-10` / `D1b`), service delegation cutoff (`S1-14` / `D3b`), and key escrow / backup verification (`S1-15` / `D4`) remain open. | [ADR-0008](../docs/decisions/0008-two-product-repository-architecture.md), [ADR-0009](../docs/decisions/0009-modular-portable-reference-skills.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
| **`BL-07`**<br>*(Cluster D baseline)* | **Foundational Registration & Temporary Questionnaire Handoff Rules:**<br>Registration uses a two-phase lifecycle (`REGISTERING` $\to$ `AVAILABLE` / `ABORTED`). Only `AVAILABLE` definitions are discoverable for execution/reassessment; allocated `assessment_id`s are never reused; registration failures are strictly distinct from attempt crash recovery. For managed runs, `learningctl` materializes a temporary public-only `questionnaire.json` outside the workspace and deletes it idempotently after `live-quiz` commits its durable journal snapshot. | Prevents half-registered pairs from being executed, keeps `rubric.json` inside the registry service boundary, and avoids leaving stale questionnaire files in learner workspaces. | `REGISTERING` status visibility and `ABORTED` tombstone retention (`S1-11` / `D2a`) and the startup-commit acknowledgment protocol (`S1-12` / `D2b`) remain open. | [ADR-0004](../docs/decisions/0004-questionnaire-rubric-separation.md), [ADR-0006](../docs/decisions/0006-ephemeral-sqlite-session-journal.md), [ADR-0009](../docs/decisions/0009-modular-portable-reference-skills.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
| **`BL-08`**<br>*(Cluster D baseline)* | **Foundational Status-Discovery & Attempt-State Authority:**<br>`learningctl status` (`--json`, `--all`) is a read-only command run once at Tutor initialization (no polling loops). `learningctl` discovers candidate attempt journals, while `live-quiz` is the sole authority for active vs. recoverable attempt state without exposing private engine SQLite tables. | Gives the Tutor a single deterministic session-start snapshot while respecting the engine's private persistence encapsulation ([ADR-0006](../docs/decisions/0006-ephemeral-sqlite-session-journal.md)). | The exact read-only active-vs.-recoverable inspection interface between `learningctl` and `live-quiz` remains open under `S1-13` (`D3a`). | [ADR-0006](../docs/decisions/0006-ephemeral-sqlite-session-journal.md), [ADR-0009](../docs/decisions/0009-modular-portable-reference-skills.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
| **`BL-09`**<br>*(Cluster E baseline)* | **Foundational Interaction Lifecycle, Reversible Abandonment, Debrief Guideline & Atomic Consolidation:**<br>• In managed workflows, `attempt.json` is staged in a persistent non-workspace staging area (no TTL expiry) until `(attempt, evaluation, Tutor observations)` are committed in one atomic registry transaction (`CONSOLIDATED`) with an idempotent receipt. Standalone `attempt.json` files remain untouched user exports.<br>• States include `PENDING_DEBRIEF`, `DEFERRED`, `PENDING_CONSOLIDATION`, `CONSOLIDATED`, and `ABANDONED`.<br>• Abandonment separates **append-only historical events** from **reversible current disposition** (`ABANDONED` is hidden from default `status` and `--all`, and transitions to `DEFERRED` or a new attempt only on explicit learner request).<br>• Bounded debrief (1 consolidated report + ~1–3 follow-up turns) is a **facilitation guideline**, not a hard technical cutoff; interrupted debriefs store lightweight structured progress, never full chat transcripts. | Prevents partial/un-debriefed quiz exports from polluting canonical mastery records while preserving crash-safe staging, learner agency over abandoned attempts, and transcript-free privacy. | **Qualifications:**<br>• Bounded debrief duration is a pedagogical facilitation guideline, not an enforced turn limit.<br>• Per-execution staging slot allocation (`S1-16` / `E1`) and pre-consolidation registry/staging split, pre-debrief discovery, checkpoint storage & `ABANDONED` payload retention (`S1-17` / `E2`) remain open. | [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md), [ADR-0009](../docs/decisions/0009-modular-portable-reference-skills.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
---
## Section 2 — Explicitly Accepted `B2` Decisions (`B2.1`–`B2.3` & `B2.4` Framing Constraints)
### 2.1 Accepted `B2.1`–`B2.3` Subdecisions
| Decision ID & Provenance | Accepted Decision Statement | Rationale | Principal Architectural Consequences | Target ADR / Doc Destinations |
| :--- | :--- | :--- | :--- | :--- |
| **`B2.1`**<br>`ACCEPTED`<br>*(`USER_EXPLICIT`, step `829`)* | **Hash Original Parsed JSON After Strict Validation:**<br>`questionnaire_hash` ($H_q$) is computed over the original parsed JSON data structure after strict validation (`extra="forbid"`, `strict=True`) succeeds, serialized through RFC 8785 JCS. Pydantic's normalized model output (`model_dump()` / `model_dump_json()`) is never used as the hash input. | Decouples the cryptographic identity of an assessment from internal Python/Pydantic model refactoring, field ordering, or default-injection behavior. | • Validators must preserve the raw parsed JSON tree (Layer 1 output) alongside or prior to constructing domain models.<br>• Default semantics and contract evolution are governed independently under `B2.4` (`S1-01`–`S1-05`). | [ADR-0004](../docs/decisions/0004-questionnaire-rubric-separation.md), [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
| **`B2.2`**<br>`ACCEPTED`<br>*(`USER_EXPLICIT`, step `845`)* | **Project-Specific Strict RFC 8785-Compatible Input Profile (Scoped to `questionnaire.json`):**<br>`questionnaire.json` must satisfy a strict project-specific JCS-compatible input profile at the parsing boundary:<br>1. Valid UTF-8 without BOM; reject unpaired UTF-16 surrogates and Unicode noncharacters; **no Unicode normalization** (such as NFC or NFD) is performed, and decoded code points are preserved exactly (NFC- or NFD-normalized input is accepted as-is without rejection or re-normalization).<br>2. Reject duplicate object keys after string unescaping (`object_pairs_hook`).<br>3. Reject `NaN`, `Infinity`, and `-Infinity` (`parse_constant`).<br>4. Domain restriction: reject all floating-point and exponential lexical tokens (`parse_float`, rejecting `600.0`, `1e0`, `1e400`) and enforce exact integers within $[-(2^{53}-1), +(2^{53}-1)]$ (`parse_int`).<br>5. Scope restriction: the integer-only restriction applies strictly to `questionnaire.json` and is **not** automatically transferred to `attempt.json` or `evaluation.json`. | Eliminates parser-level ambiguity (duplicate keys, float overflow, surrogate edge cases) before canonicalization, preserves exact authored Unicode code points without distorting inputs, and uses an integer-only domain rule where all questionnaire numeric quantities (timers, limits, counts) are naturally discrete. | • Both `live-quiz` and the registry must enforce identical Layer 1 parser hooks on `questionnaire.json`.<br>• `attempt.json` and `evaluation.json` remain free to use finite floats/integers as appropriate to scoring and telemetry.<br>• Shared negative test vectors (`DEF-02`) must cover rejected tokens (`600.0`, `1e0`, `1e400`, duplicate keys, lone surrogates, noncharacters) and positive preservation of NFC/NFD inputs without normalization. | [ADR-0004](../docs/decisions/0004-questionnaire-rubric-separation.md), [ADR-0005](../docs/decisions/0005-python-fastapi-vite-stack.md), [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
| **`B2.3`**<br>`ACCEPTED`<br>*(`USER_EXPLICIT`, step `847`)* | **Three-Layer Parsing / Canonicalization / Digest Model with Independent Implementations & Shared CI Conformance Suite:**<br>1. Explicitly separate **Layer 1** (strict JSON parser + `B2.2` input profile), **Layer 2** (full RFC 8785 JCS canonicalizer operating on Layer 1 output to emit deterministic UTF-8 bytes), and **Layer 3** (`SHA-256` lowercase hex digest).<br>2. Keep `live-quiz` and the Learning Registry independently implemented (no shared first-party runtime helper package), with each component using an established, standards-compliant full RFC 8785 library (never a hand-written canonicalizer or a stripped-down integer-only JCS subset).<br>3. Enforce cross-component determinism via a **mandatory shared raw-byte CI conformance test suite**. | Preserves the clean product boundary ([ADR-0008](../docs/decisions/0008-two-product-repository-architecture.md)), avoids custom canonicalizer bugs, and guarantees byte-for-byte agreement across products through shared specification and raw-byte test vectors rather than runtime package coupling. | • Even though Layer 1 rejects floats in `questionnaire.json`, Layer 2 remains a complete standard RFC 8785 JCS serializer.<br>• Exact Python library selection and CI test vector assembly are tracked as `DEF-02`. | [ADR-0004](../docs/decisions/0004-questionnaire-rubric-separation.md), [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md), [ADR-0008](../docs/decisions/0008-two-product-repository-architecture.md), new Issue #4 ADR(s) (`0010`+), [docs/architecture.md](../docs/architecture.md) |
### 2.2 Accepted `B2.4` Framing Constraints (`USER_EXPLICIT`, step `849`)
In `step 849`, the user decomposed `B2.4` into five subdecisions (`B2.4.1`–`B2.4.5`, tracked as `S1-01`–`S1-05`) and established four binding framing constraints:
1. `schema_version` is a top-level field of `questionnaire.json` and is therefore covered by $H_q = \operatorname{SHA256}(\operatorname{JCS}(Q))$.
2. Changing `schema_version` changes $H_q$, which under `BL-01`/`BL-02` requires registering a new `assessment_id` with no version lineage.
3. Registered $(Q, R)$ pairs are never migrated or rewritten in place.
4. Cosmetic UI improvements and internal code refactoring must not require a new `schema_version`.
---
## Section 3 — Resolved Stage 1 Architectural Decisions (`S1-01` through `S1-17`)
Every entry below originated as an unapproved `step 850` recommendation and has received an explicit `USER_EXPLICIT` disposition (`2026-11-15`; `2` `ACCEPTED_AS_PROPOSED`, `15` `ACCEPTED_WITH_MODIFICATIONS`).
### `S1-01` — `B2.4.1` (Contract Version Scope)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-01` |
| **Decision ID** | `B2.4.1` |
| **Decision question** | What exact scope does `questionnaire.json`'s `schema_version` govern (unified document structure + frozen optional defaults + assessment-significant execution semantics vs. structure-only or split version fields), and how is it recorded in the attempt journal and `attempt.json`? |
| **Already-settled constraints** | `BL-03` (`B1` full-document $H_q$), `B2.1` (hash raw parsed JSON), and `step 849` framing constraints (`schema_version` is inside $H_q$). |
| **Approved decision** | Adopt **Option 1: Unified Questionnaire Contract Version**. The top-level `questionnaire.json` `schema_version` governs the complete public questionnaire contract, including: (1) document structure and validation constraints, (2) frozen semantics of omitted optional fields, (3) assessment-significant runtime interpretation (interaction mechanics, timing rules, response-state semantics), and (4) questionnaire-defined response and export semantics. It does **not** govern cosmetic presentation changes, internal implementation details, or unrelated application behavior. An engine upgrade must preserve the defined semantics of supported questionnaire contract versions; an engine unable to honor a version must reject execution rather than silently reinterpret the questionnaire (detailed support and retirement policy addressed by `S1-04`). The complete questionnaire snapshot persisted in the SQLite attempt journal (`BL-04`) already carries `schema_version` (avoiding redundant duplicated journal state); `attempt.json` must explicitly expose the questionnaire contract version as provenance (exact field name deferred to `DEF-01`). Because `schema_version` is part of the original questionnaire JSON tree, changing it changes $H_q$ and requires a new `assessment_id` under `BL-01`/`BL-02`. |
| **Modification delta vs. `step 850`** | Tightened the semantic boundary across the four explicit contract pillars and excluded areas; added explicit engine compatibility continuity and fail-closed rejection obligations (linked to `S1-04`); removed unnecessary duplicated `schema_version` field requirement in the SQLite attempt journal since `BL-04`'s embedded questionnaire snapshot already carries it; retained explicit provenance export in `attempt.json` (`DEF-01`). |
| **Rejected alternatives & rationale** | • **Split version fields** (`schema_version` + `semantics_version`): Rejected because under `step 849` changing either top-level field changes $H_q$ and forces a new `assessment_id` anyway (`BL-02`), adding complexity without lineage benefit.<br>• **Structure-only `schema_version`:** Rejected because under `B2.1` ($H_q$ hashes raw JSON without Pydantic defaults), leaving runtime/omission semantics unversioned would allow an upgraded engine to silently alter assessment behavior for an identical $H_q$. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-01`](issue-4-follow-through.md) |
### `S1-02` — `B2.4.2` (Semantic Immutability Boundary)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-02` |
| **Decision ID** | `B2.4.2` |
| **Decision question** | Which changes to questionnaire interpretation or rendering require a new `schema_version` versus qualifying as contract-preserving implementation improvements? |
| **Already-settled constraints** | `S1-01` (`B2.4.1`) four-pillar unified contract scope, `BL-01`/`BL-02` pair immutability, `B2.1`/`BL-03` raw-JSON $H_q$, and `step 849` framing constraint (cosmetic changes and internal refactoring do not require a new contract version). |
| **Approved decision** | Adopt **Option 1: Pillar-Based Outcome & Specification Criterion**. A new `schema_version` is required whenever the **normative questionnaire contract** changes in any of the four `S1-01` pillars: (1) document structure and validation constraints, (2) semantics of omitted optional fields, (3) assessment-significant runtime interpretation, and (4) questionnaire-defined response and export semantics. The classification criterion is a change to the **normative contract**, not merely a change in observed implementation behavior. Implementation changes that restore conformance to an existing, sufficiently specified contract do **not** require a new `schema_version`—including corrections to structural validation, defaults, runtime behavior, and export behavior when the existing specification already defines intended behavior. Conversely, resolving genuine specification ambiguity by selecting a different interpretation changes the normative contract and **requires** a new `schema_version`. Contract-preserving implementation improvements may retain the existing version, including: cosmetic presentation and styling changes; accessibility improvements preserving equivalent information and task constraints; internal refactoring and equivalent dependency or renderer upgrades; and spec-compliance bug fixes. Two attempts sharing a `schema_version` are governed by the same normative questionnaire contract, which does not by itself establish that their actual execution environments or implementation builds were identical; engine implementation provenance, if required for historical execution reproducibility, is separate from questionnaire contract versioning. |
| **Modification delta vs. `step 850`** | Anchored the immutability boundary directly to changes in the **normative questionnaire contract** across the four `S1-01` pillars rather than observed implementation behavior alone; clarified that spec-compliance bug fixes encompass structural validation, defaults, runtime behavior, and export behavior when sufficiently specified, whereas resolving genuine specification ambiguity requires a new `schema_version`; explicitly decoupled contract equivalence (`schema_version`) from engine build/execution-environment provenance. |
| **Rejected alternatives & rationale** | • **Strict presentation- & renderer-locked boundary:** Rejected under `step 849` because treating cosmetic UI, accessibility, or equivalent renderer updates as contract-breaking causes unnecessary version churn and retirement pressure (`S1-04`).<br>• **Structural-validation-only boundary:** Rejected because omitting default, runtime, and export semantics contradicts `S1-01` and allows silent behavioral drift for an identical $H_q$ under `B2.1`. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-02`](issue-4-follow-through.md) |
### `S1-03` — `B2.4.3` (Defaults and Explicit Configuration)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-03` |
| **Decision ID** | `B2.4.3` |
| **Decision question** | Which behavioral settings in `questionnaire.json` must be explicitly authored, and which optional fields may be omitted with frozen semantics under a contract version? |
| **Already-settled constraints** | `BL-03` (standalone `questionnaire.json` may omit `assessment_id`), `BL-04` (self-contained journal snapshot), `B2.1` (Pydantic defaults are never injected into $H_q$), `S1-01` (`B2.4.1`), and `S1-02` (`B2.4.2`). |
| **Approved decision** | Adopt **Option 1: Explicit Behavioral Authoring & Strictly Bounded "Absent / Not Applicable" Optionality**. All assessment-significant configuration must be explicitly represented in `questionnaire.json`, including: (1) contract identifier (`schema_version`), (2) timing policy (including explicit timed or untimed behavior), (3) question interaction primitive and applicable behavioral constraints, (4) author-declared learning objective references, and (5) other questionnaire-level or question-level rules affecting administration, interaction, or response capture. Omission is permitted only when the normative contract defines a stable, unambiguous absence or not-applicable meaning that introduces no hidden behavioral policy—for example, `assessment_id` omitted for standalone execution and required for registered assessments (`BL-03`), optional stimulus and presentation attachments omitted to indicate their absence (even if present they affect behavior), and optional grouping metadata omitted to indicate no additional grouping or scenario context. Wherever applicable, the questionnaire schema must explicitly define the distinction between absent properties, explicit `null` values, and empty collections (`[]`) so they do not acquire interchangeable meanings implicitly (preserving distinct raw-JSON representations under `B2.1`). Pydantic validation and model construction must never introduce assessment-significant behavior that was neither explicitly authored nor defined by the frozen omission semantics of the applicable `schema_version` (`Optional[T] = None` is permissible as an absence marker only if no undocumented fallback policy triggers on `None`). The original parsed JSON tree remains authoritative for $H_q$; internal model defaults must not alter the authored representation used for hashing. Exact field names, schema definitions, and whether empty objective-reference arrays (`[]`, e.g., `min_length=1`) are permitted or rejected remain deferred to `DEF-01` and Stage 2. |
| **Modification delta vs. `step 850`** | Framed optionality by omission consequences rather than assuming optional content cannot affect behavior when present; added explicit requirement to disambiguate absent keys vs. explicit `null` vs. empty collections (`[]`) under `B2.1`; tightened the Pydantic invariant to distinguish safe `None` absence markers from forbidden undocumented behavioral fallbacks; explicitly deferred exact field schemas and empty objective-reference array policy (`[]` / `min_length=1`) to `DEF-01` and Stage 2. |
| **Rejected alternatives & rationale** | • **Convenience behavioral defaults in schema / engine:** Rejected because omitted behavioral policies would become invisible in $H_q$ (`B2.1`) and `BL-04` snapshots while freezing arbitrary constants into `schema_version` (`S1-01`/`S1-02`).<br>• **Zero optional fields (`null` required everywhere):** Rejected because requiring boilerplate `null` keys for absent optional attachments adds authoring friction without improving semantic clarity. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-03`](issue-4-follow-through.md) |
### `S1-04` — `B2.4.4` (Contract Version Support and Retirement)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-04` |
| **Decision ID** | `B2.4.4` |
| **Decision question** | How long must `live-quiz` support historical `schema_version`s, and how do `live-quiz`, the Learning Registry, and the Tutor behave when a contract version is eventually retired? |
| **Already-settled constraints** | `BL-01` (Tutor performs `AVAILABLE` pre-flight check before offering reassessment; registered pairs are immutable), `BL-04` (self-contained journal snapshot for recovery), `ADR-0004` / `ADR-0008` / `ADR-0009` (product decoupling & historical evaluation independence), `S1-01` (`B2.4.1`), and `S1-02` (`B2.4.2`). |
| **Approved decision** | Adopt **Option 1: Permanent Specification Freeze + Controlled Runtime Retirement + Registry Retention**.<br>1. **Normative specification:** The normative specification of every released `schema_version` remains permanently frozen.<br>2. **Runtime support:** `live-quiz` supports active `schema_version`s across minor and patch releases. Runtime support for historical versions may be retired only at a major-release boundary, following an explicit deprecation announcement identifying the affected versions and intended retirement release (the minimum deprecation notice period remains unspecified unless separately established).<br>3. **Fail-closed execution:** `live-quiz validate`, `start`, and `recover` must reject unsupported `schema_version`s with `UNSUPPORTED_SCHEMA_VERSION`. The engine must never silently coerce, migrate, or reinterpret an unsupported questionnaire or journal.<br>4. **In-flight attempts:** Retiring a `schema_version` does not invalidate or authorize deletion of existing attempt journals. An unfinished attempt requiring a retired version must be recovered using an engine release that supports that version. A new attempt requires an explicit learner decision; the old journal must not be silently discarded or reinterpreted. *(Carried-forward constraint for `S1-13` / `DEF-01`: status inspection must account for paused journals using retired contract versions by surfacing them as recoverable—via a supporting engine release—but not executable by the currently installed engine, rather than hiding them or failing altogether.)*<br>5. **Registry preservation:** The Learning Registry retains historical `AVAILABLE` assessment pairs intact regardless of current `live-quiz` runtime support. Retirement does not delete, rewrite, or invalidate registered questionnaire/rubric definitions or their historical provenance. Registry availability and current runtime executability are distinct properties ($\text{Runnable}(A) = \text{RegistryAvailable}(A) \land \text{EngineSupports}(A.\text{schema\_version})$). New registration using retired `schema_version`s must be prevented; the enforcement authority and mechanism are addressed by `S1-06` and `DEF-01`.<br>6. **Tutor pre-flight:** Tutor checks Registry `AVAILABLE` status and current `live-quiz` compatibility before offering an existing assessment for reassessment. This check is read-only and advisory; `live-quiz` independently enforces compatibility during `validate`, `start`, and `recover`.<br>7. **Historical processing:** Runtime retirement does not invalidate historical attempts, evaluations, or consolidated learning records. Historical evaluation and audit processing must not depend on the current engine being able to execute the original questionnaire.<br><br>Exact CLI interfaces, compatibility-query mechanisms, and error/exit-code mappings are deferred to `DEF-01`. |
| **Modification delta vs. `step 850`** | Explicitly decoupled historical Registry `AVAILABLE` status from current runtime executability; defined major-release-only retirement with explicit deprecation announcement and in-flight journal protection (`BL-04`); prevented new registration of retired `schema_version`s (delegating authority/mechanism to `S1-06` and `DEF-01`); clarified that Tutor pre-flight is read-only/advisory while `live-quiz` enforcement (`validate`/`start`/`recover`) is authoritative; explicitly protected historical `attempt.json`, `evaluation.json`, and consolidated records across retirement; deferred CLI/exit-code mechanics to `DEF-01` and left minimum notice period unspecified; carried forward retired-version paused-journal surfacing requirement to `S1-13` / `DEF-01`. |
| **Rejected alternatives & rationale** | • **Eternal runtime compatibility (never retire any `schema_version`):** Rejected because preserving legacy UI widgets and execution adapters forever across major releases creates unbounded maintenance and security burden.<br>• **Destructive Registry purge/deactivation on engine retirement:** Rejected because mutating or deleting historical `AVAILABLE` pairs breaks audit provenance (`BL-01`–`BL-03`) and couples persistent DB history to transient binary upgrades (`ADR-0008`). |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-04`](issue-4-follow-through.md) |
### `S1-05` — `B2.4.5` (Migration and New Definitions Boundary)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-05` |
| **Decision ID** | `B2.4.5` |
| **Decision question** | Should `learningctl` / `learning-registryd` prohibit mechanical schema up-converters (`clone-upgrade` commands) in addition to prohibiting in-place pair rewrites? |
| **Already-settled constraints** | `BL-01`, `BL-02`, `BL-06`, `ADR-0008`, `ADR-0009`, `step 849` framing constraints (no in-place pair migration; changing `schema_version` yields a new `assessment_id` with no version lineage; longitudinal continuity uses shared `learning_objective_id`s), and `S1-01`–`S1-04` (`B2.4.1`–`B2.4.4`). |
| **Approved decision** | Adopt **Option 1: Prohibit In-Place Pair Rewrites and Registry-Side Mechanical Pair Up-Converters**.<br>1. **Immutable registered definitions:** `learningctl` and `learning-registryd` must not modify registered questionnaire/rubric pairs in place.<br>2. **Registry-side transformation prohibition:** `learningctl` and `learning-registryd` must not provide `clone-upgrade` commands or equivalent mechanisms that mechanically transform registered questionnaire/rubric pairs into derived replacement pairs (Registry-side pair transformation and derived assessment registration are prohibited).<br>3. **Fresh authored replacements:** Transitioning to a different `schema_version` requires authoring a fresh coordinated $(Q', R')$ pair conforming to a supported questionnaire contract and registering it under a new, independent `assessment_id`. The new pair has no parent/child assessment lineage; longitudinal continuity remains exclusively through shared `learning_objective_id` references.<br>4. **Authoring assistance:** Human authors and `quiz-designer` may use historical questionnaire content, objective mappings, and other accessible material as authoring context. External authoring-side tools may assist with extraction, structural transformation, or draft preparation, provided their output remains an unregistered draft and is not treated as an automatically valid replacement assessment.<br>5. **Mandatory review and registration:** Every replacement pair must undergo pedagogical review, explicit resolution of assessment-significant configuration (`S1-03`), $Q'/R'$ semantic alignment, and complete pair validation. `Tutor` must obtain explicit learner consent before registering the new assessment or initiating reassessment.<br>6. **Scope qualification:** This prohibition concerns semantic questionnaire/rubric pair migration and derived assessment registration. Ordinary Registry database schema migrations, serialization, validation, integrity verification, and versioned export-projection mechanisms ([ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md)) are outside this prohibition.<br><br>Exact authoring workflow and tool interfaces are deferred to `DEF-01` and Stage 2. |
| **Modification delta vs. `step 850`** | Corrected the rationale overstatement that every `schema_version` transition is behavioral; distinguished prohibited Registry-side `clone-upgrade` / derived registration from permitted authoring-side draft assistance producing unregistered drafts subject to pedagogical review, `S1-03` resolution, $Q'/R'$ co-validation, and `Tutor` consent; explicitly scoped out ordinary Registry DB migrations, serialization, validation, and versioned export projections. |
| **Rejected alternatives & rationale** | • **Restricted Registry-side `clone-upgrade`:** Rejected because `learningctl`/`learning-registryd` must stay decoupled from semantic $(Q, R)$ transformation (`ADR-0008`), cannot guarantee rubric co-alignment (`BL-01`) or hidden-default safety (`S1-03`), and risks bypassing consent-gated authoring.<br>• **Blanket ban on external authoring-side draft helpers:** Rejected as overly restrictive when structural field changes occur across contract versions, provided draft outputs remain unregistered until reviewed, co-validated, and explicitly consented. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-05`](issue-4-follow-through.md) |
### `S1-06` — `B2.5.1` (Boundary Hash Calculation and Verification Authority)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-06` |
| **Decision ID** | `B2.5.1` |
| **Decision question** | Which components calculate $H_q$ and which components independently recompute and verify $H_q$ at authoring, registration, startup, recovery, evaluation, and consolidation boundaries? |
| **Already-settled constraints** | `BL-03` (`B1`), `BL-04` (`C1`), `BL-07` (two-phase `REGISTERING` $\to$ `AVAILABLE`/`ABORTED`), `ADR-0004` / `ADR-0008` / `ADR-0009`, `B2.1`–`B2.3` (3-layer strict parser $\to$ JCS $\to$ SHA-256), and `S1-04` (`B2.4.4` Clause 5). |
| **Approved decision** | Adopt **Option 1: Independent $H_q$ Computation at Definition/Ingestion Boundaries and Correspondence Verification at Consumer/Consolidation Boundaries**.<br>1. **Authoring:** `live-quiz validate` independently validates `questionnaire.json` under `B2.1`–`B2.3` and the active contract-version policy, calculating $H_q$ from the original validated JSON tree. For registered assessments, `assessment_id` must first be allocated by `learning-registryd` (`REGISTERING`) and embedded in $Q$ and $R$ before the final $H_q$ is calculated.<br>2. **Registration:** `learning-registryd` independently validates the complete questionnaire/rubric pair, including strict questionnaire parsing, rubric contract validity, `assessment_id` correspondence, and `R.expected_questionnaire_hash`. It independently recomputes $H_q$ and never trusts a caller-supplied hash as authoritative. It independently enforces its configured active registration `schema_version` policy, rejecting unknown or retired versions without invoking the `live-quiz` executable. Registration transitions to `AVAILABLE` only after all checks succeed.<br>3. **Execution:** `live-quiz start` independently validates $Q$, enforces supported `schema_version` compatibility, calculates $H_q$, and durably stores the questionnaire snapshot and hash in the SQLite journal before serving routes. Every `attempt.json` export embeds `questionnaire_hash = H_q`, calculated over the complete questionnaire JSON tree; the questionnaire includes `assessment_id` in the hash when present, and standalone questionnaires may omit it.<br>4. **Recovery:** `live-quiz recover` reconstructs $Q$ from the journal, independently validates and recomputes $H_q$, and verifies correspondence with the persisted journal hash before serving routes.<br>5. **Evaluation:** `quiz-evaluator` receives `rubric.json` and `attempt.json`, not `questionnaire.json`. It verifies `assessment_id` and `expected_questionnaire_hash` correspondence where registered-pair identity applies, and propagates matching provenance into `evaluation.json`. It does not independently recompute $H_q$ because it does not possess $Q$.<br>6. **Consolidation:** `learning-registryd` verifies full correspondence across its authoritative stored $(Q, R)$ pair, `attempt.json`, `evaluation.json`, and the relevant assessment identity before atomically committing `CONSOLIDATED`.<br>7. **Tutor:** `Tutor` does not calculate $H_q$ or perform cryptographic verification; it coordinates the workflow and relies on the responsible components' validation results.<br>8. **Independent implementation:** `live-quiz` and `learning-registryd` maintain independent `B2.1`–`B2.3` implementations, with equivalence demonstrated through the mandatory shared raw-byte CI conformance suite (`DEF-02`).<br>9. **Registration-version policy:** The Registry's active registration-version policy and `live-quiz` runtime support policy must remain consistent. Configuration ownership, distribution, and verification are deferred to `DEF-01` / `DEF-05`.<br><br>Exact CLI interfaces, error contracts, and implementation details remain deferred to `DEF-01` and Stage 2. |
| **Modification delta vs. `step 850`** | Enforced mandatory `assessment_id` allocation (`REGISTERING`) prior to final $H_q$ calculation; explicitly required full $(Q, R)$ contract validation alongside independent $H_q$ recomputation at `learning-registryd`; added independent Registry active-registration `schema_version` allowlist enforcement without invoking `live-quiz` (`S1-04` Clause 5, `DEF-01`/`DEF-05`); scoped `quiz-evaluator` strictly to `(R, attempt.json)` correspondence checks rather than recomputing $H_q$ from $Q$; and required `questionnaire_hash = H_q` provenance on both managed and standalone `attempt.json` exports. |
| **Rejected alternatives & rationale** | • **`learning-registryd` shelling out to `live-quiz validate`:** Rejected because it violates `B2.3` (independent implementations verified via shared CI vectors) and couples a privileged daemon to an external learner-path binary (`ADR-0008`).<br>• **Trusting caller-supplied $H_q$ without recomputation:** Rejected because it defeats fail-closed tamper/corruption verification at registration and journal recovery (`BL-04`). |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-06`](issue-4-follow-through.md) |
### `S1-07` — `B2.5.2` (Canonical Questionnaire Persistence Representation)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-07` |
| **Decision ID** | `B2.5.2` |
| **Decision question** | Should the Learning Registry (`AVAILABLE` questionnaire payload) and the `live-quiz` attempt journal (`C1` snapshot) persist **canonical RFC 8785 JCS UTF-8 bytes** alongside $H_q$, or store raw authored JSON text? |
| **Already-settled constraints** | `BL-04` (`C1` self-contained journal snapshot), `BL-07` (temporary questionnaire materialization), `B2.1`–`B2.3` (strict non-normalizing `B2.2` parsing $\to$ JCS $\to$ SHA-256), and `S1-06` (`B2.5.1`). |
| **Approved decision** | Adopt **Option 1: Persist Layer 2 RFC 8785 JCS Canonical UTF-8 Bytes Alongside $H_q$**.<br>1. Both the Learning Registry (`AVAILABLE` questionnaire payload) and the `live-quiz` SQLite attempt journal (`BL-04` snapshot) persist the exact Layer 2 RFC 8785 JCS canonical UTF-8 bytes alongside $H_q$, and `learningctl` writes those stored canonical bytes directly during temporary questionnaire materialization (`BL-07`) without model re-serialization.<br>2. Original authoring whitespace, indentation, and JSON object-key ordering are intentionally not preserved, as they have zero assessment-semantic value under `B2.1`–`B2.3`.<br>3. Unicode code points and questionnaire data remain unchanged under the non-normalizing `B2.2` input profile (canonically equivalent Unicode sequences with distinct code points remain distinct).<br>4. `live-quiz recover` still performs full `S1-06` reconstruction, contract/version validation, canonicalization, and $H_q$ recomputation; canonical byte storage is not a validation shortcut.<br>5. Concrete SQLite column representation (`BLOB` vs. `TEXT`) remains deferred to `DEF-01` / `DEF-05`.<br><br>**Archival boundary:** Canonical persistence preserves the questionnaire's canonical data representation, not the original authoring file as an archival artifact; if exact source-file provenance ever becomes a requirement, it must be handled separately rather than weakening the canonical persistence contract. |
| **Modification delta vs. `step 850`** | Explicitly documented intentional non-preservation of formatting/key ordering vs. preservation of exact `B2.2` Unicode code points and questionnaire data; clarified that `live-quiz recover` never treats canonical storage as a validation shortcut (`S1-06`); deferred SQLite `BLOB` vs. `TEXT` typing to `DEF-01` / `DEF-05`; and added the explicit boundary distinguishing canonical data persistence from original authoring-file archival. |
| **Rejected alternatives & rationale** | • **Persist raw authored JSON bytes:** Rejected because preserving insignificant whitespace/key order adds size and prevents direct $\operatorname{SHA256}(\text{stored\_bytes}) = H_q$ identity without re-running JCS, for zero assessment-semantic benefit.<br>• **Asymmetric Registry vs. journal storage:** Rejected because both components implement identical `B2.1`–`B2.3` pipelines (`B2.3`) over the same canonical handoff (`BL-07`). |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-07`](issue-4-follow-through.md) |
### `S1-08` — `C2` (Legacy `attempt.json` `assessment_version` Policy)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-08` |
| **Decision ID** | `C2` |
| **Decision question** | How should `live-quiz`, `quiz-evaluator`, and `learningctl` treat any `attempt.json` containing the removed `assessment_version` field? |
| **Already-settled constraints** | `BL-02` (`assessment_version` eliminated), `BL-05` (no historical journal migration needed; greenfield repository with zero prior deployments), and [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md). |
| **Approved decision** | Adopt **Option 1: Omit `assessment_version` from Day One + Fail-Closed Rejection + Zero Legacy Shims**.<br>1. `live-quiz` produces `attempt.json` without `assessment_version` from the initial schema onward; `quiz-evaluator` and `learningctl` (including validation and consolidation) enforce fail-closed rejection via `extra="forbid"` whenever any `attempt.json` contract input contains `assessment_version`.<br>2. **Contract-boundary strictness:** `extra="forbid"` applies specifically when parsing `attempt.json` as a contract artifact, not indiscriminately to unrelated JSON inputs.<br>3. **No mutation of static files:** Static files on disk containing `assessment_version` remain untouched unless supplied to a validator or consumer.<br>4. **No compatibility aliases or shims:** Do not introduce deprecated fields, stripping logic, import adapters, or conditional parsing paths.<br>5. **Conforming test fixtures:** Any fixture containing `assessment_version` is invalid under the new contract; its rejection is intended contract feedback rather than a compatibility issue.<br><br>**`DEF-01` parity requirement:** Ensure the JSON Schema representation (`attempt.schema.json`) and runtime Pydantic validation enforce the same closed-object policy so consumers never disagree on acceptance/rejection. |
| **Rejected alternatives & rationale** | • **Silent ignore / strip `assessment_version` on read:** Rejected because it weakens `extra="forbid"` contract strictness, introduces dead compatibility shims into a greenfield repository (`BL-05`), and masks `BL-02` violations. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_AS_PROPOSED` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-08`](issue-4-follow-through.md) |
### `S1-09` — `D1a` (Registry Repository and Package Ownership)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-09` |
| **Decision ID** | `D1a` |
| **Decision question** | Should `learningctl`, `learning-registryd`, and host provisioning live in a separate dedicated repository (`learning-registry`) or inside the `live-quiz` repository as a multi-component monorepo? |
| **Already-settled constraints** | `BL-06` (`learningctl` + `learning-registryd` service boundary, dedicated OS identity/IPC/permissions), `B2.3` (independent implementations without a shared runtime package), `S1-04`/`S1-06` (contract-version parity), and [ADR-0008](../docs/decisions/0008-two-product-repository-architecture.md). |
| **Approved decision** | Adopt **Option 1: Single Multi-Component Monorepo inside `live-quiz`** (three independently implemented and independently deployable components, not a shared application):<br>1. **Independent build and packaging boundaries:** House three top-level components (`live-quiz` engine/SPA, `learning-registry` package/daemon/CLI/host provisioning, and `skills/` portable workflows), each with its own dependency declaration, build target, and installation artifact. `live-quiz` must not depend on the Registry's Python package; `learning-registryd` must not depend on private `live-quiz` implementation modules; shared first-party runtime helper packages remain prohibited (`B2.3`).<br>2. **Mechanically enforced import isolation in CI:** CI must inspect import relationships (and use isolated package builds/virtual environments as appropriate) and fail when prohibited cross-package Python runtime imports appear, while permitting shared normative schemas (`DEF-01`), raw-byte conformance fixtures (`B2.3` / `DEF-02`), and atomic cross-contract CI verification.<br>3. **Independent release and deployment lifecycles:** Repository co-location does not imply synchronized releases; independent versioning, deployment lifecycles, OS identities, IPC boundaries, and permissions remain preserved.<br>4. **Stage 2 ADR update:** Stage 2 must amend or supersede [ADR-0008](../docs/decisions/0008-two-product-repository-architecture.md) to reflect the three-component monorepo architecture. |
| **Modification delta vs. `step 850`** | Explicitly separated repository layout from runtime/OS/deployment boundaries; required independent dependency, build, and packaging boundaries; elevated cross-package import isolation from convention to mechanical CI enforcement (permitting shared schemas and conformance fixtures); preserved independent release and deployment lifecycles; and required Stage 2 to amend or supersede `ADR-0008`. |
| **Rejected alternatives & rationale** | • **Separate dedicated `learning-registry` repository:** Viable via versioned contract artifacts and cross-repo CI workflows, but introduces additional versioning, publication, and cross-repo coordination overhead not justified for this greenfield project—especially while atomically co-verifying `S1-04`/`S1-06`/`B2.3` schemas and raw-byte conformance vectors.<br>*Note:* Physical repo separation alone would not guarantee runtime isolation without packaging, permission, and deployment boundaries. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-09`](issue-4-follow-through.md) |
### `S1-10` — `D1b` (Workspace Marker Edge Cases, Fail-Closed Error Taxonomy & Migration Trigger)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-10` |
| **Decision ID** | `D1b` |
| **Decision question** | How should `learningctl` handle duplicate `init` or unregistered `.learning-workspace` markers, classify fail-closed global DB states, and gate registry schema migrations? |
| **Already-settled constraints** | `BL-06` (nearest-ancestor `.learning-workspace` resolution, Git root rejected, host provisioning separate from `learningctl init`, `init` never recreates a missing global DB, pre-disruptive encrypted backup invariant), and `S1-05` Clause 6 (ordinary DB schema migrations permitted). |
| **Approved decision** | Adopt **Option 1: Idempotent Same-Dir `init` + Fail-Closed Unregistered Marker + 5-Class Error Taxonomy + Explicit Backup-Gated Out-of-Band Migration**.<br>1. **Same-directory `learningctl init`:** Idempotent when `.learning-workspace` already exists and its `workspace_id` is already validly registered for that workspace in the global DB.<br>2. **Unregistered / malformed marker:** Fail closed (`UNREGISTERED_WORKSPACE_MARKER`) when a `.learning-workspace` marker file's `workspace_id` is unknown to the global DB (never overwriting, auto-registering, or bypassing to a parent marker).<br>3. **Fail-closed DB/daemon error taxonomy:** Classify daemon and global DB failures into five deterministic categories: `NOT_PROVISIONED`, `MISSING_OR_LOCKED`, `CORRUPT`, `MIGRATION_REQUIRED`, and `UNSUPPORTED_SCHEMA` (exact exit codes and JSON error schema deferred to `DEF-04`).<br>4. **Explicit backup-gated migration:** Reject DB access fail-closed with `MIGRATION_REQUIRED` on schema mismatch and require an explicit out-of-band admin migration command gated on a verified encrypted backup snapshot (`S1-15`). |
| **Rejected alternatives & rationale** | • **Silent auto-migration on daemon startup:** Rejected because it blurs runtime availability under systemd socket activation with disruptive schema mutation and risks unverified/unrecoverable upgrades.<br>• **Auto-re-registering unregistered `.learning-workspace` markers:** Rejected because it risks silently aliasing or dissociating `workspace_id` provenance (`BL-06`). |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_AS_PROPOSED` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-10`](issue-4-follow-through.md) |
### `S1-11` — `D2a` (`REGISTERING` Status Visibility and `ABORTED` Tombstone Retention)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-11` |
| **Decision ID** | `D2a` |
| **Decision question** | How are incomplete `REGISTERING` records surfaced in `learningctl status`, and how are `ABORTED` registration records and their unverified draft payloads retained? |
| **Already-settled constraints** | `BL-07` (`REGISTERING` $\to$ `AVAILABLE` / `ABORTED`; only `AVAILABLE` is executable; `assessment_id` is never reused; registration failure $\neq$ attempt crash recovery), `BL-08` (`learningctl status` single read-only startup snapshot), and `S1-06` (`assessment_id` allocated in `REGISTERING` prior to $(Q, R)$ completion). |
| **Approved decision** | Adopt **Option 1: Dedicated `incomplete_registrations` in `status` (No TTL) + Lightweight Permanent `ABORTED` Tombstones**.<br>1. **Incomplete `REGISTERING` visibility:** `REGISTERING` is persistent state, not a temporary error. Surface incomplete `REGISTERING` records in a dedicated `incomplete_registrations` section of `learningctl status` (workspace-scoped by default, cross-workspace with `--all`, with zero automatic TTL expiry).<br>2. **Explicit `Tutor` authority:** `Tutor` may surface and explain incomplete registrations and offer the learner the opportunity to resume or abort them, but `Tutor` must **not** automatically finalize or abort stale registrations; both transitions require explicit authorization.<br>3. **`ABORTED` tombstones & auditability:** Transition aborted/failed registrations to lightweight permanent `ABORTED` metadata tombstones hidden from learner-facing `status` and `--all`. Hiding a tombstone is distinct from deleting its audit information: each tombstone retains administrative audit metadata (`assessment_id`, aborted state, transition timestamp, and reason where available).<br>4. **Payload purge without ID loss:** Purge any unverified draft $Q$/$R$ payloads upon transition to `ABORTED`, without removing the permanent `assessment_id` reservation or its audit metadata.<br><br>Exact metadata columns, CLI representation, and administrative inspection interfaces remain deferred to `DEF-04` and `DEF-05`. |
| **Modification delta vs. `step 850`** | Explicitly scoped default `incomplete_registrations` to the current workspace (`--all` for cross-workspace); forbade `Tutor` from automatically finalizing or aborting stale `REGISTERING` entries without explicit authorization; distinguished learner-facing hiding of `ABORTED` from administrative auditability (retaining `assessment_id`, aborted state, timestamp, and reason); clarified that draft $Q$/$R$ payload purging must preserve the `assessment_id` reservation and audit metadata; and deferred exact schema/CLI/admin inspection interfaces to `DEF-04` / `DEF-05`. |
| **Rejected alternatives & rationale** | • **Omit `REGISTERING` from `learningctl status` (separate query only):** Rejected because it breaks `BL-08`'s single-call `Tutor` initialization snapshot.<br>• **Automatic TTL expiry on `REGISTERING`:** Rejected because time-based background mutations inside `learning-registryd` risk invalidating legitimate interrupted authoring sessions. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-11`](issue-4-follow-through.md) |
### `S1-12` — `D2b` (Startup-Commit Acknowledgment and Temporary Questionnaire Cleanup Protocol)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-12` |
| **Decision ID** | `D2b` |
| **Decision question** | By what mechanism does `live-quiz start` acknowledge that the `C1` journal snapshot is durably committed and the local HTTP server is bound, so `learningctl` can delete the temporary materialized `questionnaire.json` immediately without waiting for the learner to finish the quiz? |
| **Already-settled constraints** | `BL-04` (`C1` durable snapshot before learner access), `BL-07` (idempotent temp questionnaire cleanup via `learningctl`), [ADR-0002](../docs/decisions/0002-harness-agnostic-process-lifecycle.md), and [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md). Soft/informational dependency: `S1-07` (`B2.5.2`). |
| **Approved decision** | Adopt **Option 1: Strict Startup Ordering + Explicitly Flushed `SESSION_READY` NDJSON on `stdout`**.<br>1. **Strict startup ordering:** `live-quiz start` executes strictly in order: questionnaire/schema-version validation $\to$ durable `BL-04` SQLite journal snapshot commit $\to$ localhost TCP listener bind and HTTP server readiness $\to$ emit and explicitly flush `SESSION_READY`.<br>2. **`SESSION_READY` guarantees:** `SESSION_READY` is emitted only once per successful startup after the server is actually ready to accept requests, guaranteeing both (a) durable journal snapshot persistence independent of the temporary questionnaire file, and (b) a usable listener at the advertised URL.<br>3. **Exclusive machine-readable NDJSON `stdout` protocol:** `stdout` carries exclusively one complete JSON document per line (one `SESSION_READY` event on startup, one terminal outcome event at process termination); all diagnostic messages/logging go to `stderr`. Callers must continuously drain `stdout` line-by-line (never waiting for EOF before reading) and cannot assume the full `stdout` stream is a single JSON document (reconciling [ADR-0002](../docs/decisions/0002-harness-agnostic-process-lifecycle.md) / [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md) in Stage 2).<br>4. **Temporary-file cleanup ownership:** The temporary-file owner/coordinator deletes the materialized questionnaire immediately and idempotently upon observing `SESSION_READY` without waiting for assessment completion; cleanup failure is reported independently and must not invalidate an already-committed journal snapshot.<br>5. **Mid-startup failure boundary:** Failure between durable journal commit and HTTP server readiness must not leave temporary-file cleanup exclusively dependent on receiving `SESSION_READY`; callers/coordinators must have a recovery or cleanup path for the materialized file.<br>6. **Portability qualification & deferrals:** If a future harness cannot reliably expose and drain `stdout`, the protocol's portability assumption should be revisited. Exact event schema, coordinator ownership details, and cleanup recovery mechanics remain deferred to `DEF-03` / `I9-01`. |
| **Modification delta vs. `step 850`** | Distinguished TCP socket bind from full HTTP server readiness; elevated `stdout` to an exclusive line-oriented NDJSON protocol (explicit flush, diagnostics on `stderr`, continuous draining, Stage 2 reconciliation with `ADR-0002`/`ADR-0007`); clarified temporary-file owner cleanup semantics and non-invalidation on cleanup failure; added explicit mid-startup failure cleanup boundary between journal commit and `SESSION_READY`; noted portability revisit qualification; and deferred exact event schema, coordinator ownership, and cleanup recovery mechanics to `DEF-03` / `I9-01`. |
| **Rejected alternatives & rationale** | • **Out-of-band `--ready-fd` or `--ready-file`:** Rejected to avoid extra communication channels, shell/harness FD-inheritance incompatibilities, and secondary temp-file lifecycles when `stdout` already carries structured lifecycle events.<br>• **Post-exit cleanup only:** Rejected because leaving temporary `questionnaire.json` on disk throughout multi-hour or suspended sessions violates `BL-07` and leaks files on crashes. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-12`](issue-4-follow-through.md) |
### `S1-13` — `D3a` (Read-Only Active-vs.-Recoverable Attempt Inspection Contract)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-13` |
| **Decision ID** | `D3a` |
| **Decision question** | How does `live-quiz` track active process liveness and expose a read-only (`mode=ro`) inspection interface so `learningctl status` can distinguish `ACTIVE_LIVE_ATTEMPT` from `RECOVERABLE_INTERRUPTED_ATTEMPT` without mutating journals or reading private SQLite tables? |
| **Already-settled constraints** | `BL-04` (`C1`), `BL-08` (`learningctl status` is read-only; `live-quiz` is sole authority for active vs. recoverable state without exposing private SQLite tables), [ADR-0006](../docs/decisions/0006-ephemeral-sqlite-session-journal.md), and `S1-04` (`B2.4.4` carried-forward requirement: status inspection must surface paused journals using retired contract versions as recoverable—under a supporting engine—but not executable by the currently installed engine, rather than hiding them or failing altogether). |
| **Approved decision** | Adopt **Option 1: Continuous `flock` + Read-Only Batch Inspection**.<br>1. **Continuous exclusive `flock`:** `live-quiz` holds an exclusive OS `flock` on sibling `attempt-<attempt-id>.lock` for the full duration of every active session (`start` and `recover`), established consistently before an attempt becomes inspectable.<br>2. **Read-only batch inspection:** `live-quiz` exposes a read-only batch CLI inspection command invoked by `learningctl status`, keeping private SQLite tables encapsulated from `learningctl` (`BL-08`).<br>3. **Lock-probe concurrency & safety:** Inspection probes locks without creating missing lock files and without unlinking lock files, accounting for check-then-inspect concurrency (e.g., temporary non-blocking exclusive lock during inspection) and treating a missing lock file alongside an existing journal as an anomaly rather than automatic proof of inactivity.<br>4. **Strict filesystem non-mutation:** Inspection must not create, modify, checkpoint, or delete journal files or `-wal`/`-shm` sidecars. SQLite `mode=ro` alone is not accepted as proof of zero filesystem side effects, and `immutable=1` must not be used as a generic substitute for safely inspecting a potentially active WAL database; if a journal cannot be inspected under these constraints, report an inspection anomaly rather than attempting automatic repair.<br>5. **Explicit anomaly & cleanup states:** Surface `CLEANUP_PENDING`, orphan `-wal`/`-shm` sidecars, and other inspection anomalies explicitly without automatic repair.<br>6. **Retired-version visibility:** Separate metadata inspection from execution-level validation so paused journals using retired `schema_version`s remain visible in `status` with recoverability (via a supporting engine) and current-engine executability represented separately.<br>7. **Deferrals:** Exact CLI schema, SQLite opening/inspection mechanics, lock-file lifecycle details, and safe stale lock-file pruning policy are deferred to `DEF-03`. |
| **Modification delta vs. `step 850`** | Replaced the over-strong claim that `mode=ro` alone guarantees zero sidecar mutation with an explicit filesystem non-mutation invariant (and warned against `immutable=1`); added lock-probe concurrency requirements, missing-lock anomaly treatment, and non-creating/non-unlinking rules; separated metadata inspection from execution-level validation for retired-version paused journals (`S1-04`); required explicit `CLEANUP_PENDING` and orphan-sidecar anomaly reporting; and deferred CLI schema, SQLite mechanics, and `.lock` pruning to `DEF-03`. |
| **Rejected alternatives & rationale** | • **PID-file liveness check:** Rejected due to stale-PID false positives after `SIGKILL` and PID-reuse collisions.<br>• **Direct SQLite reads by `learningctl`:** Rejected because it violates `BL-08` encapsulation of private engine SQLite tables and `ADR-0008` decoupling. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-13`](issue-4-follow-through.md) |
### `S1-14` — `D3b` (Service-Boundary Delegation Cutoff and `schema_version` Format)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-14` |
| **Decision ID** | `D3b` |
| **Decision question** | Should per-command `learningctl --json` `schema_version` standardize on `"<major>.<minor>"` string syntax, and where is the exact boundary between architectural service invariants and deferred host packaging details? |
| **Already-settled constraints** | `BL-06` (`learningctl` $\to$ UDS IPC $\to$ `learning-registryd` under `learning-registry` user, `Accept=no`, serialized mutations, per-command `schema_version` compatibility principles; exact `"<major>.<minor>"` format flagged open at `step 827`), `S1-09` (`D1a` repo boundary), and `S1-10` (`D1b` out-of-band admin migration). |
| **Approved decision** | Adopt **Option 1: `"<major>.<minor>"` String Format + Strict Agent/Admin Cutoff + `DEF-04`/`DEF-05` Delegation**.<br>1. **`learningctl --json` `schema_version` format:** Standardize every `learningctl --json` per-command response `schema_version` on `"<major>.<minor>"` string syntax (e.g., `"1.0"`, `"1.1"`, `"2.0"`), encoding additive minor updates vs. breaking major changes.<br>2. **Contract independence:** Explicitly clarify that this `learningctl --json` CLI output `schema_version` is **completely independent** of `questionnaire.json`'s `schema_version` (`S1-01`–`S1-04`).<br>3. **Strict agent/admin privilege cutoff:** Keep privileged host provisioning, encryption key escrow/import, DB schema migration (`S1-10`), and backup restore strictly out of agent-facing `learningctl` (confined to privileged admin tooling / host provisioning).<br>4. **Operational delegation:** Delegate exact systemd `.socket`/`.service` directives, UDS paths/OS group names/file modes, IPC wire framing, XDG runtime/state paths, and exact `learningctl` subcommand/flag spellings to `DEF-04` and `DEF-05`. |
| **Modification delta vs. `step 850`** | Explicitly recorded that `learningctl --json`'s `"<major>.<minor>"` CLI output `schema_version` is completely independent of `questionnaire.json`'s `schema_version` (`S1-01`–`S1-04`). |
| **Rejected alternatives & rationale** | • **Integer-only `schema_version` (`1`, `2`, ...):** Rejected because a bare integer cannot distinguish backward-compatible additive minor changes from breaking major changes under `BL-06`.<br>• **Locking systemd/UDS/CLI spellings in Stage 1/2:** Rejected because host-packaging details (`DEF-05`) and ergonomic CLI syntax (`DEF-04`) belong in implementation specifications rather than durable ADRs. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-14`](issue-4-follow-through.md) |
### `S1-15` — `D4` (Out-of-Band Key Escrow, Backup Verification Gate & Operational Delegation)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-15` |
| **Decision ID** | `D4` |
| **Decision question** | How is non-TPM cross-host portability reconciled with keeping encryption keys out of `learningctl` and DB backups, and how are backup snapshots verified before rotation or destructive maintenance? |
| **Already-settled constraints** | `BL-06` (mandatory encryption, `SQLCipher` candidate only, non-TPM default host key protection separate from workspaces and DB backups, `learning-registryd` Online Backup API snapshots on schedule and pre-disruptive operations), `S1-10` (`D1b` fail-closed & pre-migration backup gate), and `S1-14` (`D3b` admin/agent privilege cutoff). |
| **Approved decision** | Adopt **Option 1: Out-of-Band Admin Key Escrow + Stage-Then-Verify Backup Gate (`DEF-05`-Conditional Primitive)**.<br>1. **Privileged out-of-band key escrow/import:** Key material is never stored in workspace directories or DB backup directories and is never accessible via `learningctl` (admin-only functionality). Loss or unavailability of the required key must be reported as a recoverability failure, not mistaken for database corruption; backup retention and key-retention policies must remain consistent.<br>2. **Stage-then-verify backup pipeline:** For encrypted Online Backup API snapshots: produce a staged encrypted snapshot $\to$ independently reopen/verify that snapshot using the selected DB engine and appropriate key $\to$ perform engine-specific integrity checks and verify expected schema/version and essential metadata $\to$ promote atomically into the verified catalog only after verification succeeds (discard staging on failure). Full end-to-end restore drills are not required before every backup promotion.<br>3. **Protect the last verified recovery point:** A failed backup or verification operation must never discard the last verified recovery point.<br>4. **Key availability for recoverability:** A snapshot counts as cryptographically recoverable only if its required key material remains available alongside passing DB integrity checks.<br>5. **Pre-migration snapshot gate:** `S1-10` destructive schema migrations require a freshly verified pre-migration encrypted snapshot and remain explicit administrative operations.<br>6. **Three distinct backup/recovery guarantees:** Explicitly preserve the separation between: (a) **artifact integrity** (staged encrypted snapshot is internally valid and passes verification—backup pipeline), (b) **cryptographic recoverability** (snapshot can be decrypted using separately protected key material—key management/escrow), and (c) **operational recoverability** (system can actually be restored and brought back into service—admin recovery procedures and restore drills).<br>7. **Candidate discipline:** `SQLCipher` remains a **candidate**, not a selected implementation.<br>8. **Deferrals:** Concrete engine-specific verification primitives, key management, escrow, rotation, retention, scheduling, credential mechanisms, and external synchronization are deferred to `DEF-05`. |
| **Modification delta vs. `step 850`** | Replaced generic "independent keyed integrity verification" with a 5-step stage-reopen-verify-metadata-promote pipeline; distinguished key unavailability from DB corruption and aligned backup/key retention; required key availability alongside integrity to count as cryptographically recoverable; required a freshly verified snapshot before `S1-10` migrations; codified the three distinct recovery guarantees (artifact integrity vs. cryptographic recoverability vs. operational recoverability) without requiring full restore drills on every promotion; and kept `SQLCipher` strictly a candidate with primitives/escrow/rotation/retention/sync deferred to `DEF-05`. |
| **Rejected alternatives & rationale** | • **Bundling wrapped key material inside DB backup bundles:** Rejected because it violates `BL-06` key separation and collapses backup compromise into full rubric/history compromise.<br>• **Unverified Online Backup promotion:** Rejected because disk/cipher corruption in a staged snapshot could rotate away the last valid recovery point undetected. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-15`](issue-4-follow-through.md) |
### `S1-16` — `E1` (Per-Execution Staging Slot Allocation and `--output` Destination Discipline)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-16` |
| **Decision ID** | `E1` |
| **Decision question** | How are managed `attempt.json` export paths allocated before `live-quiz` generates `attempt_id` so reassessments and multiple attempts never collide on `--output` (`CONFLICT_DIFFERENT_ATTEMPT`)? |
| **Already-settled constraints** | `BL-04` (`C1`), `BL-09` (persistent non-workspace staging area for managed `attempt.json` until consolidation; standalone exports remain user-controlled files), and [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md) (single-file `--output <path>` idempotency and `CONFLICT_DIFFERENT_ATTEMPT` conflict rule). |
| **Approved decision** | Adopt **Option 1: Registry-Allocated Per-Execution Staging Slots via Existing `--output <path>` Contract**.<br>1. **`interaction_id` vs. `attempt_id` separation:** `interaction_id` identifies the managed execution and its staging lifecycle (allocated by the Registry before launching `live-quiz`), whereas `attempt_id` identifies the actual assessment attempt (generated by `live-quiz` per `BL-04`). `live-quiz` remains unaware of Registry interactions and staging directory management.<br>2. **Immutable per-execution slot:** Every managed execution receives a unique `interaction_id` and staging slot (`<staging_root>/<interaction_id>/attempt.json`) allocated before `live-quiz start` and never reused for another execution.<br>3. **Same path on recovery:** `live-quiz start` and `live-quiz recover` for the same execution must pass the exact same `--output <path>`.<br>4. **Unused/abandoned slots:** Slots allocated during execution preparation that fail before `live-quiz` creates its journal must never be silently reassigned to a different execution; unused/abandoned slot cleanup lifecycle is deferred to `DEF-04` / `DEF-05`.<br>5. **Identity allocation vs. filesystem ownership:** Registry allocates `interaction_id` and staging association, `learningctl` coordinates execution preparation, `live-quiz` atomically exports to the supplied path, and consolidation consumes the staged artifact. Output paths must be constructed from a validated identifier under a controlled staging root—never accepted as an arbitrary agent-supplied path—with exact filesystem permissions/ownership deferred to `DEF-04` / `DEF-05`.<br>6. **Unchanged `ADR-0007` & standalone rules:** Standalone exports remain completely outside this slot allocation mechanism, and [ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md)'s `CONFLICT_DIFFERENT_ATTEMPT` and same-`attempt_id` idempotency rules remain unchanged (zero `--output-dir` mode added to `live-quiz`). |
| **Modification delta vs. `step 850`** | Explicitly separated `interaction_id` (Registry staging identity) from `attempt_id` (engine attempt identity); barred silent reassignment of unused pre-journal slots (`DEF-04`/`DEF-05` cleanup); separated Registry identity allocation from filesystem artifact ownership (`DEF-04`/`DEF-05` permissions); required staging paths to be constructed from validated IDs under a controlled root rather than arbitrary agent paths; and reaffirmed unchanged `ADR-0007` and standalone export semantics. |
| **Rejected alternatives & rationale** | • **Adding `--output-dir` mode to `live-quiz`:** Rejected because it complicates `ADR-0007`'s single-file `--output <path>` idempotency/conflict contract and decouples `interaction_id` slot ownership from the exported file.<br>• **Per-`assessment_id` staging path:** Rejected because reassessments (`BL-01`) and post-abandonment retries (`BL-09`) collide on `CONFLICT_DIFFERENT_ATTEMPT`. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-16`](issue-4-follow-through.md) |
### `S1-17` — `E2` (Pre-Consolidation Storage Split, Pre-Debrief Status Reconciliation & `ABANDONED` Payload Retention)
| Field | Description |
| :--- | :--- |
| **Task ID** | `S1-17` |
| **Decision ID** | `E2` |
| **Decision question** | Where do pre-consolidation interaction metadata, append-only events, payloads, and structured debrief checkpoints live before `CONSOLIDATED`, how does `learningctl status` surface un-evaluated staged `attempt.json` exports without altering the `BL-09` states, and how does transactional consolidation verify artifact correspondence? |
| **Already-settled constraints** | `BL-09` (settled lifecycle states: `PENDING_DEBRIEF`, `DEFERRED`, `PENDING_CONSOLIDATION`, `CONSOLIDATED`, `ABANDONED`; managed `attempt.json` staged until atomic consolidation of `(attempt, evaluation, Tutor observations)` into `CONSOLIDATED` with idempotent receipt; append-only history vs. reversible `ABANDONED` disposition hidden from `status` and `--all`; bounded ~1–3 turn debrief facilitation guideline; structured debrief progress without chat transcripts), `S1-06` (`B2.5.1` 4-way correspondence), and `S1-16` (`E1` per-execution staging slot). |
| **Approved decision** | Adopt **Option 1: Registry Envelopes/Events + `E1` Slot Payloads (Retained on `ABANDONED`) + Derived `awaiting_evaluation` + Bundle-Bound Idempotent Consolidation**.<br>1. **Storage separation & `ABANDONED` retention:** The encrypted Registry DB stores lightweight interaction envelopes and append-only lifecycle events. `E1` staging slots hold unconsolidated payloads (`attempt.json`, `evaluation.json`, and structured debrief checkpoints—never full conversation transcripts) until `CONSOLIDATED`. Payloads remain retained across `ABANDONED` without changing `BL-09` states or visibility rules (`status`/`--all` hidden); retention does not authorize automatic revival (reconsideration requires an explicit learner request and a supported transition or execution path). `E1`'s encryption-at-rest, ownership, permissions, and backup requirements must be explicitly resolved before implementation (`DEF-04`/`DEF-05`).<br>2. **Read-only reconciliation:** `awaiting_evaluation` remains a strictly derived, read-only status classification—never persisted, never a `BL-09` lifecycle state, and never a transition target (leaving all five `BL-09` states unchanged). It applies only when the corresponding `attempt.json` export exists and `evaluation.json` is absent. Missing, inaccessible, malformed, or inconsistent staging data must be surfaced as an inspection anomaly. Reconciliation must not mutate either persistence domain or initiate evaluation.<br>3. **Bundle-bound consolidation:** Consolidation verifies complete $Q$/$R$/`attempt.json`/`evaluation.json` correspondence and relevant identity under `S1-06`. The idempotency receipt binds to the complete normalized `(attempt, evaluation, Tutor observations)` bundle correspondence: identical retries return the existing receipt, and mismatched retries fail closed. The receipt and `CONSOLIDATED` transition are atomic, and `E1` cleanup follows only after durable consolidation. Exact normalization, digest, schema, and storage mechanics remain deferred to `DEF-04` / `DEF-05`. |
| **Modification delta vs. `step 850`** | Explicitly barred automatic revival of retained `ABANDONED` payloads; flagged `E1` encryption-at-rest, ownership, permissions, and backup requirements as mandatory pre-implementation resolutions (`DEF-04`/`DEF-05`); restricted `awaiting_evaluation` strictly to existing `attempt.json` + absent `evaluation.json` with zero mutation/evaluation side effects and required anomaly reporting for missing/inaccessible/malformed/inconsistent staging data; and required atomic receipt + `CONSOLIDATED` commit bound to complete normalized `(attempt, evaluation, Tutor observations)` bundle correspondence (failing closed on mismatch) before `E1` cleanup. |
| **Rejected alternatives & rationale** | • **Storing unconsolidated payloads in Registry DB pre-consolidation:** Rejected because it contradicts `BL-09` staging and bloats encrypted Registry backups with unconsolidated/abandoned payloads.<br>• **Persisting a 6th `AWAITING_EVALUATION` state & purging `ABANDONED` payloads:** Rejected because it mutates the settled `BL-09` state model and breaks reversible abandonment. |
| **Provenance** | `USER_EXPLICIT` (approved `2026-11-15`; originating proposal `step 850`) |
| **Status** | `ACCEPTED_WITH_MODIFICATIONS` |
| **Tracker reference** | [issue-4-follow-through.md — `S1-17`](issue-4-follow-through.md) |
---
## Section 4 — Deferred Implementation Responsibilities (`DEF-01` through `DEF-05`)
The following engineering tasks are intentionally postponed to post-Stage-3 implementation:
- **`DEF-01` — JSON Schemas & Strict Pydantic Models:** Exact field names and `.schema.json` specifications for `questionnaire.json`, `rubric.json`, `attempt.json`, and `evaluation.json`, including recursive `extra="forbid"`, `strict=True`, and negative nesting tests.
- **`DEF-02` — RFC 8785 Library Selection & Shared Conformance Suite:** Selection of the concrete Python RFC 8785 package (`rfc8785` / `jcs` candidates) and assembly of the shared raw-byte CI conformance test suite (official RFC 8785 vectors + `B2.2` negative parser vectors + `attempt.json` float vectors).
- **`DEF-03` — `live-quiz` CLI Interface & Output Schemas:** Exact subcommand spellings, flags, and output/JSON schemas for `live-quiz validate`, startup readiness acknowledgment (`D2b`), and read-only attempt inspection (`D3a`), plus authoring `live-quiz.md`.
- **`DEF-04` — `learningctl` Domain CLI Grammar & JSON Schemas:** Exact `.learning-workspace` optional metadata fields, command/flag spellings, and CLI `schema_version` / JSON output schemas (`status`, consolidation receipt, structured debrief checkpoint), plus authoring `learningctl.md`.
- **`DEF-05` — Host Daemon Packaging, Security & Backup Operations:** Exact `learning-registryd` systemd `.socket`/`.service` units, UDS path/group/modes, private IPC wire framing, XDG runtime/state paths, encrypted DB driver (`SQLCipher` candidate), concrete backup integrity-check primitive, credential mechanism (`LoadCredentialEncrypted=` vs. keyfile), admin key-escrow/migrate/restore tooling, backup timer schedule, retention thresholds, and external sync target.
> [!IMPORTANT]
> **Boundary Rules for Deferred Items:**
> 1. **Deferred $\neq$ Decided:** Postponing an implementation mechanism does not select a default candidate (e.g., `SQLCipher` and `rfc8785` remain candidates until `DEF-02`/`DEF-05`).
> 2. **Invariants vs. Mechanisms:** An architectural invariant (such as mandatory at-rest encryption, backup integrity verification before promotion, or 3-layer JCS hashing) is binding once approved, while its concrete implementation remains open under `DEF-01`–`DEF-05`.
> 3. **No Premature ADR Encoding:** Stage 2 ADRs (`S2-01`–`S2-05`) must record the actual user-approved architectural contracts and invariants (including any approved modifications or alternatives), never locking in unapproved `DEF-01`–`DEF-05` implementation specifics as if they were settled architecture.
See [issue-4-follow-through.md — Section 5](issue-4-follow-through.md#5-deferred-implementation-responsibilities-not-completed-architecture) for detailed triggers and completion conditions for `DEF-01`–`DEF-05`.
---
## Section 5 — Decision-Record Maintenance Protocol
All subsequent sessions working on Issue #4 must follow these eight rules:
1. **Explicit User Approval Required:** Never transition a decision from `PENDING_USER_REVIEW` without an explicit `USER_INPUT` turn authorizing one of the five valid dispositions:
- `ACCEPTED_AS_PROPOSED`
- `ACCEPTED_WITH_MODIFICATIONS`
- `REJECTED_IN_FAVOR_OF_ALTERNATIVE`
- `DEFERRED_WITH_JUSTIFICATION`
- `NOT_APPLICABLE_WITH_JUSTIFICATION`
2. **Record Modifications Faithfully:** When a decision is `ACCEPTED_WITH_MODIFICATIONS` or `REJECTED_IN_FAVOR_OF_ALTERNATIVE`, replace the summary with the exact user-approved commitment and record the modification delta rather than preserving the original `step 850` recommendation as if unchanged.
3. **Preserve Rejected Alternatives & Rationale:** When alternatives are rejected during review, concisely record the rejected option and why it was rejected so Stage 2 MADR drafting (`S2-01`–`S2-04`) has complete context.
4. **Incremental Dual-Artifact Updates:** Update both [issue-4-decision-ledger.md](issue-4-decision-ledger.md) and [issue-4-follow-through.md](issue-4-follow-through.md) immediately after each atomic decision is resolved, recording the transcript step or date of approval.
5. **Stable Identifiers:** Keep task IDs (`S1-01`–`S1-18`, `CW-01`, `S2-01`–`S2-06`, `S3-01`, `DEF-01`–`DEF-05`, `I9-01`) and decision IDs (`BL-01`–`BL-09`, `B2.1`–`B2.3`, `B2.4.1`–`E2`) stable across sessions.
6. **Immutability of Prior Meaning:** Never silently broaden, narrow, or reinterpret an earlier settled decision (`BL-01`–`BL-09`, `B2.1`–`B2.3`, or any newly resolved `S1-*` item). Any revision to a settled commitment requires an explicit user decision recorded with updated provenance.
7. **New Architectural Questions:** If a new architectural question surfaces during review, assign it a distinct identifier, evaluate whether it is a genuine prerequisite for any existing task, and record it explicitly rather than folding it silently into an existing item.
8. **Separation of Authority:** [issue-4-decision-ledger.md](issue-4-decision-ledger.md) is authoritative for **decision state, provenance, and rationale**; [issue-4-follow-through.md](issue-4-follow-through.md) is authoritative for **work status, dependencies, and execution sequencing**.
+130
View File
@@ -0,0 +1,130 @@
# Issue #4 Follow-Through Tracker
**Project:** `live-quiz`
**Scope:** Atomic Stage 1 decision resolution, Architectural Comprehension Walkthrough, Stage 2 ADR/architecture formalization, Stage 3 acceptance criteria, deferred implementation boundaries, and Issue #9 sequencing.
**Repository Baseline:** `main` @ `a4eeccf` ([docs/architecture.md](../docs/architecture.md), [docs/decisions/0001`–`0009](../docs/decisions/README.md)).
**Companion Artifact:** [issue-4-decision-ledger.md](issue-4-decision-ledger.md) (authoritative record of settled decisions, rationale, unapproved recommendations, and target ADR mappings).
> [!IMPORTANT]
> **Critical Sequencing Gate & Progress Maintenance Rules:**
> 1. **One Atomic Decision at a Time:** Update each atomic task (`S1-01`–`S1-17`) incrementally only after an explicit `USER_INPUT` turn resolves it. Never mark a parent or downstream milestone complete while any constituent atomic task remains unresolved.
> 2. **Preserve Approval Provenance:** Previously approved invariants (Section 0) are locked and are **not** re-opened during `S1-01`–`S1-17`; each atomic review evaluates *only* the unresolved delta listed in its deliverable.
> 3. **Walkthrough Gate:** Stage 1 closure (`S1-18`) and the **Architectural Comprehension Walkthrough (`CW-01`)** must be completed and explicitly approved by the user **before Stage 2 (`S2-*`) begins**.
---
## 0. Provenance Baseline: Verified Invariants vs. Unverified Recommendations
Direct audit of `transcript_full.jsonl` separates established user commitments from unapproved assistant recommendations:
### A. Verified Invariants (`USER_EXPLICIT` Provenance — Do Not Re-Ask)
- **Steps `820`, `825`, `827` (Handoff v2 & Baseline Corrections):**
- **`A`:** Immutable pair $A = (Q, R)$; modification of either member requires registering a new flat `assessment_id` issued by `learningctl`; `assessment_version` and version lineage eliminated; M:N Competency↔Objective and Assessment↔Objective links (Competency↔Assessment derived); Tutor owns pedagogical reassessment decisions, performs `AVAILABLE` artifact pre-flight prior to offering reassessment, and requires explicit learner consent before new registration or reassessment.
- **`B1`:** Registered $Q$ and $R$ embed `assessment_id`; $R$ carries `expected_questionnaire_hash`; $H_q = \operatorname{SHA256}(\operatorname{JCS}(Q))$ over the entire validated public questionnaire (including `assessment_id` when present); `expected_sha256` ([ADR-0007](../docs/decisions/0007-atomic-json-export-contract.md)) remains separate; standalone execution (`live-quiz start --questionnaire <path>`) is supported without `assessment_id` or `workspace_id`.
- **`C1` & Partial `C2`:** `live-quiz` commits a complete, self-contained questionnaire snapshot and initial execution metadata (`attempt_id`, optional `assessment_id`, $H_q$, optional `workspace_id`, `time_limit_ns`) to the attempt journal before learner access; recovery uses only the journal snapshot. No historical journal migration for missing snapshots is needed (no prior deployment).
- **Foundational `D` & `E` Invariants:**
- One OS-wide persistent encrypted Learning Registry (candidate: `SQLCipher`); workspaces are logical provenance resolved via nearest-ancestor `.learning-workspace` marker (`workspace_id`), rejecting Git root as workspace boundary.
- Separate host provisioning vs. `learningctl init` (`init` never silently recreates a missing global DB).
- `learningctl` (narrow domain CLI; black-box `learningctl.md`/`--help` contract) $\to$ private typed UDS IPC $\to$ `learning-registryd` (`learning-registry` OS account, systemd socket activation `Accept=no`, serialized requests).
- Non-TPM default host key protection (stored outside workspaces and separate from DB backups); `learning-registryd` owns Online Backup API encrypted-to-encrypted snapshots on schedule and before disruptive operations.
- Registration lifecycle (`REGISTERING` $\to$ `AVAILABLE` / `ABORTED`; only `AVAILABLE` is discoverable; allocated `assessment_id` never reused; registration failure $\neq$ attempt recovery).
- Temporary public-only questionnaire materialization outside workspace, deleted idempotently via `learningctl` after durable engine snapshot commit.
- Read-only `learningctl status` (`--json`, `--all`) run once at Tutor initialization (no polling); `learningctl` discovers candidate journals while `live-quiz` is sole authority for active vs. recoverable state without exposing private SQLite tables.
- Per-command `schema_version` in `learningctl --json` outputs (additive changes increment compatibly, breaking changes increment incompatibly, ignore unknown fields, reject unsupported breaking versions; exact `major.minor` string syntax remains unverified per step `827`).
- In registry-managed workflows, `attempt.json` is an intermediate artifact staged in a persistent non-workspace staging area (no TTL deletion) until the complete learning interaction (`attempt` + `evaluation` + `Tutor observations`) is committed in one atomic registry transaction (`CONSOLIDATED`) with an idempotent receipt. Standalone `attempt.json` exports remain untouched user files.
- Interaction states: `PENDING_DEBRIEF`, `DEFERRED`, `PENDING_CONSOLIDATION`, `CONSOLIDATED`, `ABANDONED`. Abandonment separates **append-only historical events** from **reversible current disposition** (`ABANDONED` $\to$ `DEFERRED` or new attempt on explicit learner request; hidden from default `status` and `--all`). Bounded debrief (1 consolidated report + ~1–3 follow-up turns) is a **facilitation guideline**, not a hard technical limit; interrupted debriefs preserve lightweight structured progress rather than full chat transcripts.
- **Step `829` (`B2.1` Accepted):** $H_q$ is computed over the original parsed JSON representation after strict validation (`extra="forbid"`, `strict=True`), never Pydantic's `model_dump()`.
- **Step `845` (`B2.2` Accepted):** Project-specific strict RFC 8785 JCS-compatible input profile scoped exclusively to `questionnaire.json` (UTF-8 without BOM, no lone surrogates or Unicode noncharacters, no Unicode normalization such as NFC/NFD performed with decoded code points preserved exactly and already-normalized NFC/NFD input accepted, no duplicate keys after unescaping, no non-finite constants, no float/exponent tokens at `parse_float` boundary, integers in $[-(2^{53}-1), +(2^{53}-1)]$; not transferred to `attempt.json`/`evaluation.json`).
- **Step `847` (`B2.3` Accepted):** 3-layer separation (strict Layer 1 parser $\to$ full RFC 8785 Layer 2 canonicalizer on Layer 1 structure $\to$ SHA-256), independent component implementations using established RFC 8785 libraries (no hand-written JCS, no shared first-party runtime package), verified by a mandatory raw-byte shared CI conformance suite.
- **Step `849` (`B2.4` Decomposition & Framing Constraints):** Decomposed `B2.4` into five subdecisions (`B2.4.1`–`B2.4.5`) with fixed constraints (`schema_version` inside $H_q$; changing it creates a new `assessment_id` without lineage; no in-place pair migration; cosmetic/internal changes do not require a new version).
### B. Unverified Recommendations Requiring Atomic Resolution (`Step 850`)
In `step 850`, a runaway assistant response simulated synthetic `<USER_REQUEST>` turns for `B2.4.1` through `E2`. None of the specific choices inside those 17 atomic items (`S1-01`–`S1-17` below) have `USER_EXPLICIT` approval yet.
---
## 1. Stage 1 Closure & Atomic Decision-Provenance Verification
> [!NOTE]
> **True Prerequisites, Soft Dependencies & Disposition Rules:**
> - **Genuine Prerequisites** lists *only* hard architectural prerequisites among open tasks (`None (Settled baseline only)` means the task has no open hard prerequisites and is ready immediately). Soft/informational implementation dependencies are labeled explicitly and do not block architectural resolution.
> - **Task IDs (`S1-01` $\to$ `S1-17`)** reflect our recommended sequential review order.
> - **Valid Atomic Dispositions:** Each atomic decision (`S1-01`–`S1-17`) closes when it receives an explicit `USER_INPUT` assigning one of: `ACCEPTED_AS_PROPOSED`, `ACCEPTED_WITH_MODIFICATIONS`, `REJECTED_IN_FAVOR_OF_ALTERNATIVE`, `DEFERRED_WITH_JUSTIFICATION`, or `NOT_APPLICABLE_WITH_JUSTIFICATION`.
| Task ID | Decision ID | Unresolved Architectural Commitment to Decide (Excluding Already-Settled Baseline) | Genuine Prerequisites | Explicit Completion Condition | Status | Resulting Artifact |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **`S1-01`** | **`B2.4.1`** | **Contract Version Scope:** Unified Questionnaire Contract Version governing (1) document structure/validation, (2) omitted optional-field defaults, (3) assessment-significant runtime execution semantics, and (4) questionnaire-defined response/export semantics (excluding cosmetic UI/refactoring); engine rejects unsupported versions (`S1-04`), journal inherits via `BL-04` snapshot without duplication, and `attempt.json` carries provenance (`DEF-01`). | None *(Settled `BL-03`, `B2.1`, step `849`)* | Explicit `USER_INPUT` recording a justified disposition for `B2.4.1`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-01`](issue-4-decision-ledger.md#s1-01--b241-contract-version-scope) |
| **`S1-02`** | **`B2.4.2`** | **Semantic Immutability Boundary:** Pillar-based normative-contract criterion requiring a new `schema_version` only when the normative questionnaire contract changes across `S1-01`'s 4 pillars (including resolving genuine spec ambiguity), while permitting cosmetic, accessibility, refactoring, equivalent renderer, and spec-compliance fixes within the same version; engine provenance kept separate from contract versioning. | `S1-01` (`B2.4.1`) | Explicit `USER_INPUT` recording a justified disposition for `B2.4.2`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-02`](issue-4-decision-ledger.md#s1-02--b242-semantic-immutability-boundary) |
| **`S1-03`** | **`B2.4.3`** | **Defaults & Explicit Configuration:** Explicit authoring required for all assessment-significant configuration (`schema_version`, timing policy, primitives/constraints, objective references, behavioral rules); omission allowed only with frozen *"absent / not applicable"* meaning (`assessment_id` in standalone mode, optional stimulus/grouping); schema must distinguish absent vs. `null` vs. `[]`, Pydantic must add no hidden behavior, $H_q$ stays raw parsed JSON, and exact fields + empty `objectives` (`[]`) policy defer to `DEF-01`/Stage 2. | `S1-01` (`B2.4.1`) | Explicit `USER_INPUT` recording a justified disposition for `B2.4.3`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-03`](issue-4-decision-ledger.md#s1-03--b243-defaults-and-explicit-configuration) |
| **`S1-04`** | **`B2.4.4`** | **Contract Version Support & Retirement:** Permanent spec freeze; major-release-only engine retirement after explicit deprecation notice; fail-closed `UNSUPPORTED_SCHEMA_VERSION` enforcement on `validate`/`start`/`recover`; in-flight journal preservation (recoverable via supporting engine, no silent discard/reinterpretation); historical Registry `AVAILABLE` retention separated from runtime executability (new retired registrations prevented via `S1-06`/`DEF-01`); advisory Tutor pre-flight; historical evaluation/audit independence; paused retired-version journal surfacing carried forward to `S1-13`/`DEF-01`. | `S1-01`, `S1-02` (`B2.4.1`–`B2.4.2`) | Explicit `USER_INPUT` recording a justified disposition for `B2.4.4`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-04`](issue-4-decision-ledger.md#s1-04--b244-contract-version-support-and-retirement) |
| **`S1-05`** | **`B2.4.5`** | **Migration & New Definitions Boundary:** Prohibit in-place pair rewrites and Registry-side `clone-upgrade` / derived-pair registration; cross-version replacements require fresh $(Q', R')$ authoring, pedagogical review, $Q'/R'$ alignment, full validation, `Tutor` consent, and a new lineage-free `assessment_id` linked via shared objectives. Authoring-side draft helpers remain allowed (unregistered drafts only); ordinary Registry DB migrations, serialization, validation, and export projections are excluded. | `S1-01` (`B2.4.1`, settled `BL-01`, `BL-02` & step `849`) | Explicit `USER_INPUT` recording a justified disposition for `B2.4.5`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-05`](issue-4-decision-ledger.md#s1-05--b245-migration-and-new-definitions-boundary) |
| **`S1-06`** | **`B2.5.1`** | **Boundary Hash Calculation & Verification Authority:** Independent $H_q$ calculation/recomputation at authoring (`live-quiz validate` after `REGISTERING` `assessment_id` allocation), registration (`learning-registryd` full pair validation + `H_q` + independent active `schema_version` policy), `live-quiz start` (persisted journal + `questionnaire_hash = H_q` on all managed/standalone `attempt.json` exports), and `live-quiz recover`; `(R, attempt.json)` correspondence in `quiz-evaluator`; full 4-way bundle correspondence at `learning-registryd` consolidation; zero crypto in `Tutor`; independent `B2.1`–`B2.3` implementations (`DEF-02`). | `BL-03`, `BL-04`, `B2.1`–`B2.3`, `S1-04` (`B2.4.4`) | Explicit `USER_INPUT` recording a justified disposition for `B2.5.1`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-06`](issue-4-decision-ledger.md#s1-06--b251-boundary-hash-calculation-and-verification-authority) |
| **`S1-07`** | **`B2.5.2`** | **Canonical Questionnaire Persistence Representation:** Persist Layer 2 RFC 8785 JCS canonical UTF-8 bytes alongside $H_q$ in both the Learning Registry (`AVAILABLE`) and `live-quiz` journal (`BL-04`), with direct byte copy at `BL-07` materialization; formatting/key order discarded while `B2.2` Unicode code points remain intact; `recover` still runs full `S1-06` validation/rehashing; SQLite `BLOB`/`TEXT` deferred to `DEF-01`/`DEF-05`; archival source-file provenance excluded from this contract. | `S1-06` (`B2.5.1`, settled `BL-04`, `BL-07`) | Explicit `USER_INPUT` recording a justified disposition for `B2.5.2`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-07`](issue-4-decision-ledger.md#s1-07--b252-canonical-questionnaire-persistence-representation) |
| **`S1-08`** | **`C2`** | **Legacy `attempt.json` (`assessment_version`) Policy:** Omit `assessment_version` from day one with fail-closed `extra="forbid"` rejection at `attempt.json` contract boundaries across `live-quiz`, `quiz-evaluator`, and `learningctl`, zero compatibility aliases/stripping shims, static files untouched, conforming fixtures required, and JSON Schema/Pydantic closed-object parity (`DEF-01`). | None *(Settled `BL-02`, `BL-05`)* | Explicit `USER_INPUT` recording a justified disposition for `C2`. | `ACCEPTED_AS_PROPOSED` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-08`](issue-4-decision-ledger.md#s1-08--c2-legacy-attemptjson-assessment_version-policy) |
| **`S1-09`** | **`D1a`** | **Registry Repository & Package Ownership:** Three-component monorepo inside `live-quiz` (`live-quiz`, `learning-registry`, `skills/`) with independent dependency/build/packaging boundaries, mechanically CI-enforced zero cross-package Python runtime imports (shared schemas & conformance vectors permitted), independent release/deployment lifecycles, and Stage 2 amendment/supersession of `ADR-0008`. | None *(Settled `BL-06`, `B2.3`, `ADR-0008`)* | Explicit `USER_INPUT` recording a justified disposition for `D1a`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-09`](issue-4-decision-ledger.md#s1-09--d1a-registry-repository-and-package-ownership) |
| **`S1-10`** | **`D1b`** | **Workspace Marker Edge Cases, Fail-Closed Taxonomy & Migration Trigger:** Idempotent same-dir `learningctl init` when validly registered; fail-closed `UNREGISTERED_WORKSPACE_MARKER` for unknown markers; 5-class DB/daemon failure taxonomy (`NOT_PROVISIONED`, `MISSING_OR_LOCKED`, `CORRUPT`, `MIGRATION_REQUIRED`, `UNSUPPORTED_SCHEMA`, CLI shape deferred to `DEF-04`); explicit out-of-band admin migration gated on verified encrypted backup (`S1-15`). | None *(Settled `BL-06`)* | Explicit `USER_INPUT` recording a justified disposition for `D1b`. | `ACCEPTED_AS_PROPOSED` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-10`](issue-4-decision-ledger.md#s1-10--d1b-workspace-marker-edge-cases-fail-closed-error-taxonomy--migration-trigger) |
| **`S1-11`** | **`D2a`** | **`REGISTERING` Status Visibility & `ABORTED` Tombstone Retention:** Surface `REGISTERING` in dedicated `incomplete_registrations` section of `learningctl status` (workspace-scoped default, `--all` cross-workspace, no TTL expiry); `Tutor` cannot auto-finalize or auto-abort; `ABORTED` hidden from learner `status`/`--all` while retaining permanent `assessment_id` reservation + admin audit metadata and purging unverified $Q$/$R$ drafts (`DEF-04`/`DEF-05`). | None *(Settled `BL-07`)* | Explicit `USER_INPUT` recording a justified disposition for `D2a`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-11`](issue-4-decision-ledger.md#s1-11--d2a-registering-status-visibility-and-aborted-tombstone-retention) |
| **`S1-12`** | **`D2b`** | **Startup-Commit Acknowledgment & Temp Questionnaire Cleanup Protocol:** Strict startup order (validate $\to$ durable `BL-04` journal commit $\to$ HTTP server readiness $\to$ flushed `SESSION_READY` NDJSON); exclusive NDJSON `stdout` (`stderr` diagnostics, continuous line draining, `ADR-0002`/`ADR-0007` reconciliation); temp-file owner idempotent cleanup independent of quiz completion & resilient to mid-startup commit-before-ready failure (`DEF-03`/`I9-01`). | None *(Hard prerequisite: settled `BL-04` / `C1` & `BL-07`; Soft / informational dependency: `S1-07` / `B2.5.2`)* | Explicit `USER_INPUT` recording a justified disposition for `D2b`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-12`](issue-4-decision-ledger.md#s1-12--d2b-startup-commit-acknowledgment-and-temporary-questionnaire-cleanup-protocol) |
| **`S1-13`** | **`D3a`** | **Read-Only Active-vs.-Recoverable Attempt Inspection Contract:** Continuous exclusive `flock` on `attempt-<attempt-id>.lock` (`start`/`recover`); read-only batch `live-quiz` CLI inspection (`BL-08`); non-creating, non-unlinking concurrency-safe lock probes (missing lock = anomaly); strict journal/sidecar filesystem non-mutation (`mode=ro` alone insufficient, no generic `immutable=1`); explicit `CLEANUP_PENDING`/orphan-sidecar anomaly reporting; retired-version recoverability vs. executability surfaced without execution-level validation (`S1-04`); CLI/SQLite/pruning details deferred to `DEF-03`. | None *(Settled `BL-04`, `BL-08`, `ADR-0006`)* | Explicit `USER_INPUT` recording a justified disposition for `D3a`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-13`](issue-4-decision-ledger.md#s1-13--d3a-read-only-active-vs-recoverable-attempt-inspection-contract) |
| **`S1-14`** | **`D3b`** | **Service-Boundary Delegation Cutoff & `schema_version` Format:** Standardize `learningctl --json` per-command `schema_version` on `"<major>.<minor>"` strings (explicitly independent of `questionnaire.json`'s `schema_version` in `S1-01`–`S1-04`); keep host provisioning, key escrow, DB migration, and restore out of agent-facing `learningctl`; delegate systemd/UDS/group/mode/wire/subcommand details to `DEF-04`/`DEF-05`. | `S1-09` (`D1a` repo boundary) | Explicit `USER_INPUT` recording a justified disposition for `D3b`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-14`](issue-4-decision-ledger.md#s1-14--d3b-service-boundary-delegation-cutoff-and-schema_version-format) |
| **`S1-15`** | **`D4`** | **Out-of-Band Key Escrow, Backup Verification Gate & Operational Delegation:** Privileged out-of-band key escrow/import separate from backups & `learningctl` (key loss $\neq$ DB corruption); stage $\to$ reopen & keyed engine/schema/metadata verification $\to$ atomic promotion (no full restore drill per promotion, never prune last verified point); key availability required for cryptographic recoverability; freshly verified snapshot before `S1-10` migrations; separate artifact integrity vs. cryptographic vs. operational recoverability; `SQLCipher` candidate only; primitives/escrow/rotation/retention/schedule/sync deferred to `DEF-05`. | `S1-10` (`D1b` fail-closed & pre-migration backup gate) | Explicit `USER_INPUT` recording a justified disposition for `D4`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-15`](issue-4-decision-ledger.md#s1-15--d4-out-of-band-key-escrow-backup-verification-gate--operational-delegation) |
| **`S1-16`** | **`E1`** | **Per-Execution Staging Slot Allocation & `--output` Destination Discipline:** Separate `interaction_id` (Registry staging identity) from `attempt_id` (engine identity); allocate one immutable `<staging_root>/<interaction_id>/attempt.json` slot per managed run (validated ID under controlled root, never arbitrary agent path, never reused/reassigned if unused); pass identical `--output` path on `start`/`recover`; keep Registry allocation separate from filesystem ownership (`DEF-04`/`DEF-05`); preserve `ADR-0007` & standalone rules unchanged. | None *(Settled `BL-04`, `BL-09`, `ADR-0007`)* | Explicit `USER_INPUT` recording a justified disposition for `E1`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-16`](issue-4-decision-ledger.md#s1-16--e1-per-execution-staging-slot-allocation-and---output-destination-discipline) |
| **`S1-17`** | **`E2`** | **Pre-Consolidation Storage Split, Pre-Debrief Status Reconciliation & `ABANDONED` Payload Retention:** Registry DB stores envelopes + append-only events; `E1` stores unconsolidated `attempt.json`, `evaluation.json`, and structured checkpoints (no transcripts) retained across `ABANDONED` (no auto-revival; `E1` encryption/ownership/permissions/backup resolved pre-implementation in `DEF-04`/`DEF-05`); read-only `status` reconciliation surfaces `attempt.json`-without-`evaluation.json` via non-persistent `awaiting_evaluation` (leaving `BL-09` 5 states intact, anomalies surfaced, zero mutation/evaluation); atomic `CONSOLIDATED` + receipt bound to normalized `(attempt, evaluation, Tutor observations)` correspondence (`S1-06`, fail closed on mismatch) before `E1` cleanup; normalization/digest/schemas deferred to `DEF-04`/`DEF-05`. | `S1-06` (`B2.5.1`), `S1-16` (`E1`) *(plus settled `BL-09`; no hard prerequisite on `S1-07`/`B2.5.2`)* | Explicit `USER_INPUT` recording a justified disposition for `E2`. | `ACCEPTED_WITH_MODIFICATIONS` (`USER_EXPLICIT`, `2026-11-15`) | [Ledger §3 — `S1-17`](issue-4-decision-ledger.md#s1-17--e2-pre-consolidation-storage-split-pre-debrief-status-reconciliation--abandoned-payload-retention) |
| **`S1-18`** | **Closure** | **Verified Stage 1 Decision Closure Report:** Reconciled ledger of `A`–`E2` with verified `USER_EXPLICIT` provenance, explicit dispositions (`2` `ACCEPTED_AS_PROPOSED`, `15` `ACCEPTED_WITH_MODIFICATIONS`), dependency map, and deferred-items boundary (`DEF-01`–`DEF-05`, `I9-01`). | `S1-01`–`S1-17` | Every atomic decision (`S1-01`–`S1-17`) has received one explicit disposition (`ACCEPTED_AS_PROPOSED`, `ACCEPTED_WITH_MODIFICATIONS`, `REJECTED_IN_FAVOR_OF_ALTERNATIVE`, `DEFERRED_WITH_JUSTIFICATION`, or `NOT_APPLICABLE_WITH_JUSTIFICATION`) backed by explicit user approval or user-authorized deferral, with provenance verified in [issue-4-decision-ledger.md](issue-4-decision-ledger.md). | `COMPLETED` (`USER_EXPLICIT`, `2026-11-15`) | [issue-4-decision-ledger.md](issue-4-decision-ledger.md) |
---
## 2. Architectural Comprehension Walkthrough (Hard Sequencing Gate Before Stage 2)
> [!WARNING]
> **Hard Gate:** `CW-01` (`CW-01a`–`CW-01e` + supporting system map) must be completed and receive explicit user approval before any Stage 2 (`S2-*`) task begins. The supporting system map is an explanatory walkthrough aid, explicitly distinct from authoritative repository documentation ([docs/architecture.md](../docs/architecture.md)).
| Task ID | Expected Deliverable | Dependencies | Relevant Decision IDs | Explicit Completion Condition | Status | Resulting Artifact |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **`CW-01`** | **Complete Architectural Comprehension Walkthrough & Supporting System Map** covering five required subjects:<br>• **`CW-01a`:** System context and component responsibilities (`tutor`, `quiz-designer`, `learning-objectives`, `quiz-evaluator`, `learningctl`, `learning-registryd`, `live-quiz`).<br>• **`CW-01b`:** Data flows and integration contracts (`questionnaire.json`, `rubric.json`, `attempt.json`, `evaluation.json`, JCS hashing, approved startup acknowledgment, read-only attempt inspection, consolidation receipts).<br>• **`CW-01c`:** Persistence domains and artifact lifecycles (global encrypted Learning Registry vs. ephemeral attempt SQLite journals vs. short-lived materialized questionnaires vs. approved pre-consolidation staging/persistence topology vs. standalone exports).<br>• **`CW-01d`:** Trust boundaries and security assumptions (blind pass, runtime rubric exclusion, `learning-registry` OS service boundary, non-TPM key isolation, black-box CLI guardrail, formative host threat model).<br>• **`CW-01e`:** Failure scenarios, recovery, and consistency guarantees (crash at every registration, startup, execution, export, evaluation, debrief, migration, and backup boundary). | `S1-18` | `A`–`E2`, Issues #1–#8 | All five walkthrough subjects and the supporting non-normative system map are reviewed with the user, and the user gives **explicit approval** to proceed to Stage 2. | `COMPLETED` (`USER_EXPLICIT`, 2026-11-16; `CW-01a`–`CW-01e` closed and map approved) | [Supporting System Map](../.internal/cw-01-supporting-system-map.md) |
---
## 3. Stage 2 — ADR Formalization & Architecture Documentation Reconciliation
> [!NOTE]
> **Conditionality Rule:** Stage 2 deliverables (`S2-01`–`S2-06`) must not pre-encode unapproved `step 850` recommendations. Each Stage 2 artifact must incorporate the **actual user-approved Stage 1 dispositions** (including `ACCEPTED_WITH_MODIFICATIONS` and `REJECTED_IN_FAVOR_OF_ALTERNATIVE` outcomes) from [issue-4-decision-ledger.md](issue-4-decision-ledger.md) and preserve all deferred items (`DEF-01`–`DEF-05` and any Stage 1 `DEFERRED_WITH_JUSTIFICATION` dispositions) as unresolved.
| Task ID | Expected Deliverable | Dependencies | Relevant Decision IDs | Explicit Completion Condition | Status | Resulting Artifact |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **`S2-01`** | **ADR Allocation & Scope Plan:** Determine exact new ADR count, numbering (`0010`+ against [docs/decisions/README.md](../docs/decisions/README.md)), and repository placement boundary based on the user-approved Stage 1 dispositions (especially `D1a` / `S1-09` and `E2` / `S1-17`), preserving deferred matters as unresolved. | `CW-01` *(Hard Gate)*, `S1-09`, `S1-17` | `A`–`E2` | User approves the exact list of amended ADRs and new ADR titles/numbers before drafting begins. | `READY` (CW-01 approved; S2-01 not started) | Pending |
| **`S2-02`** | **Amend Engine & Execution ADRs (`0002`, `0004`, `0005`, `0006`, `0007`):** Reconcile engine lifecycle (`0002`), input/rubric isolation & contract evolution (`0004`, `0005`), journal snapshot & active-vs.-recoverable inspection (`0006`), and identity/hash/export contracts (`0007`) strictly with the settled baseline (`BL-01`–`BL-05`, `BL-07`–`BL-08`, `B2.1`–`B2.3`) and the **actual user-approved Stage 1 dispositions** (including approved modifications or alternatives for `B2.4.*`, `B2.5.*`, `C2`, `D2b`, `D3a`, `E1`), preserving deferred matters (`DEF-01`–`DEF-03`, `DEF-05`) as unresolved. | `S2-01` | `A`, `B1`–`B2.5.2`, `C1`–`C2`, `D2b`, `D3a`, `E1` | Amended MADRs drafted, verified against approved ledger dispositions and free of regressions against Issues #1–3 & #5–8, and approved by user. | **Blocked** (on `S2-01`) | `../docs/decisions/0002-*.md`, `0004-*.md`, `0005-*.md`, `0006-*.md`, `0007-*.md` |
| **`S2-03`** | **Amend Repository & Reference Skills ADRs (`0008`, `0009`):** Reconcile component/repository ownership (`0008`) and reference skill / Tutor-registry integration (`0009`) strictly with the settled baseline (`BL-01`–`BL-02`, `BL-06`–`BL-09`) and the **actual user-approved Stage 1 dispositions** (including approved modifications or alternatives for `D1a`, `D2a`, `D3b`, `E2`), preserving deferred matters (`DEF-03`–`DEF-05`) as unresolved. | `S2-01` | `A`, `D1a`, `D2a`, `D3b`, `E2` | Amended `ADR-0008` and `ADR-0009` drafted, verified against approved ledger dispositions, and approved by user. | **Blocked** (on `S2-01`) | `../docs/decisions/0008-*.md`, `../docs/decisions/0009-*.md` |
| **`S2-04`** | **Author New MADR(s) (`0010`+) & Update ADR Index:** Formalize the new ADR(s) allocated in `S2-01` from the actual user-approved Stage 1 dispositions (recording accepted choices, selected alternatives, rationales, and explicit boundaries leaving deferred matters unresolved) and update [docs/decisions/README.md](../docs/decisions/README.md). | `S2-01` | `A`–`E2` | New MADR file(s) and `../docs/decisions/README.md` index authored and approved. | **Blocked** (on `S2-01`) | `../docs/decisions/0010-*.md` (+ any additional allocated MADR), `../docs/decisions/README.md` |
| **`S2-05`** | **Reconcile `docs/architecture.md`:** Update system diagram, component table, contract topologies, persistence lifecycles, canonicalization/versioning rules, and interaction/debrief workflows to match the approved Stage 1 dispositions and Stage 2 ADRs; remove stale `assessment_version` and unspecified-registry text while preserving deferred matters as unresolved. | `S2-02`–`S2-04` | `A`–`E2` | [docs/architecture.md](../docs/architecture.md) updated and aligned with `ADR-0001`–`0010+`. | **Blocked** (on `S2-02`–`S2-04`) | `../docs/architecture.md` |
| **`S2-06`** | **Cross-Document Consistency Verification:** Audit [docs/architecture.md](../docs/architecture.md), `../docs/decisions/0001`–`0010+`, and [docs/decisions/README.md](../docs/decisions/README.md) for terminology, invariant, exit-code, ledger-disposition fidelity, deferred-boundary preservation, and boundary consistency across Issues #1–#8. | `S2-05` | Issues #1–#8, `A`–`E2` | Verification check passes with zero cross-document contradictions and user approves Stage 2 completion. | **Blocked** (on `S2-05`) | Pending (Stage 2 Verification Report & Git Commit) |
---
## 4. Stage 3 — Acceptance Criteria
| Task ID | Expected Deliverable | Dependencies | Relevant Decision IDs | Explicit Completion Condition | Status | Resulting Artifact |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **`S3-01`** | **Derive Verifiable Acceptance Criteria:** Translate reconciled `docs/architecture.md` and `ADR-0001`–`0010+` into falsifiable acceptance criteria (preserving the boundary between architectural guarantees and deferred implementation details). | `S2-06` | Issues #1–#8, `A`–`E2` | Acceptance criteria document authored, verified traceable to ADRs, and approved by user. | **Blocked** (on `S2-06`) | `../docs/acceptance-framework.md` (planned) |
---
## 5. Deferred Implementation Responsibilities (Not Completed Architecture)
These items remain **explicitly deferred** to post-Stage-3 technical design and implementation (never counted as completed architectural work):
| Task ID | Expected Deliverable | Trigger / Prerequisite | Relevant Decision IDs | Explicit Completion Condition | Status | Resulting Artifact |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **`DEF-01`** | **JSON Schemas & Strict Pydantic Models:** Exact field names and `.schema.json` specs for `questionnaire.json`, `rubric.json`, `attempt.json` (incl. contract-version provenance field spelling per resolved `B2.4.1`), and `evaluation.json`, with recursive `extra="forbid"`, `strict=True`, and negative nesting tests. | Post-`S3-01` (Implementation kickoff) | `B1`, `B2.1`, `B2.2`, `B2.4.1`–`B2.4.3`, `C2` | Schemas and models pass unit + negative validation suites. | **Deferred** | Pending |
| **`DEF-02`** | **RFC 8785 Library Selection & Shared Conformance Suite:** Choose Python JCS package (`rfc8785`/`jcs` candidates) and assemble raw-byte CI conformance test vectors (official RFC 8785 vectors + `B2.2` negative parser vectors + `attempt.json` float vectors). | Post-`S3-01` | `B2.2`, `B2.3` | CI conformance suite passes identically across `live-quiz` and registry implementations. | **Deferred** | Pending |
| **`DEF-03`** | **`live-quiz` CLI Interface & Output Schemas:** Finalize subcommand spellings, flags, and JSON/output schemas for `live-quiz validate`, startup readiness acknowledgment (`D2b`), and read-only attempt inspection (`D3a`); author `live-quiz.md`. | Post-`S3-01` (and `S1-12`, `S1-13`) | `B2.5.1`, `D2b`, `D3a` | `live-quiz.md` and `--help` contracts implemented and integration-tested. | **Deferred** | Pending (`live-quiz.md`) |
| **`DEF-04`** | **`learningctl` Domain CLI Grammar & JSON Schemas:** Finalize `.learning-workspace` optional metadata fields, command/flag spellings (`assessment`, `interaction`, `backup`, reconsideration), and CLI `schema_version` / JSON schemas (`status`, consolidation receipt, structured debrief checkpoint); author `learningctl.md`. | Post-`S3-01` (and `S1-10`–`S1-17`) | `D1b`, `D2a`, `D3b`, `E1`, `E2` | `learningctl.md` and `--help` contracts implemented and validated against `learning-registryd`. | **Deferred** | Pending (`learningctl.md`) |
| **`DEF-05`** | **Host Daemon Packaging, Security & Backup Operations:** Finalize `learning-registryd` systemd `.socket`/`.service` units, UDS path/group/modes, private IPC wire framing, temp/staging XDG paths, encrypted DB driver (`SQLCipher` candidate), concrete backup integrity-check mechanism, credential storage (`LoadCredentialEncrypted=` vs. keyfile), admin key-escrow/migrate/restore tools, backup timer schedule, retention thresholds, and external sync target. | Post-`S3-01` (and `S1-09`, `S1-14`, `S1-15`) | `D1a`, `D1b`, `D2b`, `D3b`, `D4`, `E1` | Host installer, systemd units, and backup/restore drills verified in target Linux/NixOS environment. | **Deferred** | Pending |
---
## 6. Issue #9 — Companion Skill Portability & Integration Contracts (Separate Milestone)
| Task ID | Expected Deliverable | Dependencies | Relevant Decision IDs | Explicit Completion Condition | Status | Resulting Artifact |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **`I9-01`** | **Original Issue #9 Discovery, ADR Reconciliation & Acceptance Criteria:** Resolve companion skill portability, single-agent vs. subagent execution fallbacks, `learningctl.md` / `live-quiz.md` black-box operating contracts, host-path neutrality, and optional Tutor facilitation UX guidance. | `S2-06` (or explicit user schedule directive) | Issue #9, `D1a`, `D3b`, `E2`, [ADR-0008](../docs/decisions/0008-two-product-repository-architecture.md), [ADR-0009](../docs/decisions/0009-modular-portable-reference-skills.md) | Issue #9 Stage 1 $\to$ Stage 2 $\to$ Stage 3 completed and explicitly approved by user. | **Open (Separate Milestone)** | Pending |