Files
olp/CLAUDE.md
T
taodengandClaude Opus 4.7 f784fdb947 fix+docs: D33 — round-5 cleanup batch (F1/F3/F5/F8/F9/F10/F11/F12)
cold-audit catch from 2026-05-24 (round 5)

Round-5 cold-audit cleanup batch. 8 items + 1 release-discipline
reconciliation. Largest batch by line count (582+/39-) but every item
is small-and-focused. 3 P2 items (F1/F3/F5 of which F3 + F1 are real
correctness/observability fixes; F5 backfills /health to spec).

Changes (10 files, +583/-39):

**P2 fixes**

1. **F1 — ALIGNMENT.md mistral authority pin self-contradicted plugin**
   (ALIGNMENT.md): row cited `vibe --prompt --output json` but mistral.mjs
   uses `--output streaming` (the plugin header at lines 360-369 even
   justifies WHY: `--output json` emits single blob, breaks NDJSON
   line-buffered parser). Constitution self-contradicting itself —
   missed across 4 prior rounds. Pin updated to `--output streaming`
   with DOCS-1 reference.

2. **F3 — Deterministic function_call synth ID**
   (lib/ir/openai-to-ir.mjs): deprecated `function_call` translation
   produced `id: \`fc-${Date.now()}\`` → ID flows into normalized
   tool_calls → cache key SHA-256. Two identical requests separated
   by ≥1ms → different cache keys → cache always misses for
   `function_call` request shape. Violates ADR 0005 invariant
   "same inputs → same key, no random, no timestamp."

   Fixed: id is now `fc-<16-hex>` from SHA-256 of `${name}\0${arguments}`.
   NUL separator prevents the (name='ab',args='c') vs (name='a',args='bc')
   collision. 2^64 collision resistance is more than sufficient for
   tool_call ID disambiguation (per-request semantic key, not crypto
   primitive).

**P3 fixes**

3. **F5 — /health invokes per-plugin healthCheck()** (server.mjs +
   docs/openai-spec-pin.md): ADR 0002 says "healthCheck — startup AND
   /health endpoint use this." Pre-D33 /health returned only
   {enabled, available} counts. Now async, iterates loadedProviders,
   awaits each plugin's healthCheck() in try/catch. Returns
   `providers: {enabled, available, status: {<name>: {ok, latencyMs?, error?}}}`.

