mirror of
https://github.com/dtzp555-max/olp.git
synced 2026-07-19 09:45:07 +00:00
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>
235 lines
9.1 KiB
JavaScript
235 lines
9.1 KiB
JavaScript
/**
|
|
* lib/providers/base.mjs — Provider contract definition and shared helpers
|
|
*
|
|
* Authority: ADR 0002 § "Provider contract (v1.0 interface)"
|
|
*
|
|
* This module does NOT implement the Provider contract itself.
|
|
* Provider plugins compose the helpers exported here; they do not inherit
|
|
* from a base class (per ADR 0002 § Consequences/Mitigations: "compose helpers,
|
|
* do not inherit").
|
|
*/
|
|
|
|
// ── Contract typedef ──────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* @typedef {Object} ProviderAuth
|
|
* @property {string} type - e.g. 'subscription', 'api-key', 'oauth'
|
|
* @property {string} storage - e.g. 'cli-managed', 'env', 'keychain'
|
|
* @property {string} path - artifact location hint
|
|
* @property {string|null} refresh - refresh mechanism or null if not applicable
|
|
*/
|
|
|
|
/**
|
|
* @typedef {Object} ProviderHints
|
|
* @property {boolean} requiresTTY
|
|
* @property {boolean} concurrentSpawnSafe
|
|
* @property {number} maxConcurrent
|
|
* @property {number} [maxSpawnTimeMs] - optional integer milliseconds, default 600000
|
|
* @property {boolean} [cacheable] - optional, default true; if false, opt out of OLP's
|
|
* response cache entirely — executeHopFn skips cacheStore.getOrCompute and calls
|
|
* collectAllChunks directly. ADR 0002 Amendment 3 (D23).
|
|
*/
|
|
|
|
/**
|
|
* @typedef {Object} ProviderContractV1
|
|
* @property {string} name - unique lowercase key
|
|
* @property {string} displayName - human-readable name
|
|
* @property {'1.0'} contractVersion - must be '1.0' for v1.0 plugins (D4 fold-in per reviewer F3)
|
|
* @property {string[]} models - model strings this provider serves
|
|
* @property {ProviderAuth} auth
|
|
* @property {function} spawn - async (irRequest, authContext) => AsyncIterator<IRResponseChunk>
|
|
* @property {function} estimateCost - (request) => {inputTokens, outputTokensEstimate, currency, usd}|null
|
|
* @property {function} quotaStatus - async (authContext) => {available, percentUsed, resetsAt, pool}|null
|
|
* @property {function} healthCheck - async () => {ok: boolean, latencyMs: number, error?: string}
|
|
* @property {ProviderHints} hints
|
|
*/
|
|
|
|
// ── Contract validator ────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Validates that a plugin object satisfies the v1.0 Provider contract.
|
|
* Per ADR 0002 § "Loading model", the registry calls this at startup for
|
|
* every registered provider; an invalid provider throws rather than silently
|
|
* degrading.
|
|
*
|
|
* @param {*} p
|
|
* @returns {{ valid: boolean, errors: string[] }}
|
|
*/
|
|
export function validateProvider(p) {
|
|
const errors = [];
|
|
|
|
if (!p || typeof p !== 'object') {
|
|
errors.push('provider must be an object');
|
|
return { valid: false, errors };
|
|
}
|
|
|
|
if (typeof p.name !== 'string' || p.name.trim() === '') {
|
|
errors.push('name must be a non-empty string');
|
|
} else if (!/^[a-z][a-z0-9_-]*$/.test(p.name)) {
|
|
errors.push('name must be lowercase alphanumeric (with _ or -) starting with a letter');
|
|
}
|
|
|
|
if (typeof p.displayName !== 'string' || p.displayName.trim() === '') {
|
|
errors.push('displayName must be a non-empty string');
|
|
}
|
|
|
|
// contractVersion: required to be exactly '1.0' for v1.0 plugins (D4 fold-in per reviewer F3)
|
|
// Per ADR 0002 § Mitigations: "The contract is versioned. v1.0 is the subset in this ADR;
|
|
// future additions require ADR amendment plus a contract-version bump."
|
|
if (p.contractVersion !== '1.0') {
|
|
errors.push(`contractVersion must be '1.0', got ${JSON.stringify(p.contractVersion)}`);
|
|
}
|
|
|
|
if (!Array.isArray(p.models)) {
|
|
errors.push('models must be an array of strings');
|
|
} else if (p.models.some(m => typeof m !== 'string')) {
|
|
errors.push('every entry in models must be a string');
|
|
}
|
|
|
|
if (!p.auth || typeof p.auth !== 'object') {
|
|
errors.push('auth must be an object with { type, storage, path, refresh }');
|
|
} else {
|
|
if (typeof p.auth.type !== 'string') errors.push('auth.type must be a string');
|
|
if (typeof p.auth.storage !== 'string') errors.push('auth.storage must be a string');
|
|
if (typeof p.auth.path !== 'string') errors.push('auth.path must be a string');
|
|
if (p.auth.refresh !== null && typeof p.auth.refresh !== 'string') {
|
|
errors.push('auth.refresh must be a string or null');
|
|
}
|
|
}
|
|
|
|
if (typeof p.spawn !== 'function') {
|
|
errors.push('spawn must be a function');
|
|
}
|
|
|
|
if (typeof p.estimateCost !== 'function') {
|
|
errors.push('estimateCost must be a function');
|
|
}
|
|
|
|
if (typeof p.quotaStatus !== 'function') {
|
|
errors.push('quotaStatus must be a function');
|
|
}
|
|
|
|
if (typeof p.healthCheck !== 'function') {
|
|
errors.push('healthCheck must be a function');
|
|
}
|
|
|
|
if (!p.hints || typeof p.hints !== 'object') {
|
|
errors.push('hints must be an object with { requiresTTY, concurrentSpawnSafe, maxConcurrent } + optional { maxSpawnTimeMs, cacheable }');
|
|
} else {
|
|
if (typeof p.hints.requiresTTY !== 'boolean') errors.push('hints.requiresTTY must be a boolean');
|
|
if (typeof p.hints.concurrentSpawnSafe !== 'boolean') errors.push('hints.concurrentSpawnSafe must be a boolean');
|
|
if (typeof p.hints.maxConcurrent !== 'number' || !Number.isInteger(p.hints.maxConcurrent) || p.hints.maxConcurrent < 0) {
|
|
errors.push('hints.maxConcurrent must be a non-negative integer');
|
|
}
|
|
if (p.hints.maxSpawnTimeMs !== undefined) {
|
|
if (typeof p.hints.maxSpawnTimeMs !== 'number' || !Number.isInteger(p.hints.maxSpawnTimeMs) || p.hints.maxSpawnTimeMs <= 0) {
|
|
errors.push('hints.maxSpawnTimeMs must be a positive integer (milliseconds) or omitted');
|
|
}
|
|
}
|
|
// ADR 0002 Amendment 3 (D23): cacheable is optional; if present must be boolean.
|
|
// undefined → default true (cacheable); false → provider opts out of cache.
|
|
if (p.hints.cacheable !== undefined && typeof p.hints.cacheable !== 'boolean') {
|
|
errors.push('hints.cacheable must be a boolean or omitted');
|
|
}
|
|
}
|
|
|
|
return { valid: errors.length === 0, errors };
|
|
}
|
|
|
|
// ── Error class ───────────────────────────────────────────────────────────
|
|
|
|
/** Error codes surfaced by provider plugins */
|
|
export const PROVIDER_ERROR_CODES = /** @type {const} */ ([
|
|
'AUTH_MISSING',
|
|
'QUOTA_EXHAUSTED',
|
|
'RATE_LIMITED',
|
|
'CLI_NOT_FOUND',
|
|
'SPAWN_FAILED',
|
|
// OUTPUT_PARSE_ERROR removed (D32 F4): no plugin emits it; dead code.
|
|
// Re-add via ADR 0004 amendment if a future plugin surfaces parse failures.
|
|
'SPAWN_TIMEOUT', // ADR 0004 § Trigger taxonomy bullet 4: spawn timeout is a hard trigger
|
|
]);
|
|
|
|
export class ProviderError extends Error {
|
|
/**
|
|
* @param {string} message
|
|
* @param {typeof PROVIDER_ERROR_CODES[number]} code
|
|
*/
|
|
constructor(message, code) {
|
|
super(message);
|
|
this.name = 'ProviderError';
|
|
this.code = code;
|
|
}
|
|
}
|
|
|
|
// ── Shared helpers ────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Wraps a promise with a timeout. Rejects with a ProviderError if the promise
|
|
* does not settle within `ms` milliseconds.
|
|
*
|
|
* @template T
|
|
* @param {Promise<T>} promise
|
|
* @param {number} ms
|
|
* @param {typeof PROVIDER_ERROR_CODES[number]} errorCode
|
|
* @returns {Promise<T>}
|
|
*/
|
|
export function withTimeout(promise, ms, errorCode) {
|
|
return new Promise((resolve, reject) => {
|
|
const timer = setTimeout(() => {
|
|
reject(new ProviderError(`Operation timed out after ${ms}ms`, errorCode));
|
|
}, ms);
|
|
promise.then(
|
|
v => { clearTimeout(timer); resolve(v); },
|
|
e => { clearTimeout(timer); reject(e); },
|
|
);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Merges two AsyncIterators into a single ordered stream.
|
|
* Items from whichever source yields first are emitted first.
|
|
* Useful when a provider plugin wants to interleave two internal streams.
|
|
*
|
|
* Not used at D3 (no providers yet) but provided as infrastructure so
|
|
* provider authors don't each implement their own fan-in.
|
|
*
|
|
* @template T
|
|
* @param {AsyncIterator<T>} iter1
|
|
* @param {AsyncIterator<T>} iter2
|
|
* @returns {AsyncGenerator<T>}
|
|
*/
|
|
export async function* mergeStreams(iter1, iter2) {
|
|
// Convert each iterator to a pull-based promise queue
|
|
const done1 = { done: true };
|
|
const done2 = { done: true };
|
|
|
|
let p1 = iter1.next();
|
|
let p2 = iter2.next();
|
|
|
|
while (true) {
|
|
const winner = await Promise.race([
|
|
p1.then(r => ({ r, which: 1 })),
|
|
p2.then(r => ({ r, which: 2 })),
|
|
]);
|
|
|
|
if (winner.which === 1) {
|
|
if (winner.r.done) {
|
|
// iter1 exhausted — drain iter2
|
|
for await (const v of { [Symbol.asyncIterator]: () => iter2 }) yield v;
|
|
return;
|
|
}
|
|
yield winner.r.value;
|
|
p1 = iter1.next();
|
|
} else {
|
|
if (winner.r.done) {
|
|
// iter2 exhausted — drain iter1
|
|
for await (const v of { [Symbol.asyncIterator]: () => iter1 }) yield v;
|
|
return;
|
|
}
|
|
yield winner.r.value;
|
|
p2 = iter2.next();
|
|
}
|
|
}
|
|
}
|