Memoria rewrite scaffold #
The implementation specification is ../spec/rewrite-src-new.md.
It is the source of truth for future tickets; existing scaffold declarations may
need alignment before implementation (see specification section 16).
This tree is independent of ../src. It does not import the existing application
and is not yet a replacement CLI. The scaffold uses Odin's core:/base: libraries;
system libcurl via vendor:curl is the permitted HTTPS dependency for the rewrite.
Progress and ticket handoffs: ../spec/rewrite-progress.md.
WP12's independent catalog service and interactive model/
variant selection are implemented/tested offline. Model pickers lazily acquire a
catalog consumer; trusted root policy, not catalog prices/presence, authorizes
execution. The opt-in production root remains free-router-only, with no paid fallback.
WP0 contracts, WP1 canonical conversation, WP2 headless reducer, WP3 worker executor,
WP4 real native/process backends and five built-in tools, WP5 HTTP/SSE, WP6 bounded
Chat Completions/Responses codecs, WP7 private config/auth/noninteractive CLI,
WP8 actual OpenRouter adapter/isolated opt-in headless binary, and WP9 private
canonical snapshots/writer leases/headless session workflows, and WP10 Darwin
terminal/decoder, owned UTF-8 editor/history/width and pure key/confirmation policy
are implemented. WP11 adds opt-in coordinated plain-text chat and durable session
workflows; authenticated live acceptance remains pending, not live-validated.
Canonical APIs and handoff are documented in
conversation/README.md.
Reducer/action/ownership contracts: agent/README.md.
Validated toolchains: prior milestones Odin dev-2026-09:a2fb372b7, WP7
dev-2026-10:84bc3fc21, on macOS. Development validation
uses Python 3.9+ stdlib only. WP5 uses vendor:curl and macOS system libcurl;
TLS verification is always enabled. Exact link/lifecycle/budget contracts:
http/README.md.
Protocol ownership/options/supported subsets:
protocol/wire/README.md,
protocol/chatcompletions/README.md,
protocol/responses/README.md.
Codecs verify complete response/transport EOF before emitting any tool batch,
preserve provenance-compatible continuation, and never execute retries. Synthetic
localhost headless tests exercise real transport/codecs/workers/sequential tools;
they do not establish live provider/auth support. H08-H09 retry execution is pending.
Review regressions guard cancellation callbacks, verify NUL-free completed call
identifiers and every supplied Chat type, and never infer context overflow from 413.
# Set to an existing approved temporary directory; no binaries enter src.new.
python3 -B src.new/scripts/validate.py --out-dir "$APPROVED_TEMP_DIR"
The runner checks dependency rules, discovers every *_test.odin package,
runs tests with Odin memory tracking and failure on leaks/bad frees,
checks/builds/runs the status CLI and checks/builds the opt-in headless binary (help
only, never live). It also supplies an offline loopback TLS peer
with a public synthetic self-signed certificate for verification-rejection tests;
no external network or provider credentials are needed. It explicitly supplies
an isolated --config-root, workspace and HOME/XDG/key environment for CLI checks;
never run a storage-aware validation CLI against a real account.
Preserved WP7 review validation (2026-10-07): 301 Odin + 15 Python tests, strict
memory checks, imports and isolated CLI check/build/status pass. Environment scalar
injection and stdin truncation regressions are covered; prior records remain in
progress.
WP8 initial validation (2026-10-07): 320 Odin + 18 Python tests, same strict
tracking/toolchain, both CLI check/build/help/status and import rules pass. Real
localhost provider-worker-native-fixture follow-up is tested. Authenticated live
acceptance is deliberately unrun and remains a WP8 completion blocker.
WP8 review validation (2026-10-07): 325 Odin + 18 Python tests after five
Retry-After-date/null-late-accounting regressions (9 adapter, 33 Chat codec and 4
headless OpenRouter tests). Full strict checks/builds/help/status and
git diff --check pass; no authenticated/live API calls.
Manual odin test/build/run commands must use -out:<approved-temp-path>.
Preserved final WP8 free-router review baseline: 328 Odin +18 Python tests;
exact regression history remains in progress.
WP9 pre-review validation (2026-10-08): 381 Odin +24 Python tests, same strict toolchain/
tracking, imports/DAG and isolated command checks pass after the last code edit.
Private v1 schema, writer leases/revision gates/listing/staging and headless new/
resume/recovery workflows: sessionstore,
app. No interactive-ready, full WP18 or authenticated WP8 claim.
WP9 narrow independent-review fixes (2026-10-08): 387 Odin +24 Python tests
pass under the full strict validator after the latest edits. Intent authority/
durable presence is required again before candidate rename; listing vector growth
uses the explicit allocator. Added marker refusal/presync/cleanup-retry and
attached-executor app save-only retry/rebinding/shutdown regressions. Prior counts
above remain historical evidence; OpenRouter free-router protections are unchanged.
odin check src.new/cmd/memoria is output-free and does not support -out.
WP10 foundations and exact lifecycle/ownership/caps/subsets:
terminal, editor,
width, key policy. The validator also
checks/builds a standalone offline terminal fixture and runs actual isolated PTY
subprocess tests (raw restoration, signals, resize, paste, partial startup failures,
write failure, disappearance and suspend/reacquire). No actual user TTY is touched.
At WP10, status/login/setup stayed non-TTY usable with no raw startup in
cmd/memoria; WP11 now adds only explicitly opted-in chat startup. The WP10 fixture
alone did not establish an interactive-ready CLI.
WP10 strict validation (2026-10-08): 425 Odin +34 Python tests, preserving the
387/24 baseline. Added15 terminal,10 editor,4 width,9 policy Odin tests and1 checker/
9 actual PTY Python tests. Full tracked-memory validator passes; independent review
pending, no interactive wiring/live provider acceptance or old storage changes.
WP10 narrow review corrections (2026-10-08): 431 Odin +35 Python tests under
the final strict validator. Mixed Kitty modifiers no longer become cancellation;
releases use parsed metadata; completed-byte Kitty ownership/CAN cancellation
protect parent keyboard stacks; timed-out recognized paste headers safely drain
late payload. Added5 terminal +1 composition Odin tests and1 actual PTY pop-retry
test. Prior425/34 evidence retained; WP11 remains pending.
WP11 validation (2026-10-08): 451 Odin +46 Python tests, strict memory checks, imports/DAG, CLI/helper checks/builds, isolated help/status and actual PTY tests. The20 new Odin tests cover async workflows/allocations, UI admission/cancellation, readonly viewport, control sanitization and narrow writer controls. Added10 actual interactive PTY/root-startup tests and1 non-TTY/consent CLI test. Earlier431/35 remains historical evidence. No authenticated/live request was made.
WP12a validation (2026-10-08): 483 Odin +46 Python tests with strict memory, imports/DAG, command checks/builds, isolated CLI and existing actual PTYs. Adds30 catalog/cache/worker/localhost tests plus2 bulk-parser/private-storage regressions. No external remote catalog or authenticated model request made in that milestone. WP12b validation (2026-10-08): 498 Odin +52 Python tests, strict memory, imports/ DAG, command checks/builds, isolated CLI and actual PTYs. Adds15 selection/ownership/ allocation tests and6 PTYs. Exact API/lifetime: app/INTERACTIVE.md. WP13 validation (2026-10-08): 508 Odin +76 Python tests, strict memory/import DAG, command checks/builds, isolated CLI and actual PTYs. Adds10 tracked host-editor/app tests and24 controlling-PTY editor cases; no external calls or real credential access.
Diagnostic commands provide noninteractive setup: default status, help, config-check, explicit user selection save, API-key stdin login, Codex device login and refresh. Exact flags/schemas/env/lifetimes: config, private host storage, auth, provider setup metadata. Status/check/help never write defaults; real auth requests occur only on explicit login/refresh commands. It explicitly constructs allow-all native/ process and root-owned HTTP services, registers list/read/write/edit/bash, prints the startup warning and discoverable profile/status, but diagnostic commands do not run an agent/tools. Explicit WP11 chat binds the real OpenRouter adapter and private WP9 session backend:
# Build into approved temporary storage; keep legacy src untouched.
odin build src.new/cmd/memoria -out:"$APPROVED_TEMP_DIR/memoria-new"
# Requires a configured key, usable input/output TTYs, and explicit network consent.
"$APPROVED_TEMP_DIR/memoria-new" --chat --accept-network
This starts a new durable session, supports plain streaming, draft/history/queue,
Ctrl-C confirmation, Ctrl-R save-only retry, local completion and new/resume pickers.
It selects openrouter/free only, never silently replacing a saved other selection;
no paid fallback. No model request occurs until an ordinary prompt is submitted;
opening a model picker may fetch public models.dev metadata asynchronously. Exact
ownership/caps/commands/non-goals: app/INTERACTIVE.md.
Model/variant acceptance changes next-turn selection and saves user config off-loop;
active adapter/protocol/capabilities and provenance stay captured. Ctrl-X e launches
root-captured $EDITOR/vi with private temp and foreground terminal handoff while
active workers drain and queued turns wait. Host-editor policy.
Semantic rendering, skills and compaction remain WP14/15/18. Real tools use explicit
operation boundaries and provide no filesystem/network isolation. Same-user
files/credentials and inherited exported environment secrets are exposed. A later
restricted profile must replace services without rewriting the engine or silently
falling back. The interactive banner warns of unrestricted access; full release
readiness and all-product lifecycle requirements remain WP19.
Packages #
| Package | Owns | Must not own |
|---|---|---|
cmd/memoria |
Process entry and concrete dependency wiring | Agent transitions or rendering |
app |
User workflows and service composition | Provider protocols or component internals |
agent |
Turn states, typed actions/events, submitted-prompt queue | Terminal state, disk storage |
execution |
Headless owner, owned bounded worker mailboxes/snapshots, cancellation/join/checkpoints | Keybindings, ANSI, concrete tools |
conversation |
Canonical content and session data | ANSI, wire formats, runtime handles |
sessionstore |
Versioned durable snapshots | Automatic execution on resume |
provider |
Normalized model requests/events | Concrete authentication, tool execution |
providers/* |
Endpoints, capabilities, provider quirks | Shared wire-protocol implementation |
protocol/* |
Request encoding and wire-event interpretation | Credentials or UI |
http |
Transport and SSE framing | Model semantics |
auth |
Secrets and authentication flows | Public configuration |
config |
Non-secret settings | Mutable active access policy |
catalog (planned) |
Normalized model metadata/cache service | Picker state |
instructions (minimal WP8) |
Frozen headless instructions; discovery/skills still WP15 | Authorization or HTTP |
tool |
Definitions, registration, execution contract | Concrete file/shell operations |
tools/* |
Individual tool schemas and implementations | Terminal writes |
skills |
Discovery, metadata, instruction loading | Tool registration or UI |
subagent (planned) |
Isolated child runtime composition | Duplicated agent loop |
workspace (planned) |
Bounded ignore-aware path indexing | Draft/picker internals |
access |
Replaceable native access/authorization boundary | Approval prompts or implicit nil-meaning-allow |
sandbox |
Replaceable subprocess backend; initially explicit allow-all | Silent downgrade from a future restricted profile |
terminal |
Raw mode, key decoding, ANSI writer | Application keybindings |
ui/chat |
Frontend modes and keybindings | Agent execution |
ui/editor |
Draft buffer and cursor | Models, sessions, loading state |
ui/picker |
Generic filtering and selection | Catalog fetching |
ui/transcript |
Conversation presentation | Persisted conversation content |
ui/layout |
Styled spans, wrapping, cell measurement | ANSI or provider events |
markdown |
Semantic Markdown parsing | Terminal escape codes |
highlight |
Code tokenization | Provider/session state |
Directories containing only a README are planned implementation boundaries, not
fake working backends. The contracts in .odin files are deliberately small and
can evolve with the first headless vertical slice.
Dependency rules #
cmd/memoria -> app + concrete adapters
app -> execution + ui/chat + sessionstore + config/profiles + provider
execution -> agent + conversation + provider + tool + sessionstore
agent -> conversation + provider + tool
provider -> conversation
tool -> conversation + access + sandbox
sessionstore -> conversation + protocol/wire + config/storage (host authority only)
ui/chat -> terminal + ui/editor + ui/picker
ui/editor -> ui/layout (pure width only)
terminal, ui/layout -> Odin libraries only (OS APIs restricted to terminal backend)
ui/transcript -> conversation + markdown + highlight + ui/layout
markdown, highlight -> ui/layout
concrete providers -> provider + protocol + http + auth
concrete tools -> tool + access + sandbox/skills
subagent (planned) -> execution + instructions + tool
tools/task (planned) -> subagent + tool
WP8 additionally has providers/openrouter -> config/profiles for explicit
metadata/capability contracts; instructions -> conversation + tool for a bounded
definition/profile snapshot; cmd/openrouter-headless -> execution + concrete OpenRouter + tools/fixture + instructions. No engine/provider enum or forbidden
codec/tools imports. The new command is opt-in only; normal status/help/setup flags
retain their behavior and never invoke a model. See adapter API/source/wire/live
acceptance instructions. Offline validation also
checks/builds the dedicated binary and runs help only. H08-H09 retries remain an
explicit execution gap; WP12 catalog, WP15 discovery and all interactive/frontend
readiness remain pending. WP9 persistence is separate explicit composition, not
enabled by this acceptance binary. Real native fixture tools are
registration-restricted, not an OS sandbox. No automatic stored-key/live call.
Only the entry point and integration tests import app. Directory nesting does not imply
Odin package visibility or inheritance; dependencies are explicit imports.
Odin package names must also be unique in a build: the terminal directory uses
package terminal_io to avoid colliding with core:terminal (used by testing).
Ownership and concurrency #
- Allocating APIs take an allocator. Owners expose
destroyoperations. - Conversation append clones borrowed input into session-owned storage.
- The prompt queue owns submitted text. Taking a prompt transfers ownership.
- Registries borrow definition strings and adapter state; the composition root keeps them alive and tears them down after users stop.
- Provider/tool sinks borrow payloads only for the callback. Any asynchronous consumer must clone into owned storage before returning.
- Agent actions borrow request data for immediate dispatch. Workers must own snapshots, never retain a pointer to a mutable session or draft.
- One coordinator owns agent, session, and frontend state. Workers send owned, bounded completion messages; they do not mutate those states or write stdout.
- Every operation carries a turn/request identity. Reject stale completions.
- Only the terminal frontend writes stdout; diagnostics go elsewhere.
The detailed WP3 API/lifetime/gate handoff is in execution/README.md.
Actual threads exercise owned snapshots, asynchronous envelopes and checkpoint dispatch
with injected fake services. Reducer stale/duplicate rejection now also releases owned
messages. WP4's native and process services
now execute real isolated fixture operations through the same headless workers;
WP5's transport/SSE now runs real offline socket fixtures independently of model
semantics; WP7 independently persists public config/private credentials and tests
actual auth wire/refresh with injected transport and localhost. WP9 now tests actual
durable sessions and headless workflows. Logs/catalogs, authenticated live acceptance
and interactive execution remain future work.
Behavior decisions #
- Draft editing and submitted prompts are separate. Submitted prompts are FIFO subsequent turns, not injection into an active request. Choose model/variant when a queued turn begins. Queue owns at most 32 prompts/2 MiB total with a 64 KiB UTF-8 prompt cap; refusal never changes caller input. A take transfers ownership; clear releases entries and reports the discard count. The reducer clears the queue on confirmed cancellation or terminal failure and advances normally only after the end checkpoint succeeds.
- Ctrl-A/E move within a line. Ctrl-X enters prefix mode; e/m/t request the editor, model picker, or variant picker; q requests quit. Unknown combinations are consumed.
- While work is active, Ctrl-C asks for confirmation; a second within two seconds
interrupts, preserves the draft, and clears queued prompts. Once idle, Ctrl-C
clears a nonempty draft, otherwise requests exit. The keymap now forwards
Interruptintent without altering draft/picker state. WP10 supplies stable-ID confirmation/returned cancellation intents; WP11 application effects and cancel/checkpoint/drain/signal startup/shutdown wiring remain pending. - Resume restores conversation, not in-flight execution. Never rerun interrupted tools automatically.
- Canonical text is never reconstructed from ANSI output. Sanitize untrusted control sequences at the display boundary.
- Streaming presentation keeps completed blocks stable and reparses the provisional tail. The spec defines bounded table buffering and plain fallback.
- Initial native file/skill/shell backends explicitly allow all filesystem/network operations. Missing backend is an error. Future restricted profiles are immutable for a run and must never fall back to allow-all after setup failure.
- Full current feature coverage is required, including subagents, compaction, file mentions, project instructions, catalog caching, reasoning and usage.
- macOS first, independent rewrite storage, and JS/TS/JSON highlighting.
- Editor/model/variant workflows work during active turns; captured active-turn selection remains unchanged. Queue clears on cancellation/terminal failure.
Next work #
WP1 owns canonical timestamps/outcomes, captured selection, reasoning/tool states,
usage, provenance-safe projection and restart recovery. WP2 supplies the reducer,
WP3 worker infrastructure, WP4 actual backends/tools, WP5 HTTP/SSE, WP6 codecs,
and WP7 config/auth/CLI; WP8 actual OpenRouter/offline headless capability, WP9
headless durable store/workflows and WP10 terminal/editor/policy foundations are
implemented at their documented boundaries. WP11 interactive chat and WP12 catalog/
selection/persistence and WP13 external editor are also implemented. Next is WP14
semantic rendering, separately scoped; current rendering stays bounded plain text
with incremental control sanitization. Authenticated WP8
free-router acceptance is still pending explicit network/key approval; H08-H09
model retries/replay protection remain explicit request-execution work. No paid
fallback/default change, credentials or live validation is implied by these tickets.
Follow spec section 15 dependencies, not an
old refactoring plan. tests remains the scaffold import suite; package tests
and tests/headless separately exercise ownership/limits and injected contracts.
No contract-only requirement is marked as a completed user-facing feature.