4. **F8 — X-OLP-Cache reports fallback-hop cache hits** (server.mjs):
   pre-D33 cacheStatus computed from `preCheckHit && fallbackHops === 0`
   — only counted primary-hop cache hits. When fallback fires + the
   fallback hop's getOrCompute returns from cache, header reported
   `miss` despite no spawn happening.

   Fixed: peek BEFORE getOrCompute inside executeHopFn, set
   `lastHopWasCached` closure variable on every hop (last-write-wins
   = serving hop's state). cacheStatus combines
   `lastHopWasCached || (preCheckHit && fallbackHops === 0)`.

   F8 chose option (b) peek-then-getOrCompute over option (a)
   getOrCompute API change because option (a) would break ~15 test
   callsites for marginal benefit. Accepted race window same as
   existing preCheckHit pattern.

5. **F9 — validateProvider hints error message updated** (lib/providers/
   base.mjs): pre-D33 message listed cacheable as missing and
   maxSpawnTimeMs as required. Now: `'hints must be an object with
   { requiresTTY, concurrentSpawnSafe, maxConcurrent } + optional
   { maxSpawnTimeMs, cacheable }'`.

6. **F10 — Dead cache-write branch removed** (server.mjs): the
   `if (hasStopChunk)` check in the streaming stop-less exhaustion
   branch was unreachable (the stop-chunk completion path returns
   earlier inside the for-await loop). Removed the dead code + added
   a comment documenting the invariant.

**Governance/policy**

7. **F11 — Phase rolling mode policy formalized** (CLAUDE.md +
   CHANGELOG.md): 22+ D-day commits accumulated under "Unreleased"
   without per-D version bumps — Iron Rule 5 (release-kit bump-before-
   push) appeared to be silently violated. Reality: per-D bumps would
   produce 30+ noise tags during Phase 1. F11 formalizes the policy:
   intra-Phase D-day commits accumulate under Unreleased; bump+tag
   fires explicitly at Phase close (maintainer-triggered, not
   automated). CLAUDE.md release_kit overlay gains `phase_rolling_mode`
   block documenting the exception with self-pointer ("if Rule 5
   appears silently violated, check this section first"). CHANGELOG
   "Unreleased" gets a notice at top.

   **No version bump, no git tag in D33** — policy formalization only.

8. **F12 — /v1/models created is stable per-model timestamp**
   (models-registry.json + lib/providers/index.mjs + server.mjs +
   docs/openai-spec-pin.md): pre-D33 used Math.floor(Date.now()/1000)
   per request — violates OpenAI spec which treats `created` as
   per-model attribute. Clients caching models by created would see
   spurious updates on every poll.

   Fixed: models-registry.json gains `bootstrapCreated: 1778630400`
   top-level constant + per-model `created` fields where known
   (anthropic claude-{opus,sonnet,haiku} with estimated release dates;
   devstral models from "25-12" suffix; codex models pinned to
   bootstrap pending verified release dates). handleModels uses
   `getModelCreated(modelId)` helper from lib/providers/index.mjs.
   Aliases share canonical's timestamp.

**Tests** (test-features.mjs): 401 → 414 (+13):
- F3 ×3 (same input → same id → same cache key; different name → different)
- F5 ×4 (empty/single/multi/throwing-plugin /health shapes)
- F8 ×1 (2-hop primary-fail + secondary-cache-hit → X-OLP-Cache: hit)
- F12 ×5 (stability/fallback/alias-equals-canonical)

Pre-commit fold-in (per evidence-first checkpoint #4):
- **D33 reviewer flagged F3 empty-args asymmetry** (Concern #1): hash
  input used `?? ''` (empty stays) but emitted IR field used
  `|| '{}'` (empty becomes '{}'). Consequence: `arguments: ''` and
  `arguments: '{}'` emit identical IR but compute different ids →
  different cache keys for semantically-identical requests. The exact
  cache-stability bug F3 was supposed to fix.

  Folded in: canonicalize empty-args to '{}' BEFORE hashing. Hash
  input now matches IR emission exactly. Same line change resolves
  the asymmetry.

Authority:
- ALIGNMENT.md self-amendment (F1 pin correction)
- ADR 0005 invariant "same inputs → same key, no random, no timestamp"
  (F3 restoration)
- ADR 0002 § Provider contract "/health uses healthCheck" (F5)
- ADR 0004 § Observability headers (F8 X-OLP-Cache correctness)
- ADR 0005 § Cache write conditions item 1 (F10 truncation-not-cached
  invariant explicit)
- Iron Rule 5 (F11 release-kit reconciliation)
- OpenAI /v1/models spec — `created` per-model stable (F12)
- CC 开发铁律 v1.6 § 10.x — Round-5 Cold Audit caught all 8

Reviewer (Iron Rule v1.6 § 10.x Mode A, fresh-context opus, independent
of drafter): APPROVE_WITH_MINOR. Verified:
- F1 plugin cross-reference (mistral.mjs:360-369) accurately documents
  the rationale
- F3 collision resistance + NUL separator + restored cache invariant
- F5 all 4 cases (empty/single/multi/throwing) work
- F8 closure semantics across multi-hop chains (verified hop-fail +
  fallback-hit case)
- F10 dead code removal preserves the stop-chunk completion path
- F11 phase_rolling_mode policy honest about what happened and what
  the going-forward rule is
- F12 stability across consecutive /v1/models calls; alias-canonical
  parity
- 414/414 tests pass

3 remaining non-blocking suggestions (F3-vs-modern-tool_calls path
canonicalization symmetry; F12 codex models explicit-vs-fallback
writeup mismatch; F8 servingHopWasCached naming) tracked as future
polish; not folded.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-24 19:12:03 +10:00

142 lines
9.1 KiB
Markdown

@AGENTS.md
@~/.cc-rules/AGENTS.md
# OLP Project Session Instructions
> **WARNING — READ BEFORE WRITING ANY CODE IN THIS REPO**
>
> Before touching any provider plugin (`lib/providers/*.mjs`), the entry surface (`server.mjs` request handlers), or the IR (`lib/ir/*`), read [`./ALIGNMENT.md`](./ALIGNMENT.md) in full. The constitution is binding. Non-compliant commits are reverted.
---
## Before starting any task
1. Read `./ALIGNMENT.md`. Internalize the five Rules and the three-authority model (per-provider CLI / OpenAI spec / IR contract).
2. Run `/dev-start <task description>` to get a pre-flight plan that incorporates the iron rules, `SKILL_ROUTING.md`, this file, and `ALIGNMENT.md`.
3. Locate the provider authority **before** drafting any code:
- Provider-plugin change → identify the provider CLI documentation page or observed behaviour you are matching, and pin the CLI version.
- Entry-surface change → identify the OpenAI `/v1/chat/completions` spec section and URL.
- IR change → identify the ADR you are amending or co-merging.
No code is written ahead of the authority citation.
---
## Hard requirements for plugin / server.mjs / IR changes
Every PR that modifies a provider plugin, the entry surface in `server.mjs`, or the IR in `lib/ir/` must satisfy all three of the following. A PR missing any one of them is blocked from merge.
1. **Authority citation.** The commit message and PR body declare the relevant authority and citation:
- Provider plugin → `<provider> CLI <version> § <section-or-flag>` plus URL or transcript reference.
- Entry surface → OpenAI spec URL plus the specific field, parameter, or behaviour.
- IR → `ADR NNNN § <section>` (and the amending ADR if applicable).
If the underlying authority does not perform the operation, the PR must state this explicitly and justify scope under `ALIGNMENT.md` Rule 2 (in practice, this almost always means the PR should be closed).
2. **CI `alignment.yml` pass.** The workflow must pass. It greps for known-hallucinated tokens, validates `models-registry.json`, and soft-checks per-provider commit citations. New blacklist tokens are added via PR amendment to `alignment.yml`; removing entries requires an `ALIGNMENT.md` amendment PR. Do not suppress the workflow.
3. **Independent reviewer (Iron Rule 10).** The implementation author may not self-approve. A separate reviewer — human or a subagent spawned with a fresh context — must read the diff, open the cited authority (provider CLI doc / OpenAI spec / ADR), and explicitly confirm the citation. A review comment that does not confirm the authority was checked is not a valid approval.
---
## Iron rules in force
This repo operates under the CC Development Iron Rules (CC 开发铁律) v1.4. Three rules are load-bearing for OLP work:
- **Iron Rule 10 (Code Review).** Every implementation phase has an independent reviewer. Self-review does not count. See hard requirement #3 above.
- **Iron Rule 11 (Incremental Diff Review).** Non-trivial work is split into the minimum reviewable unit — one PR per layer per severity. `ALIGNMENT.md`, this file, the PR template, and the CI workflows are shipped as a single constitutional PR (one layer: governance). Subsequent layers (plugin loader, individual provider plugins, IR serializers, cache layer, fallback engine, dashboard) each land as their own PR.
- **Iron Rule 12 (Pre-Brainstorm Prior-Art Search).** Before proposing any new IR field, fallback trigger, or provider plugin, search the relevant provider's docs, OpenAI's spec, the local `docs/adr/`, and the cross-machine `~/.cc-rules/memory/learnings/`. The provider-specific search is the decisive one: if the provider CLI does not perform the operation, Rule 2 of the constitution applies.
The full iron rules are at `~/.claude/CC_DEV_IRON_RULES.md` (symlinked from the cc-rules repo on the maintainer's workstations). Load them into session context with `/cc-rules` when needed.
---
## Skills relevant to this repo
- `/dev-start` — pre-flight planning, always first for non-trivial tasks.
- `/cc-rules` — load the iron rules into context.
- `/agent-dispatch` — pick the correct model (opus for design and review, sonnet for straightforward edits, haiku for mechanical chores) before spawning any subagent.
- `/cc-mem search <keyword>` — look up cross-machine memory for prior decisions, especially provider-policy events and CLI-version migrations.
---
## Commit message conventions
- Subject line uses Conventional Commits (`fix:`, `feat:`, `docs:`, `refactor:`, `chore:`).
- Provider-plugin commits include the citation pattern `<provider> CLI <version>` or a direct provider docs URL in the body. CI performs a soft check.
- Entry-surface commits include an OpenAI spec URL.
- IR commits cite the authorizing or amending ADR.
- Any assertion of the form "Provider X uses Y" in the body must be immediately followed by a citation (CLI version + section, or docs URL, or observed-transcript reference). CI soft-checks the pattern.
- Co-author trailer is required for LLM-assisted commits (`Co-Authored-By: Claude <model> <noreply@anthropic.com>`).
---
## Project-level escalation
If a design decision cannot be resolved by reference to the relevant authority (provider CLI / OpenAI spec / ADR) and `ALIGNMENT.md`, escalate to the project maintainer via `/cc-chat` rather than guessing. Silent guessing is what produced OCP's 2026-04-11 drift; OLP inherits that institutional lesson and does not repeat it.
---
## Release kit overlay (CC 开发铁律 第五律 5.5)
This project's overlay per iron rule v1.4's 5.5. Machine-checkable declaration.
```yaml
release_kit:
version_source: package.json
changelog: CHANGELOG.md
release_channel:
type: github-release
tag_format: v{semver}
auto_create_on_tag_push: true # via .github/workflows/release.yml
docs_source: README.md
resource_lists:
- name: Supported Providers table
location: README.md § "Supported Providers"
source_of_truth: models-registry.json
- name: Routing chains table
location: README.md § "Configuration"
- name: API Endpoints table
location: README.md § "API Endpoints"
- name: Environment Variables table
location: README.md § "Environment Variables"
new_feature_doc_expectations:
- new provider plugin → README § "Supported Providers" entry + ADR 0006 inclusion entry + risk-tier classification
- new fallback trigger → README § "Configuration" + tests in test-features.mjs
- new IR field → ADR 0003 amendment + README impact note (if user-visible)
- new env var → README § "Environment Variables" table
- new endpoint → README § "API Endpoints" table + relevant Config / Troubleshooting §
- new auto-sync / hook → dedicated §, must document trigger + manual invocation + opt-out + any bootstrap quirk
- new file / SPOT / schema → Architecture or contributor § with link
bootstrap_quirk_policy:
- any first-run migration quirk (e.g., from OCP) → README § "Troubleshooting" + scripts/migrate-from-ocp.mjs if applicable
# NOTE: scripts/migrate-from-ocp.mjs is planned (Phase 7), not yet authored. The scripts/ directory
# does not currently exist. References here are forward-looking; do not attempt to run this script.
phase_rolling_mode:
# Iron Rule 5 (release-kit version bump before push) applies at Phase boundaries,
# NOT to individual D-day commits within a Phase.
#
# Rationale: OLP Phase 1 is a single cohesive deliverable (boot layer + provider
# plugins + cache + fallback engine + hardening). Bumping a version tag for every
# D-day push would produce 30+ noise tags with no user-facing semantic boundary.
# ADR 0005 § "Cache key stability" requires that key composition is stable across
# a release; mid-phase tag churn would falsely signal stability windows.
#
# Policy:
# - While a Phase is in progress, individual D-day pushes land under "Unreleased"
# in CHANGELOG.md. package.json stays at the Phase-N pre-release identifier
# (e.g. "0.1.0-bootstrap" during Phase 1 boot; the token may be updated to
# "0.1.0-phase1" once Phase 1 implementation starts landing).
# - The version bump + git tag fires at Phase CLOSE — a dedicated "Phase N close"
# PR that bumps package.json, promotes "Unreleased" to the release version in
# CHANGELOG.md, and triggers .github/workflows/release.yml via the tag push.
# - The Phase close PR is triggered explicitly by the project maintainer; it is
# NOT automatic. No automated tooling bumps the version.
# - Cross-Phase discipline: if D-day work touches a boundary already tagged (e.g.
# a hotfix to a shipped Phase N deliverable), follow Iron Rule 5 normally — bump
# patch, tag, release before pushing.
#
# This overlay is the authoritative source. If Iron Rule 5 appears to be silently
# violated (no version bump after many D-day pushes), check this section first
# before filing a compliance finding.
current_phase: Phase 1
current_pre_release_identifier: "0.1.0-bootstrap"
phase_close_trigger: explicit maintainer action (not automated)
```