diff --git a/AGENTS.md b/AGENTS.md index 11a92f8..fa08b82 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -117,5 +117,15 @@ When the user requests a durable behavior change, record it here or in the relev | Path | Scope | |---|---| -| [docs/AGENTS.md](docs/AGENTS.md) | Durable documentation: ADRs and their numbering, format, and status rules | +| [docs/AGENTS.md](docs/AGENTS.md) | Durable documentation: ADRs (numbering, format, status) and session logs under `docs/devlog/` (one log per unit of work; `INDEX.md` is the source of truth) | | [tests/AGENTS.md](tests/AGENTS.md) | Offline test suite: jiti aliasing to host-package stubs, fixtures, and what the tests pin | + +## Session Logs + +Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Full history: [`docs/devlog/INDEX.md`](docs/devlog/INDEX.md). The 10 most recent: + + +| Date | Log | +|------|-----| +| 2026-11-25 | [20261125-fresh-context-audit-rounds-1-5_log.md](docs/devlog/20261125-fresh-context-audit-rounds-1-5_log.md) | + diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 211b840..8a27c58 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -2,13 +2,14 @@ ## Purpose -Durable documentation that explains *why* the project is shaped the way it is. Currently: architecture decision records under `docs/adr/`. +Durable documentation that explains *why* the project is shaped the way it is: architecture decision records under `docs/adr/`, plus the session-log record under `docs/devlog/`. ## Ownership - This doc owns the ADR numbering scheme, file format, and status rules. - The root AGENTS.md owns repo-wide rules and the top-level Child DOX Index. - Each ADR owns its single decision; nothing outside `docs/` is owned from here. +- `docs/devlog/` holds session logs written by the write-log skill: one `YYYYMMDD-_log.md` per completed unit of work, newest first in `docs/devlog/INDEX.md` (the source of truth; the root AGENTS.md keeps only a 10-row pointer window). Logs are records: append, never rewrite. ## Local Contracts @@ -25,10 +26,11 @@ Durable documentation that explains *why* the project is shaped the way it is. C - Add an ADR when a decision meets all three criteria above; do not backfill records for obvious choices. - When an ADR is superseded, change its status rather than deleting it, and add the replacement under the next number. - Keep each record to a single decision. +- After a completed task, issue fix, or milestone, write a log with the write-log skill; register it in `INDEX.md` and refresh the root window in the same pass. ## Verification -- No automated check. Review by reading: every file in `docs/adr/` matches `NNNN-slug.md` and numbering is gap-free and sequential. +- No automated check. Review by reading: every file in `docs/adr/` matches `NNNN-slug.md` and numbering is gap-free and sequential; every `docs/devlog/*.md` other than `INDEX.md` matches `YYYYMMDD-_log.md` and has a row in `INDEX.md`. ## Child DOX Index diff --git a/docs/devlog/20261125-fresh-context-audit-rounds-1-5_log.md b/docs/devlog/20261125-fresh-context-audit-rounds-1-5_log.md new file mode 100644 index 0000000..bf5e05e --- /dev/null +++ b/docs/devlog/20261125-fresh-context-audit-rounds-1-5_log.md @@ -0,0 +1,114 @@ +# Fresh-context audit of the Nous Portal provider: five rounds to a clean round + +> **Date:** 2026-11-25 +> **Type:** generic +> **Reference:** procedure in `~/.pi/agent/prompts/finish_audit.md`; commits `00d50e1`, `b9065d4`, `8d91094`, `78e8924`, `04fa08f` + +## Goal + +Audit the session's changes to `index.ts` (and its tests and docs) with the +fresh-context reviewer fanout from `finish_audit.md`: three reviewers per round +(`ponytail-review`, `security-review`, `review`), each with a fresh context and +read-only access to a materialized diff; fix the accepted findings; repeat until +one full round produces zero accepted production-code findings after the last +code-change round. + +## What Was Done + +- **Round 1 → `00d50e1`** (tests 4 → 8): `slow_down` now sleeps longer instead of + re-polling at once and the interval cap that could lower a server interval is + gone; non-JSON token errors keep the HTTP status instead of surfacing as + `SyntaxError`; dead `process.env.NOUS_API_KEY` fallback removed from + `fetchModels`; `apply()` persists the catalog flag before mutating memory; + `sleep` moved to `node:timers/promises`; three unused exports removed; + `t.mock.method` replaces hand-rolled fetch swaps; stub gained `getAgentDir`. +- **Round 2 → `b9065d4`** (tests 8 → 14): `apply()` swaps the current model only + when a Nous model was filtered out and names the model actually in use; poll + interval floored at 1 s; the provider's own `context.publish` removed + (`createProvider` already publishes the `fetchModels` return value with + `checkedAt`); `tokenRequest` tolerates a literal `null` error body; tsconfig + and `.editorconfig` trimmed; slash commands driven through a recording `pi`. +- **Round 3 → `8d91094`** (tests 14 → 17): the catalog-tier header is stripped + from request **options** too, on both `stream` and `streamSimple`; the + "Press Enter" prompt in OAuth login removed; non-finite poll intervals rejected + and every sleep capped at the deadline; `/nous-free` back to full, + `/nous-catalog` cycling, and startup restore of a saved catalog are covered. +- **Round 4 → `78e8924`** (tests 17 → 18): `apply()` exits silently when a newer + invocation changed the catalog while it awaited the model refresh (pinned with + a deferred-refresh test); `CITATION.cff` no longer claims a release date while + the CHANGELOG is `[Unreleased]` and no tag exists. +- **Round 5 → `04fa08f`** (tests 18 → 20, no production change): pins the + provider-level `fetchModels` last-good retention, the `tokenRequest` OAuth + error mapping, and a real `setModel` assertion in the overlap test; README + drops the hard-coded live catalog counts (409 / 3 / 42). +- Each round: five patch files re-materialized into `_code_review/` by explicit + path list (production / tests / config / docs / meta), verified byte-identical + to HEAD and free of secrets; a cumulative ledger of 36 "already fixed — do NOT + re-report" items grew in `_code_review/BRIEF.md` and was inlined into every + reviewer task. Round 5 verdicts: security and ponytail clean, general + docs-only/tests-only — zero code-change findings, stopping rule met. +- Every production fix was mutation-checked after its commit: reverting it fails + exactly its own test. Closing gate `npm run check`: `tsc` clean, 20/20. +- Live smoke tests during the session (from `/tmp`, temporary + `~/.pi/agent/nous-portal-catalog` flag, removed afterward): OAuth login and + token refresh, subscription-billed inference, and paid / free / promo model + calls answered. The network-refresh path of OAuth was not exercised live. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Native pi-ai `Provider` via `createProvider`; OAuth access token used directly as the inference bearer | Nous retired agent-key minting (`410 session_key_minting_retired`), which is where both community extensions end their login. Recorded in `docs/adr/0001-stack.md`. | +| Catalog tier rides on `Model.headers["x-nous-catalog-tier"]` and is stripped from **both** the model and the request options | pi persists and restores model objects across runs, so a side table misses restored entries; pi copies `model.headers` into `options.headers` before calling the provider and the client applies `options.headers` last. | +| `withoutTierHeader` wraps both `stream` and `streamSimple` | They are separate implementations in pi-ai and `streamSimple` calls the module-local `stream`, so a `stream`-only wrapper is bypassed. | +| No request-body rewriting (`tags.user`) | Nous free and discounted models return HTTP 500 when it is injected; `upstage/solar-mini4:free` is left out of `BASELINE` instead. | +| `login()` is `notify(code)` then poll, with no prompt | pi's login dialog `showPrompt` clears the device-code confirm action, so a prompt leaves Enter opening nothing; pi's dialog already shows the code and opens the browser. | +| Hand-rolled poll loop with interval `Number.isFinite && > 0 ? max(…, 1) : 5`, sleeps `min(interval·1000, deadline − now)` | pi-ai's `pollOAuthDeviceCodeFlow` is not exported; `interval: 0` and an overflowing JSON number (`Infinity`, clamped by Node to 1 ms) both become tight loops. Mirrors pi-ai's poller. | +| `apply()` uses a supersede guard (`if (catalog !== next) return;`) rather than filtering by `next` | The guard removes both the mislabeled notice and the extra `setModel`; the surviving invocation reports the final state. A stale notice in the later `setModel` await is not humanly reachable and state stays correct. | +| `models = fetched` kept; no provider-level `context.publish` | `createProvider` persists and publishes whatever `fetchModels` returns; a second publish was a timestamp-less write. An empty live result keeps the last good list. | +| Rejected: `verification_uri` origin check | The attacker who could point it elsewhere is Nous itself. | +| Withdrawn: "LICENSE link is dead" | The license is tracked; evidence in `LICENSE-head.txt`. | +| Not added: a unit test for the poll loop | It would need extraction and timer control; the loop is verified live and its error paths are unit-tested through `tokenRequest`. | +| Not fixed (fail closed, server-controlled input): 2xx token body without `access_token`; `fetchModels` 2xx body `null`; a malformed catalog row aborts the list | No exploit path; re-login or a surfaced `TypeError` follows. | +| Mutation checks run only after the fix is committed | `git checkout -- ` restores HEAD; before the commit that is the pre-fix state (see gotchas). | +| Round-5 tests/docs fixes applied without a sixth round | The procedure counts only accepted production-code findings; test-only and docs-only findings do not reset the loop. | +| README carries no live catalog counts; `CITATION.cff` has no `date-released` | DOX style: document stable contracts, not diary entries; a date before a tag exists contradicts the CHANGELOG. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| The catalog-tier header still reached Nous after the round-1 "fix"; the old test pinned the leak as expected | pi copies `model.headers` into `options.headers` (`pi-ai dist/models.js:361`, `model-runtime.js:476,488`) and the client applies `options.headers` last (`openai-completions.js:539-540`); `streamSimple` calls the module-local `stream` | `untier(model)` and `untier(options)` on both entry points; test asserts the header is absent while a sibling header survives (`8d91094`) | +| "Press Enter" in login made Enter open nothing, silently | `showPrompt` in `login-dialog.js:189` calls `clearDeviceCodeAction()` | Prompt removed with a comment explaining why (`8d91094`) | +| An overflowing `interval` became a tight loop | JSON number → `Infinity`; Node clamps `setTimeout` to 1 ms | `Number.isFinite` check, 1 s floor, sleeps capped at the deadline (`8d91094`) | +| Two quick `/nous-*` invocations: the first notice mislabelled the catalog and could fire one extra `setModel` | `apply()` read the shared mutable `catalog` after `await refresh` | Supersede guard + deferred-refresh test (`78e8924`); the test's `setModel` half was vacuous until `04fa08f` gave the session a Nous model | +| Mutation cleanup `git checkout -q -- index.ts` reverted the uncommitted round-3 production fixes | Mutation checks ran before committing | Re-applied (stale edit anchors first, then a fresh read); from round 4 on: commit → mutate → checkout | +| A `node -e` mutation with `\\n` inside bash single quotes matched nothing and the chain continued | Over-escaped regex in the shell quoting | Plain string replace that exits non-zero when the content is unchanged | +| New `tokenRequest` test failed on `error.message` | The local `OAuthError` prefixes messages with `${code}: ` | Assert on the prefixed form (`slow_down: 400 SLOW DOWN`) | +| `goal_complete` rejected with "summary says the goal is not complete" | Text heuristic tripped on negated ledger phrases ("NOT DONE", "not a goal requirement") | Same facts rephrased affirmatively; accepted | +| README live counts (409 / 3 / 42) drift; `CITATION.cff` `date-released` predates any release | Point-in-time snapshot presented as a contract; project tooling stamped a date | Counts dropped (`04fa08f`); `date-released` dropped (`78e8924`) | + +## Files Changed + +| File | Change Summary | +|------|----------------| +| `index.ts` | Device-code poll bounded (finite interval, floor, deadline cap); tier header stripped from model and options on both stream entry points; login prompt removed; `apply()` persist-before-mutate and supersede guard; dead env fallback, interval cap, and a redundant `context.publish` removed; `tokenRequest` tolerates `null` bodies | +| `tests/index.test.mjs` | 4 → 20 tests: tier header on both sides, `tokenRequest` error paths (HTML, `null`, JSON mapping), bearer credentials, slash commands via `drive()` with a deferred `refresh`, provider `fetchModels` last-good retention | +| `tests/stubs/pi-ai.mjs` | `getAgentDir` returning a private `mkdtemp` dir shared via `globalThis`; `agentDir` export | +| `README.md` | Overlay semantics, install lockfile flag, browser-UA posture, hermes row, typecheck pin; live counts removed | +| `AGENTS.md`, `tests/AGENTS.md`, `docs/AGENTS.md` | Both header strips documented; allowlist includes `pi-coding-agent`; test contracts updated; session-log ownership added | +| `CITATION.cff`, `CHANGELOG.md` | `date-released` dropped while unreleased; `/nous-catalog` switch semantics stated | +| `tsconfig.json`, `.editorconfig`, `.gitignore` | Inert options removed; `.mjs` covered; `_code_review/` ignored | +| `docs/devlog/20261125-fresh-context-audit-rounds-1-5_log.md`, `docs/devlog/INDEX.md` | This log and the index | + +## Open Items & Next Steps + +- [ ] Rotate the API keys that were printed into the session log during the earlier investigation, if that log is not private. +- [ ] At release: rename `## [Unreleased]` to `## [0.1.0] - ` and add `date-released` to `CITATION.cff` in the same commit, then tag `v0.1.0`. +- [ ] `SCOPE = "inference:mint_agent_key"` is legacy (the mint endpoint returns 410) and grants nothing reachable; revisit if Nous publishes a replacement scope. +- [ ] `upstage/solar-mini4:free` stays out of `BASELINE` while Nous returns 500 on an injected `tags.user`; re-check periodically. +- [ ] The OAuth network-refresh path has not been exercised by a live smoke test. +- [ ] `_code_review/` is gitignored; the 36-item ledger lives only on this machine. + +--- +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md new file mode 100644 index 0000000..975644b --- /dev/null +++ b/docs/devlog/INDEX.md @@ -0,0 +1,8 @@ +# Session Log Index + +Complete history of session logs in this directory, newest first. One-line summaries — open a log for full detail. + + +| Date | Type | File | Summary | +|------|------|------|---------| +| 2026-11-25 | generic | [20261125-fresh-context-audit-rounds-1-5_log.md](20261125-fresh-context-audit-rounds-1-5_log.md) | Five-round fresh-context audit of the Nous Portal provider: two P1s surfaced in round 3, clean in round 5 | diff --git a/tests/AGENTS.md b/tests/AGENTS.md index 5b0831b..b38bc23 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -15,7 +15,7 @@ Offline unit tests for `index.ts`. They pin the pure logic that has real branchi - `index.test.mjs` loads `index.ts` through jiti, the same TS loader pi uses, because the host packages are not installed in `node_modules`. - Host imports are aliased to `stubs/pi-ai.mjs`. Alias keys are matched longest-prefix first: `@earendil-works/pi-ai/compat` must be listed before `@earendil-works/pi-ai`, or the bare key swallows the subpath and resolution fails. - `stubs/pi-ai.mjs` exports only what `index.ts` imports: `envApiKeyAuth`, `createProvider`, `openAICompletionsApi`, `getAgentDir` (plus `agentDir` so tests can find the flag file). `getAgentDir` is called inside the default export, so it is reached only by tests that drive the commands; it returns a private `mkdtemp` dir per run, shared through `globalThis` because jiti loads the stub as a separate instance from a native import. It is a type-less stub; correctness of those functions is pi's concern and is verified live, not here. -- Exported functions under test: `toModel`, `toCredential`, `tokenRequest`, `fetchModels`, `tierOf`, `withoutTierHeader`, and the default export via the `drive()` harness. Anything else is not unit-tested (notably the device-code poll loop inside `login`, which would need timer control and extraction). +- Exported functions under test: `toModel`, `toCredential`, `tokenRequest`, `fetchModels`, `tierOf`, `withoutTierHeader`, and the default export via the `drive()` harness. `drive(flag)` returns `run(name, model, available, refresh)` — pass a deferred promise as `refresh` to simulate overlapping command invocations, and a Nous `model` when the `setModel` half of a contract is under test — plus the registered `provider`, which is how the provider-level `fetchModels` last-good retention is reached. Anything else is not unit-tested (notably the device-code poll loop inside `login`, which would need timer control and extraction). - Network calls are replaced with `t.mock.method(globalThis, "fetch", …)` from `node:test`, which restores itself when the test ends. Do not hand-roll a `globalThis.fetch` swap. - `fetchModels` reads a key only from the `credential` argument. Env resolution of `$NOUS_API_KEY` is `envApiKeyAuth`'s job upstream. The one test that touches `process.env` sets it deliberately, to pin that `fetchModels` ignores it; it restores the previous value in `t.after`.