mirror of
https://github.com/Gitlawb/openclaude.git
synced 2026-11-06 20:58:14 -04:00
v0.31.0
1223
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
5cd11336ca |
chore(main): release 0.31.0 (#2190)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>v0.31.0 |
||
|
|
bfb44ffa81 |
fix(chrome): launch the packaged CLI entrypoint in npm installs (#2146)
* fix(chrome): launch the packaged CLI entrypoint * fix(chrome): harden install verification * fix(chrome): verify installed setup targets * fix(chrome): harden setup receipt verification * test(chrome): require the packaged heap-limit helper A packed tarball that has every other required entry but not package/bin/heap-limit.mjs must fail clean-install verification. |
||
|
|
55e9b24d91 |
perf(bg): avoid full scans for exact session IDs (#2166)
* perf(bg): avoid full registry scans for exact session IDs * fix(bg): keep resolver test seam internal |
||
|
|
70fe2de2f8 |
fix(bg): clean up old completed session artifacts (#2167)
* fix(bg): clean up old completed session artifacts * fix(bg): reclaim orphaned terminal facts * test(bg): stabilize reservation cleanup handoff * test(bg): clarify cleanup race invariants * fix(bg): validate cleanup completion timestamps * fix(bg): isolate reused session generations * fix(bg): recover terminal session handoffs * fix(bg): retain zero-day cleanup ownership * fix(bg): preserve handled exception outcomes * fix(bg): unify retention lifecycle cleanup * fix(bg): harden retention coordination * fix(bg): preserve retention pass outcomes * test(bg): harden cleanup fixtures and launcher checks |
||
|
|
5fb5abb6f8 | fix(ci): restore main validation (#2236) | ||
|
|
a07b06cee6 |
fix(agent): forward subagent permission prompts to parent session (#2235)
* fix(agent): forward interactive permission prompts * fix(agent): preserve nested permission prompts * fix(agent): isolate permission prompt state * fix(agent): preserve root state for forked commands * fix(agent): close permission handoff races * fix(agent): settle forwarded permission cancellations * fix(agent): keep permission prompts session-owned * fix(agent): preserve origin session permission policy * fix(agent): retain permission owner across delayed starts * fix(agent): isolate concurrent permission prompts * fix(agent): retain inactive owner permission prompts * fix(agent): preserve owner decisions across switches * fix(agent): scope channel permission requests * fix(agent): validate permission mode updates against root context Subagent persist paths were validating setMode against the agent-local context while applying to the root session, which could enable fullAccess or bypassPermissions when only the child marked bypass available. |
||
|
|
70d97fd137 |
feat(web-search): add Ollama backend (#2234)
* feat(web-search): add Ollama backend * fix(web-search): harden Ollama routing * fix(web-search): preserve Ollama profile identity * fix(web-search): align Ollama diagnostics * fix(web-search): align Ollama endpoint diagnostics * fix(web-search): honor Ollama endpoint aliases * fix(web-search): reject Ollama key placeholders * fix(web-search): complete Ollama configuration guidance |
||
|
|
876fb7924a |
feat(query): configure idle timeout (#2233)
* feat(query): configure idle timeout * docs(query): clarify idle timeout limits * feat(settings): configure query idle timeout * test(query): exercise idle timeout integration * fix(query): apply live idle timeout overrides |
||
|
|
0c2043f05e |
fix(hooks): preserve compound Bash commands on Windows (#2217)
* fix(hooks): preserve compound Bash commands on Windows * fix(hooks): preserve environment assignments before scripts --------- Co-authored-by: fancivez <fancive@gmail.com> |
||
|
|
6d09260291 |
chore(types): reduce any usage with safety tooling + 7-batch phase 1 (#2208)
* chore(types): add any-usage baseline + lint budget gate (Phase 0)
Phase 0 of a multi-phase plan to reduce explicit `any` usage safely.
No source files modified in this PR.
- Add eslint@9 + @typescript-eslint deps (lint only, no fix rules).
- New minimal flat eslint.config.js enabling only
`@typescript-eslint/no-explicit-any` as warn. Stub plugins registered
for legacy `custom-rules`, `eslint-plugin-n`, and `react-hooks`
references in existing `// eslint-disable` comments so the comments
stay valid (no rule name resolution errors).
- New `scripts/any-usage-report.ts`: walks src/, tests/, scripts/ and
buckets `any` usage into `: any` annotations, `as any` casts,
`[key: ...]: any` index signatures, `// @ts-ignore` directives, and
generic `any` args. Emits `reports/any-usage.{json,md}`. `--check`
mode exits non-zero if the count grows vs the baseline.
- Lock the baseline at 1,031 occurrences across 198 files.
- Add `lint`, `lint:any-budget`, `check:strict` scripts.
- Plan: docs/plans/imperative-hugging-sphinx.md
Verification:
- `bun run typecheck` clean
- `bun run lint` exit 0 (845 warnings, 0 errors)
- `bun run lint:any-budget` ok (current=1031 baseline=1031)
* chore(types): narrow any in 6 small src files (Phase 1, batch 1)
Phase 1 of the plan to reduce `any` usage. Targets only files with
1–2 lint hits where the concrete type is reachable in scope.
- src/services/api/withRetry.ts: isQuotaExhausted signature `any` → `unknown`,
add local structural narrowing for `.message`/`.status` access.
- src/utils/validation.ts: assertFunction predicate signature `any[]`/`any` →
`unknown[]`/`unknown`.
- src/utils/conversationArc.ts: extractTextFromContent — replace `(block: any)`
in filter/map with explicit type predicate narrowing.
- src/utils/optionalRuntimeModule.ts: dynamic-import wrapper returns
`Promise<unknown>` instead of `Promise<any>`.
- src/entrypoints/mcp.ts: tighten block mapping with the existing structural
type already in scope; replace `(finalResult as any).isError` with a
narrow cast.
- src/components/EffortPicker.tsx: drop redundant `: any` on useAppState
selector — the function's generic infers `AppState` for free.
Verification:
- bun run typecheck clean
- bun run lint: 835 warnings (was 845)
- bun run lint:any-budget: 1022 / 1031 baseline (delta -9)
- bun test src/utils/optionalRuntimeModule.test.ts + conversationArc.test.ts:
36 pass / 0 fail
- bun test src/services/api/withRetry.test.ts: 44 pass / 0 fail
* chore(types): narrow any in WebSearchTool + adapters (Phase 1, batch 2)
Phase 1 continues. These are all boundary code (HTTP responses from
external search APIs), so every `any` is at a module boundary per the
plan. Each adapter now types its response with `unknown` + structural
narrowing instead of `any`.
- providers/types.ts: firstMatch/normalizeHit accept `unknown` and narrow
to `Record<string, unknown>` before index access.
- providers/timeout.ts: fetchJsonWithWebSearchTimeout returns
Promise<unknown>.
- providers/{bing,brave,jina,linkup,mojeek,tavily,you,exa,custom}.ts: each
adapter's response data is cast to a minimal shape (`{ results?: unknown }`
etc.), then array elements are narrowed to `Record<string, unknown>` with
`typeof` checks per field.
- WebSearchTool.ts: getCodexSources and extractCodexWebSearchFailure now
take `Record<string, unknown>`; nested `action`/`error`/`result` are
cast locally to `Record<string, unknown>` so `?.field` chains type-check.
Verification:
- bun run typecheck clean
- bun run lint: 805 warnings (was 835, -30)
- bun run lint:any-budget: 992 / 1022 baseline
- bun test src/tools/WebSearchTool: 138 pass / 0 fail across 9 files
* chore(types): narrow any in 6 mid-size src files (Phase 1, batch 3)
Phase 1 continues. Each replacement uses a precise structural cast
(`as { uuid?: string }` etc.) or `unknown` with typeof/Array.isArray
narrows at use sites.
- src/utils/settings/types.ts: zod preprocess callback `any` → `unknown`,
copy via `Record<string, unknown>`.
- src/entrypoints/sdk/v2.ts: initialMessages param/var `any[]` → `Message[]`;
local cast at the boundary with stripChainFields.
- src/entrypoints/sdk/query.ts: msg `.uuid` access uses
`as { uuid?: string }`; `fileHistoryCanRestore` etc. accept `UUID` (from
`crypto`); `mcpServerStatus` accesses `client.error` / `client.config`
directly since the union members already have them.
- src/commands/cache-probe/cache-probe.ts: getField reduce `any` → `unknown`
with typeof guard; catch (err: any) → `err: unknown` with
`err instanceof Error`; mainMakeUsage/mainConvertChunkUsage take `unknown`
and read fields via typeof checks.
- src/services/compact/snipProjection.ts: snipMetadata / uuid accessed via
narrow structural casts, no longer `as any`.
- src/utils/messages.ts: tool_use block destructuring for extra_content uses
`as { extra_content?: unknown; [k: string]: unknown }` instead of
`as any`.
Public SDK surface (entrypoints/sdk.d.ts, entrypoints/sdk/index.ts
SdkMcpToolDefinition<Schema = any>) is intentionally permissive for
consumer ergonomics and is left untouched per the plan's do-not-touch
list.
Verification:
- bun run typecheck clean
- bun run lint: 782 warnings (was 805, -23)
- bun run lint:any-budget: 969 / 992 baseline
- bun test (sdk v2/factories + compact + messages): 91 pass / 0 fail
* fix(types): correct BetaContentBlock cast in messages.ts (Phase 1 fix)
Verifier caught that the `as { [k: string]: unknown; extra_content?: unknown }`
cast on a `BetaToolUseBlock` did not sufficiently overlap (BetaToolUseBlock
lacks an index signature), so the destructured spread of `restBlock`
yielded a malformed union member that failed to assign to BetaContentBlock[].
Fix: cast through `unknown` first, then assert the final return value as
`BetaContentBlock` (the declared element type of the outer `.map`). This
narrows from the prior `as any` while keeping the previous structural
intent (preserve all block fields, optionally inject `extra_content`).
Verification:
- bun run typecheck clean
- bun test src/utils/messages/: 79 pass / 0 fail
* chore(types): narrow any in 5 dense src + 1 script (Phase 1, batch 4)
Each replacement preserves runtime behavior while using concrete types
where reachable and `unknown` with structural narrowing where not.
- src/components/ClaudeMdExternalIncludesDialog.tsx: 4 helper updaters
(acceptProject/User, declineProject/User) take `ProjectConfig` from
`src/utils/config.ts` instead of `any` (matches the
`saveCurrentProjectConfig` updater signature).
- src/components/ProviderManager.tsx: env-clearing objects in
`activateGithubProvider` and the GitHub disable path used
`undefined as any`. The intent is "delete this key on merge" but the
zod schema coerces to string. Replaced with
`undefined as unknown as string` (honest about the lie) and added a
comment explaining intent.
- src/services/compact/snipCompact.ts: introduced a structural
`SnipMessage` type for the public function params. Tests construct
fake messages with `uuid: 'u4'` (not branded UUID), so a strict
`Message[]` would reject them; the structural type accepts both
production messages and test fixtures. `snipCompactIfNeeded` is
generic `<T extends SnipMessage>` so callers get the same shape back.
Internal content blocks use `unknown` + type-predicate narrowing.
- src/query.ts: yield site for the boundary message casts to `Message`
since the value is constructed as a real `Message` in production.
- scripts/grpc-cli.ts: proto descriptor, stream, and message callback
typed as `unknown` / `ClientDuplexStream<unknown, unknown>`. The
dynamic `.proto` payload is cast once at the boundary into a
structural shape so per-field access (`text_chunk.text` etc.) is
tracked explicitly.
- scripts/generate-sdk-types.ts: the JSON-Schema-walking converter
takes `unknown` everywhere and narrows via typeof / Array.isArray at
each access. `Map<unknown, string>` for placeholder identity
comparison, `Set<string | undefined>` no longer used here.
Verification:
- bun run typecheck clean
- bun run lint: 728 warnings (was 782, -54)
- bun run lint:any-budget: 916 / 969 baseline
- bun test src/services/compact: 91 pass / 0 fail
* chore(types): remove 3 eslint-disable no-explicit-any suppressions
Tighten three small call sites where the `any` was used as a lazy
escape hatch and a real type was reachable in scope.
- src/main.tsx: `(global as any).require('inspector')` becomes
`(global as unknown as { require: (s: string) => { url: () => string } })`.
The dynamic require is being phased out, but while it remains the
narrow structural cast documents the shape we actually consume.
- src/ink/reconciler.ts: catch (error: any) → catch (error: unknown);
`error.code === 'ERR_MODULE_NOT_FOUND'` accesses the code via
`(error as { code?: unknown }).code`.
- src/components/wizard/WizardProvider.tsx:
`createContext<WizardContextValue<any> | null>(null)` →
`createContext<WizardContextValue | null>(null)`. The
`WizardContextValue` generic already defaults to
`Record<string, unknown>`, so the `<any>` was redundant; consumers
that need a tighter type can supply it via
`useContext<WizardContextValue<T>>`.
Note: most remaining lint warnings come from file-level
`/* eslint-disable @typescript-eslint/no-explicit-any */` blocks at the
top of do-not-touch files (src/types/{message,utils,tools}.ts,
src/constants/querySource.ts, src/entrypoints/sdk/controlTypes.ts) and
from public SDK surface (src/entrypoints/sdk{,.d.ts,v2.ts}). Both are
intentional per the plan.
Verification:
- bun run typecheck clean
* chore(types): refresh any-usage baseline
* fix(types): address PR review feedback on any-reduction tooling
- Pin eslint to resolved version (9.39.5) so lint warning totals stay
stable across lockfile updates.
- Wire lint:any-budget into the regular `check` gate (was only in
check:strict), so any-usage regressions block PRs.
- any-usage-report: use lstat and skip symlinks so a self-referencing
link under src/tests/scripts can't stall the budget scan.
- any-usage-report --check: exit nonzero when the baseline file is
missing or invalid so the gate can't be silently disabled.
- Remove dangling references to docs/plans/imperative-hugging-sphinx.md
from eslint.config.js and scripts/any-usage-report.ts headers.
- mcp.ts: defensively skip non-object tool-output entries (primitives
/ null) instead of crashing on boundary data.
- messages.ts: realign the mis-indented tool_search-off branch so the
blockExtra + return block reads at the right level.
No budget delta (913 -> 913). Typecheck, lint, budget, and the affected
unit tests all green.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(types): narrow any in src/grpc/server.ts (5 warnings)
- protoDescriptor cast: replace `as any` with a structural type that only
declares the AgentService shape we actually use.
- handleChat: ServerDuplexStream<any, any> -> <unknown, unknown>; the
clientMessage is narrowed locally where it's read.
- previousMessages: any[] -> Message[] (already imported, already used
as the type of this.sessions).
- catch (err: any) -> catch (err); err.message is now gated behind an
instanceof Error check.
Typecheck, lint, budget, and the 2 grpc unit tests all green.
Lint 728 -> 723 (-5). Budget 913 -> 909 (-4).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(types): narrow any in src/utils/knowledgeGraph.ts (18 warnings)
Add explicit LegacyEntity / LegacyRelation / LegacySummary / LegacyData
types so the migration path stops round-tripping through `any`.
- LegacySource.data, mergeLegacySources, normalizeLegacyData,
readLegacySqliteStore, SqliteReadResult.data, and doMigration all take
the new LegacyData shape.
- LegacyData.entities is typed `Record<string, LegacyEntity> | LegacyEntity[]`
because older JSON dumps stored entities as an array. normalizeLegacyData
converts the array form to the record form so downstream code can keep
using Object.entries. (Old loop relied on the same `id ?? entryKey`
fallback, so behavior is preserved; verified by all 20 unit tests.)
- SQLite row accessor now returns `Record<string, unknown>` (was `any[]`);
per-row readers narrow `row.id`, `row.attributes`, `row.keywords`,
`row.content` from `unknown` and the existing typeof guards preserve
the previous fail-soft behavior on malformed rows.
Lint 723 -> 705 (-18). Budget 909 -> 894 (-15). All 20 knowledgeGraph
unit tests pass; typecheck clean.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* chore(types): narrow SDK tool() generic and handler signature (12 warnings)
The public SDK MCP tool() helper previously defaulted its Schema generic
to `any` and typed handler args as `any`. Switch both to `unknown`:
- SdkMcpToolDefinition<Schema = unknown>
- tool<Schema = unknown> with handler (args: Schema, extra: unknown)
- annotations?: any -> ToolAnnotations (imported from MCP SDK types)
This is a strictly tighter API: callers who pass a concrete schema get
the same behavior; callers who relied on implicit any now have to
validate handler args (which they should have been doing anyway).
All 4 SDK MCP tool wiring tests pass; typecheck clean.
Lint 705 -> 695 (-10). Budget 894 -> 884 (-10).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(types): address PR feedback on SDK + grpc type hardening
Apply 4 of 5 CodeRabbit review items (skipped item 5: SDK resume flow
JSONL validation, deferred as larger refactor).
- sdk.d.ts: switch MCP type imports to the package's public
`@modelcontextprotocol/sdk/types.js` subpath (was the internal
dist/esm/types.js path).
- sdk.d.ts: handler return Promise<any> -> Promise<CallToolResult> in
both SdkMcpToolDefinition and the tool() helper, matching the
runtime contract and the sibling declarations in sdk/index.ts and
sdk/v2.ts.
- grpc/server.ts: introduce a local ClientMessage interface (matching
the openclaude.proto oneof payload) and type the duplex-stream
request as ServerDuplexStream<ClientMessage, unknown>. The handler
body was already reading these fields by name; the type now
documents them.
- grpc/server.ts: ServiceDefinition generic was being passed a
ServerDuplexStream, which isn't a valid T (T must be a record
keyed by method name). Switch to ServiceDefinition<{ Chat: never }>
so the call to addService accepts a real implementation-map key.
Typecheck, lint, budget, and the 6 affected unit tests all green.
Lint 695 -> 693 (-2). Budget 884 -> 882 (-2).
* fix(types): address 6 reviewer findings on PR #2208
Six findings (four P2, two P3) from the second review pass.
1. knowledgeGraph legacy array normalization: previously dropped entries
whose `id` was neither string nor number, breaking recovery for
idless array entries. Use the array index as the fallback key so
mergeLegacySources' existing `id ?? entryKey` logic continues to
recover the entry. All 20 unit tests still pass.
2. SDK tool() generic conflated schema descriptor with invocation
value type, breaking the test fixture (and any external consumer)
that declares the handler with a concrete value type. Restore
`args: any` for the handler across the factory, SdkMcpToolDefinition,
and the .d.ts declaration; keep `Schema` as the generic for
inputSchema typing.
3. sdk.d.ts now declares ToolAnnotations and CallToolResult locally
instead of importing from @modelcontextprotocol/sdk, preserving
the optional peer contract. A consumer without MCP installed no
longer gets TS2307 on a no-op SDKSession type import.
4. any-usage-report now strips comments, string literals, and
template-literal contents before applying the annotation regex,
so `// example: any`, `': any'`, and similar non-type occurrences
no longer count. @ts-ignore / @ts-expect-error / @ts-nocheck
directives are preserved for the ignore category. Budget went
from 882 to 776.
5. generate-sdk-types: schemas module cast as Record<string, () => unknown>
was wrong because HOOK_EVENTS is a non-callable; cast as
Record<string, unknown> and narrow per-access. def.getter() and
Reflect.get(schema, 'description') both narrowed to a callable /
object shape before use. Generated output unchanged (diff empty).
6. any-usage-report walk(): readdir failures now propagate instead
of being silently swallowed, so a partial scan cannot publish a
too-low replacement baseline or pass --check.
Typecheck, lint, budget, and 26 affected unit tests all green.
* chore(types): refresh any-usage baseline after upstream rebase
Baseline 776 -> 779. The +3 comes from upstream #2196 (Command Code
gateway) test mocks merged to main after the baseline was recorded:
2x (payload: any) in ProviderManager.test.tsx, 1x 'as any' in
providerProfiles.test.ts. Symptom-level narrowing of another merged
PR's test fixtures is out of scope; re-baseline to the rebased tree.
---------
Co-authored-by: Gravirei <gravirei@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
|
||
|
|
35d7edc2f6 |
fix(api): validate API_TIMEOUT_MS in the native Anthropic clients (#2169)
* fix(api): validate API_TIMEOUT_MS in the native Anthropic clients
The native Anthropic client path parsed API_TIMEOUT_MS with a raw
parseInt: `parseInt(process.env.API_TIMEOUT_MS || String(600 * 1000), 10)`
in client.ts and `parseInt(process.env.API_TIMEOUT_MS || '', 10)` in the
non-streaming fallback. Because `||` only substitutes the default for an
empty/unset value, any non-empty malformed value ("abc", "25ms") is truthy
and parses to NaN, and a negative value passes straight through. A NaN or
negative timeout on the SDK client is undefined behavior, and an oversized
value overflows the 32-bit setTimeout ceiling into a tiny/immediate delay.
The OpenAI-compatible shim already routes API_TIMEOUT_MS through
getApiTimeoutMs, which rejects non-digit/negative input, falls back to a
default, and clamps to the 32-bit ceiling. Reuse that single parser in the
native clients too. getApiTimeoutMs gains an optional fallbackMs argument so
the non-streaming path keeps its context-specific default (120s on remote,
300s otherwise) while still validating and clamping the override; existing
shim callers are unaffected (the default remains 600s).
Tests cover the fallback argument in the parser and assert the constructed
native client's timeout for malformed, negative, zero, unset, valid, and
oversized values.
* test(api): cover the non-streaming fallback timeout and pin route env
Add direct coverage for getNonstreamingFallbackTimeoutMs, which the previous
tests only exercised indirectly through the shared parser. It now asserts the
context-specific defaults survive the change (300s local, 120s remote) for
missing and invalid API_TIMEOUT_MS, that a valid override is honored in both
contexts, and that an oversized one is clamped. The function is exported for
this; test files are knip entry points, so it does not read as dead code.
Also clear every provider route-selection variable explicitly in the native
client timeout test. The suite's afterEach already restores them, but pinning
them up front keeps an inherited CLAUDE_CODE_USE_OPENAI (or another route
flag) from diverting getAnthropicClient into the shim and measuring the wrong
client's timeout.
* test(api): pin the native client path and document the timeout contract
The native timeout test cleared many provider variables but left
NEARAI_API_KEY untouched, and the suite never snapshotted it at all.
NEARAI_API_KEY alone selects the env-only Near AI route, and clearing the
competing vendor keys removed the very credentials whose presence suppresses
it, so an inherited value routed getAnthropicClient to the OpenAI shim. The
shim is returned as a cast object with no SDK timeout, so the assertions read
undefined and the regression silently stopped being covered. CLINE_API_KEY had
the same gap.
Snapshot, clear, and restore both alongside the other route-selection inputs,
and assert the constructed object is an Anthropic instance before reading its
timeout, so a stray variable or a future env-only route fails loudly instead
of weakening the test. Verified by injecting NEARAI_API_KEY: the guard now
fails on the shim object rather than passing on undefined.
Also refresh the API_TIMEOUT_MS reference, which still said the Anthropic SDK
kept its own timeout handling. It now describes both consumers: the
headers-deadline semantics for OpenAI-compatible paths, and the native
Anthropic SDK request timeout plus the non-streaming fallback's own defaults
(120s remote, 300s otherwise), under the same validation and clamping.
|
||
|
|
decad0e172 |
fix(openai-shim): request streaming usage from compatible local providers (#2144)
* fix(openai-shim): request streaming usage from local providers * test(openai-shim): verify cached streaming usage accounting * fix(openai-shim): retry strict streams without usage options |
||
|
|
cbbe10ff8a |
fix(frontmatter): anchor the closing --- to the start of a line (#2027)
* fix(frontmatter): anchor the closing --- to the start of a line The opening delimiter was anchored but the closing one was not, and [\s\S]*? is lazy, so parsing stopped at the first `---` appearing anywhere -- including inside a value. A description reading "Reviews code --- thoroughly" ended the block early: the value was truncated and the remaining frontmatter lines plus the real delimiter leaked into the body that is sent to the model. A `---` line inside a block scalar did the same. Requiring the captured block to be empty or to end at a line break pins the close to a line start. The m flag would also work for the close but would un-anchor the open, letting a horizontal rule partway down a body be read as frontmatter. Tightened the trailing run to spaces and tabs as well, since \s* matched a newline and accepted a bare `---` with no line terminator after it. Affects every .md frontmatter consumer: agents, skills, slash commands, output styles and memory files. * test(frontmatter): fold the delimiter cases into the existing suite A separate test file adds a slot to bun's sequential file ordering, which shifted which suite runs before which and surfaced an unrelated mock leak in CI (taskReport git metadata and the /ads command failed on both Node versions, neither touching frontmatter). The cases belong next to the existing parser coverage anyway. * test(frontmatter): cover tabs after both delimiters * fix(frontmatter): accept CRLF delimiter lines Windows-authored Markdown terminates the `---` delimiters with `\r\n`. The `[ \t]*\n` matcher rejected the carriage return, so such files were treated as having no frontmatter. Accept an optional `\r` on the open, captured body, and close line endings. * fix(frontmatter): keep consuming blank separator lines after the close Anchoring the closing delimiter narrowed its trailing match from `\s*` to just the delimiter's own line ending, so a conventional blank line between the frontmatter and body survived as a leading newline in the parsed content. Skill and plugin-command bodies are fed into prompts untrimmed, so that became a stray newline in the model instructions. Consume trailing whitespace-only lines again after the (still strictly validated, line-terminated) close, which cannot revive the mid-document false close since it only runs once a valid terminator matched. * fix(frontmatter): close empty frontmatter at the first delimiter line The anchored close made the captured block's outer quantifier greedy, so empty frontmatter followed by a body horizontal rule (`---\n---\n---`) read the second delimiter as YAML and closed on the third, swallowing the rule. Make the outer capture lazy so an empty block closes at the first `---` line as it did before anchoring; real frontmatter still matches on backtrack. Fixes the same shape hard-failing `claude plugin validate`. |
||
|
|
c3930ca5ad |
fix(mcp): resolve server names by own-property, not the prototype chain (#1983)
* fix(mcp): resolve server names by own-property, not the prototype chain
getMcpConfigByName and the mcp remove handler look names up in plain
object maps built from JSON config with a bare servers[name] truthiness
check. Reserved names ('constructor', '__proto__', 'toString', …) resolve
to inherited Object.prototype members, which are truthy, so:
- `mcp get constructor` skips the not-found guard, prints a fabricated
record, and hands the Object constructor to the health check;
- `mcp remove constructor` reports the reserved name as present in
multiple scopes and prompts to pick one instead of "No MCP server found".
The same leak reaches runAgent and the print handlers, which all route
through getMcpConfigByName. Gate every lookup on Object.hasOwn so only
real, own-property server names resolve.
* test(mcp): restore project mcpServers in afterEach for isolation
Save and restore getCurrentProjectConfig().mcpServers the same way the
global config is handled, rather than hardcoding undefined, so the test
never leaks state into suites that share the in-memory test config.
* fix(mcp): cover the remaining prototype-name mutation and doctor paths
The own-property gate only covered unscoped removal and getMcpConfigByName.
The scoped paths still used bare lookups:
- removeMcpConfig's project/user/local existence checks accepted inherited
members, so 'mcp remove constructor -s user' reported a successful removal
while leaving the configuration untouched;
- addMcpConfig's already-exists checks rejected valid 'mcp add constructor';
- doctor's servers[name] and activeServers[name] fabricated definitions for
prototype names.
Gate all of them on Object.hasOwn. Also reject the name '__proto__' at add
time: it passes the character check but assigning it on a plain object hits
the prototype setter instead of creating an own property, so the server
would be reported as added and silently vanish.
Restore NODE_ENV in the test teardown alongside the config state.
* fix(mcp): report a reserved __proto__ entry in file config
A hand-authored .mcp.json can contain a server named "__proto__": JSON.parse
gives it a real own key, but it cannot be copied onto a plain object, so the
schema's rebuild dropped it before validation ever ran. The entry simply did
not exist and nothing said why, and with own-property lookups the scoped
removal path now correctly reports it as absent -- so there was no way to
learn the name was the problem.
Detect it on the raw parsed config and surface a fatal validation error
naming the entry, matching the rejection addMcpConfig already performs for
the same name. The rest of the file still parses.
* test(mcp): serialize the proto-name suite on the shared mutation lock
The suite swaps NODE_ENV and the process-wide global and project MCP
configurations without holding sharedMutationLock, so bun can run it
alongside another state-mutating file: that file observes the injected
realserver/locallyreal fixtures, or its own updates are overwritten when
this teardown restores its snapshots.
Acquire the lock in setup and release it from a finally in teardown, the
same shape officialRegistry.test.ts uses.
Also cover the reserved __proto__ entry arriving from parsed file config.
* fix(mcp): reserve constructor alongside __proto__
With own-property lookups in place, `mcp add constructor` persists an entry
the config schema then rejects -- and it rejects the whole mcpServers
object, so the newly added server is unusable and every other server in that
scope stops loading with it.
Refuse the name at add, and name it at file ingress: the only diagnostic
before was a generic "does not adhere to schema" against `mcpServers`, which
does not say which entry is at fault. The scan runs ahead of the schema
parse because that path returns early. `__proto__` and `constructor` are the
only two names that fail a write/read round trip -- toString,
hasOwnProperty, valueOf and the rest all persist and read back correctly.
* fix(mcp): reject a config with a reserved server name outright
parseMcpConfig flagged a fatal reserved name but, for __proto__, still returned
a usable partial config because zod's rebuild silently drops the key and the
schema parse succeeds. Callers that branch on the config -- the --mcp-config
ingress in main.tsx -- then took the partial config and discarded the error,
starting with the bad entry quietly gone. Return config: null whenever a fatal
reserved-name error is present, matching the constructor path where the schema
already fails, so the invalid input is rejected at every consumer.
* fix(mcp): keep reserved-name findings visible in all-server doctor output
doctorAllServers builds server reports only for names that survived parsing or
are active, and attaches server-keyed findings to those. A fatal reserved-name
error is keyed by a name that never survives parsing, so its finding was built
into no report and dropped -- mcp doctor --config-only read clean while the
invalid config was present. Surface any finding whose server has no report as a
global finding.
* fix(mcp): do not mutate a fatally poisoned project .mcp.json
A reserved server name (`__proto__`/`constructor`) now fails the whole
parse and returns config: null, so getProjectMcpConfigsFromCwd reports an
empty map even though valid siblings remain on disk. Project-scope add
rebuilt the file from that empty snapshot and wrote only the new server,
silently dropping every sibling; project-scope remove reported a valid
sibling as "not found". Refuse to mutate the file when it fails to parse,
naming the offending entry, instead of treating the empty map as truth.
* fix(mcp): surface reserved-name errors in single-server doctor output
doctorServer set report.findings to only the global findings and never
applied the orphan fold doctorAllServers uses, so a fatal reserved-name
error in a poisoned scope was dropped when the requested target lived in
another scope -- exit 0 with the real fault hidden. Promote findings for
names other than the reported one, and skip the state.not_found branch
when a validation finding already explains the requested name so the
report no longer carries two blocking findings with contradictory text.
* fix(mcp): honor the fatal-parse contract across every scope
The config:null contract was only enforced on project-scope .mcp.json.
Extend it so a fatally poisoned scope is never silently mutated:
- Re-check the project snapshot immediately before the write rebuild, not
only at the existence check -- the file can go fatal in between, and
rebuilding from the resulting empty map would drop valid siblings.
- Refuse user/local add and remove when that scope parses to config:null,
so the CLI no longer reports success for a scope that then loads nothing
(or mutates a sibling in a raw map that stays unloadable).
- Gate enterprise exclusive control on the managed file's presence, not on
a successful parse, so a poisoned managed-mcp.json can't silently drop
the policy lock and let user/project servers take over.
Generalize the guard to assertMcpScopeWritable(errors, scopeLabel).
* test(mcp): pin allowedSettingSources so the local-scope guard is hermetic
getMcpConfigsByScope() returns an empty writability-error list when a scope's
setting source is disabled, and allowedSettingSources is a process-wide global
other suites mutate. In bun's file order a suite that leaves localSettings
disabled (e.g. one exercising --setting-sources) would make the 'fatally
poisoned local scope' case skip its guard, so addMcpConfig(...'local') resolved
instead of rejecting -- the intermittent CI failure at config.protoName.test.ts.
Pin the full source set in beforeEach and restore it in afterEach, matching the
NODE_ENV and MCP-config snapshotting this suite already does.
* fix(mcp): guard scope mutations on raw parse errors, not the source filter
assertMcpScopeWritable read errors from getMcpConfigsByScope()/
getProjectMcpConfigsFromCwd(), which suppress errors to an empty list when a
scope's setting source is disabled. addMcpConfig/removeMcpConfig still mutate
the raw mcpServers maps, so under a narrowed --setting-sources set a fatally
poisoned scope could be written or deleted (clobbering valid siblings) while the
CLI reported success. Add getScopeMutationErrors(), which parses each scope's
raw source directly, and route every write guard through it.
* fix(mcp): detect unscoped-remove membership from parsed scope views
Unscoped `mcp remove` read local/user membership from the raw
getCurrentProjectConfig()/getGlobalConfig() maps while project used the parsed
view. A fatally poisoned local/user scope has no loadable servers yet still
holds the raw entry, so the handler listed the server as living there and then
removeMcpConfig refused with 'Cannot modify … config'. Read all three scopes
through getMcpConfigsByScope() so detection matches what is actually removable.
* fix(mcp): read the raw project scope for mutations, not the source view
getScopeMutationErrors only covered the write guard's errors; the project
existence check and .mcp.json rebuild still read servers from the
source-gated getProjectMcpConfigsFromCwd(). With projectSettings excluded from
--setting-sources that returned an empty map, so an add rebuilt the file
without the valid siblings and a remove mis-reported the server as absent.
Drop the source gate from getProjectMcpConfigsFromCwd() (a mutation-only read)
so it always sees the real file, and fold the project write guards back onto
its returned errors. Regression covers add/remove with projectSettings off.
* test(mcp): re-pin the poisoned local fixture atomically per mutation
The local-scope poison regressions flaked under the full parallel suite:
sharedMutationLock serializes other lock holders but not every writer of the
process-wide test project config or NODE_ENV, so a stray async task from another
suite could clobber the fixture during an await gap between the setup and the
assertion. addMcpConfig/removeMcpConfig reach their scope guard with no awaited
work in between, so re-establishing NODE_ENV, the enabled sources, and the
poisoned config synchronously immediately before each mutation (pinPoisonedLocalScope)
keeps the guard's read atomic regardless of what ran during earlier awaits.
* fix(mcp): surface managed-mcp.json parse errors in enterprise mode
Enterprise exclusive mode engages on the managed file's presence, so a
malformed or reserved-name managed-mcp.json fail-closes every other MCP source.
getClaudeCodeMcpConfigs returned errors: [] for that branch, and
getSettingsWithAllErrors aggregated only user/project/local, so startup and the
MCP UI saw an empty server list with no diagnosable reason. Propagate the
enterprise scope's parse errors as generic-error PluginErrors from the exclusive
branch and include the enterprise scope in the settings error aggregation.
* fix(mcp): detect unscoped-remove membership source-filter-independent
Reading membership from getMcpConfigsByScope applied the --setting-sources load
filter, so an unscoped `mcp remove foo` reported "No MCP server found" for a
clean user/local/project entry that removeMcpConfig(foo, scope) still mutates
when that source is narrowed out. Read each scope the same way removeMcpConfig
resolves existence -- the raw getCurrentProjectConfig()/getGlobalConfig() maps
and getProjectMcpConfigsFromCwd() -- still own-property gated so inherited
members are not treated as present.
* fix(mcp): surface managed-mcp.json errors in headless startup
The headless (-p) MCP consumer destructured only servers from the
config promise and discarded errors. A fatal managed-mcp.json
fail-closes every file-based MCP source, so scripted users saw an empty
server list with no diagnostic — indistinguishable from an intentionally
empty configuration. Emit the config errors on stderr in non-interactive
sessions (interactive already surfaces them via the MCP error UI).
* fix(mcp): enforce enterprise-exclusive boundary in named lookups
getMcpConfigByName() gated plugin-only mode but not the enterprise-
exclusive policy. A present managed-mcp.json takes exclusive, fail-closed
control of MCP (its mere presence engages the policy, even when the file
is malformed), and getClaudeCodeMcpConfigs() drops every non-enterprise
source accordingly — but the named lookup fell through to the user/
project/local maps. A user with a locally configured server plus an
invalid managed file could therefore still resolve that server by name
via 'mcp get <server>' (checkMcpServerHealth) or an agent definition's
named-server reference (runAgent), bypassing the intended policy.
Return only an enterprise-owned entry (or null) whenever
doesEnterpriseMcpConfigExist() is true, before consulting other scopes,
mirroring the boundary getClaudeCodeMcpConfigs() already enforces.
|
||
|
|
d16318a47f | fix(xai): validate OAuth state before settling callbacks (#2228) | ||
|
|
e2b021d8bb |
fix(plugins): keep Windows marketplace cache on copy ENOENT (#2220)
* fix(plugins): keep marketplace cache when Windows copy hits ENOENT (#2183) ChromeDevTools marketplace add cloned successfully then failed finalize because recursive fs.cp throws on unreadable nested files. Keep the validated clone and join tilde plugin-cache paths so Windows does not glue the home directory onto .openclaude. * fix(plugins): keep marketplace cache if dest cleanup throws (#2183) Copy-fallback recovery still failed add when removing a partial dest threw, and getMarketplace refetch did not persist a keep-temp cachePath. * fix(plugins): use persisted installLocation after marketplace refetch (#2183) Keep-temp recovery can change cachePath on disk while same-call getPluginById and install-by-name still returned the pre-refetch path. * fix(plugins): persist keep-temp installLocation only for remote sources getMarketplace refetch was rewriting file/directory installLocation to the marketplace root, which can make later remove delete a user directory. |
||
|
|
055e5d551a |
feat(launcher): support --max-old-space-size-percentage (#2219)
* feat(launcher): support --max-old-space-size-percentage heap sizing Convert Node's percentage heap flag into --max-old-space-size from constrained or total RAM so small containers and large workstations can avoid the fixed 8192 MB cap on every supported Node version. Fixes #2213 * fix(launcher): reject unconstrained memory sentinels in heap percentage Ignore libuv UINT64_MAX constrainedMemory values, clamp sub-megabyte percentage results to 1 MB, and keep spaced heap-flag values on background Node launches. * fix(launcher): report unresolved heap percentage instead of silent MB fallback A valid percentage with unknown available memory no longer looks like an unrelated megabyte env or default success; the launcher warns once, docs state full precedence, and child NODE_OPTIONS tests call the real helper. * fix(launcher): strip launcher heap flags when Node already has a cap Commander rejected --max-old-space-size-percentage on native heap+gc and disable-relaunch paths. Strip those argv tokens before import, and do not treat a following non-percentage word as the flag value. * fix(launcher): propagate execArgv heap caps to subprocess NODE_OPTIONS Child tools inherit NODE_OPTIONS, not the parent process.execArgv. When the CLI already started with a numeric --max-old-space-size cap there, copy that value into NODE_OPTIONS instead of defaulting to 8192 MB. Also strip launcher-only heap flags on the OPENCLAUDE_HEAP_RELAUNCHED early-return path and harden launcher integration tests with Node 22-safe execArgv fixtures. |
||
|
|
2e687df4ec |
fix(image): allow large/metadata-less screenshots through on resize failure (#1964) (#1970)
* fix(image): allow large/metadata-less screenshots through on resize failure (#1964) Stop Alt+V paste from falling through to "No image found in clipboard" when the native image connector returns undefined metadata or a screenshot exceeds 1568px. - Reorder the metadata guard so an undefined metadata object is handled before reading metadata.format (previously threw TypeError and was swallowed into a "no image" result). Fall back to magic-byte format detection. - Drop the `!overDim` gate from the catch-block allow-through so a dimensionally-large but base64-small image passes through. The API resizes images >1568px server-side; only the base64 size is a hard limit. - Keep IMAGE_MAX_WIDTH/HEIGHT at 1568; only the crash and gate logic changed. - Add imageResizer.test.ts covering the undefined-metadata path, the overDim<=5MB allow-through regression, the >5MB throw, and the happy path. * fix(image): enforce many-image dimension limit in resize-failure fallback (#1970) When the native image processor crashes, the fallback previously returned the original buffer unchanged whenever its base64 size was <= 5MB, with no dimension check. That let oversized images (e.g. 3840x2160 PNG/JPEG/WebP) stay in conversation history and later break many-image requests with a 400 "image dimensions exceed ... many-image" error. - Add IMAGE_MANY_IMAGE_MAX_WIDTH/HEIGHT (2000px) to apiLimits. - In the resize-failure fallback, detect images exceeding the 2000px many-image limit via magic-byte dimension parsing (PNG IHDR, WebP VP8/ VP8L, JPEG SOF0/2/3, GIF screen descriptor) and, when possible, downsample with platform Canvas APIs (awaiting a fully-decoded source). If downsample is unavailable or the result still exceeds the 5MB payload budget, reject with ImageResizeError instead of returning the oversized original. - Unknown/unparseable dimensions fail safe (treated as exceeding the limit). - Correct two pre-existing WebP dimension-offset bugs surfaced during review. Adds regression tests for PNG/JPEG/WEBP/GIF over the many-image limit. * fix(image): address review - media-type subtype, WebP offsets, Canvas DOM resolve, metadata-less budget - ResizeResult.mediaType is the subtype ('png'/'jpeg'), not a full MIME type. The Canvas downsample branch wrongly returned 'image/png'/'image/jpeg'; corrected to 'png'/'jpeg' to match every other return in the file. - WebP dimension parser corrected against real sharp-encoded frames: VP8L transform header reads from byte 21 (bits[0..13] width, [14..27] height); VP8 lossy width/height read from bytes 26/28. Previous offsets were off and produced wrong dimensions. - Canvas fallback now resolves createElement/Image from document (browser/ Electron) with a globalThis fallback, so it actually engages where Canvas is available. - metadata-less + oversized branch now tries progressive JPEG quality [80,60,40,20] and only returns an in-budget result; otherwise fails via the user-facing limit error instead of returning an oversized buffer that validateImagesForAPI would reject (the regression the PR recovers from). - Add WebP/VP8L fixtures and tests asserting exact parsed dimensions and in-limit acceptance. * fix(image): address 4 P1 review findings in resize-failure fallback - Metadata-less branch now enforces the many-image 2000px limit via a shared enforceManyImageDimensionLimit helper (extracted from the catch-path guard), instead of letting compact high-resolution screenshots pass through unchecked. - VP8 lossy WebP dimensions are stored directly (no -1 bias per RFC 6386); only VP8L uses minus-one encoding. Fixed parser and test fixture. - Add VP8X (extended WebP) dimension parsing, needed for alpha/animation. - DOM Image fallback now constructs with no args and assigns src after installing onload/onerror, since the Image constructor takes width/height, not a URL. * fix(image): require raw dimensions before canvas downsample in many-image guard readImageDimensions can return null for unparseable buffers; falling back to 0,0 made tryDownsampleToManyImageLimit treat the image as 1x1 and silently downsample to a single pixel instead of throwing ImageResizeError. * fix(image): keep in-budget 4K pastes when Canvas resize fallback is unavailable The many-image 2000px guard rejected Windows clipboard screenshots whenever image_processor_napi failed and Canvas was absent, recreating #1964. Pass those images through, invoke DOM canvas methods with their owners, and skip JPEG fill/TEM bytes before reading segment lengths. * fix(image): reject API-hard 8000px edges and surface paste resize errors Passthrough after a processor crash was sending images the API hard-rejects and still mapping ImageResizeError to "No image found". Keep 4K single-image paste, fall through from createImageBitmap to Image, and show the real resize error on Alt+V. * fix(image): document paste resize errors and test native rethrow Clipboard ImageResizeError was still easy to treat as a missing reader on the native path, and the Alt+V vs generic notification contract had no focused tests. Share the paste error helpers, document the 5MB/8000px prompt, and cover native resize rejection without enabling NATIVE_CLIPBOARD_IMAGE. * test(image): stabilize clipboard mock module identity * fix(image): close resize fallback review gaps * test(image): cover JPEG canvas fallback subtype * fix(image): downsample before enforcing API edge * fix(paste): settle rejected image path reads * test(paste): isolate rejection regressions * fix(image): report payload limit after fallback * test(image): restore mocked modules after suites Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(images): enforce many-image limits at Anthropic request boundary Count retained history and tool-result images, verify resized payload dimensions, and report actionable failures before dispatch. Exercise mock restoration deterministically. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(images): preserve resize failure diagnostics at request boundary The many-image validation catch replaced the original image-processing error with a generic RequestImageDimensionsError without logging it or keeping a cause chain, so logAPIError and the assistant error path only ever saw the wrapper message. - Log the underlying processing failure via logError before wrapping. - Rethrow an existing RequestImageDimensionsError unchanged instead of reconstructing it. - Attach the original error as the wrapper's cause; ImageResizeError and RequestImageDimensionsError now forward ErrorOptions to super. - Expand usesAnthropicImageLimits coverage to the reachable isFirstPartyBaseUrl:false input for bedrock/vertex/foundry. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix: count partner documents in request image limits --------- Co-authored-by: jatmn <the@jat.mn> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> |
||
|
|
eb3c5902eb |
feat(skills): add verify for revocations and eyebrow drift checks (#2215)
* feat(skills): add verify for revocations and eyebrow drift checks * apply code reviews fixes * fix(skills): read execute bits through the fs seam, skip symlink tests where unsupported * fix(skills): check X_OK through the fs seam, report symlink tests as skipped |
||
|
|
0b68e579b9 |
fix(profiles): apply context limit to all profile models (#2201)
* fix(profiles): apply context limit to all models * fix(profiles): include saved model in context limits * test(profiles): cover saved model context lifecycle * fix(profiles): align context limit keys with runtime models --------- Co-authored-by: fancivez <fancive@gmail.com> |
||
|
|
1afeb4b1e7 |
docs: add a skills guide (#2211)
* docs: add a skills guide * docs: imprvements on skills doc * docs(skills): address review on the skills guide * docs(skills): correct verify exit code descriptions * docs(skills): state what each check covers * docs(skills): align validate wording and name each install path condition |
||
|
|
ec850d2d1a |
docs(web): add llms.txt for LLM discovery (#2205) (#2209)
* docs(web): add llms.txt for LLM discovery (#2205) Hosts an llmstxt.org-spec summary of OpenClaude at the website root so LLMs (ChatGPT et al.) have an authoritative source and stop conflating the project with unrelated tools named "Openclaw". * docs(web): address review feedback on llms.txt - Clarify the License entry: MIT applies only to OpenClaude contributors' modifications, not the underlying Claude Code (Anthropic proprietary). Addresses Greptile's misstatement flag. - Convert the bare npm one-liner in the Install section into a Markdown linked list entry per the llmstxt.org spec. Addresses CodeRabbit's "link-only sections" note. * fix(web): make AUR entry in llms.txt hyperlink-first The 'AUR package: [openclaude](...)' entry put text between the list marker and the hyperlink, which makes the reference llms.txt parser fail with AttributeError ('NoneType' has no attribute 'groupdict') and aborts parsing of the whole document. Use link-first syntax preserving destination and meaning. Verified with the reference parser (parse_llms_file): 4 sections, 21 links, all URLs correct. web:build passes and web/dist/llms.txt matches source byte-for-byte; web:typecheck clean. --------- Co-authored-by: Gravirei <gravirei@users.noreply.github.com> |
||
|
|
0abfca30e5 |
fix(sdk): preserve async generator session context (#2204)
* fix(sdk): preserve async generator session context * fix(sdk): complete async context boundaries * test(sdk): assert queryAsync init isolation and close V2 sessions. Replace the source-text queryAsync check with a behavioral observation of init, and release concurrent V2 sessions so the async-context coverage matches the runtime contract. |
||
|
|
3609d751c0 |
fix: identify OpenCode Go requests (#2203)
* fix: identify OpenCode Go requests * fix: harden OpenCode Go identity headers * fix: pin OpenCode session across retries |
||
|
|
5b9daef605 |
feat(providers): add Command Code hybrid gateway (#2196)
* feat(providers): add focused Command Code hybrid gateway Register Command Code as a descriptor-first OpenAI-compatible aggregating gateway with a hybrid catalog, dedicated CMD_API_KEY credentials, and the same surgical sibling wiring used by LLMTR. * fix(providers): reject Command Code placeholder keys and restore saved secrets on relaunch Treat CMD_API_KEY placeholders as unusable at request time, and migrate a profile-owned persisted OPENAI_API_KEY into CMD_API_KEY on canonical Command Code restart when dedicated keys are missing. * fix(providers): re-apply Command Code when the dedicated key drifts Profile apply already writes CMD_API_KEY, but alignment only compared OPENAI_API_KEY, so a stale dedicated secret could keep winning request auth. * fix(providers): isolate Command Code from leftover OpenAI keys Selecting --provider commandcode left a distinct generic OPENAI_API_KEY in-process because Command Code shared LLMTR's fallback path. Mirror the dedicated credential or clear the generic key on the canonical endpoint. * fix: enforce Command Code transport contract * fix: apply model override before validation * fix: support inline model overrides * fix: align early model parsing with CLI * fix: address Command Code review feedback * fix: validate Command Code profile models * fix: keep startup model display in sync * fix: avoid echoing rejected Command Code models * fix: share effective model flag parsing * fix: preserve teammate provider overrides * fix: isolate command code startup state * fix: align command code startup state * fix: close command code route gaps * fix: preserve teammate route precedence * fix: align launcher and root option parsing * fix: preserve model and credential semantics * fix: reject Claude aliases on Command Code * fix: preserve root --model after a consumed delimiter Required-value options such as --system-prompt consume a following -- token, so early Command Code model recovery must scan the full argv instead of truncating at the first delimiter. * fix: reject Command Code Claude models in /model and lists The shared Chat Completions predicate only inspected whole strings, and /model still applied OpenClaude aliases. Reject list members and block those selections on the Command Code route. * fix: ignore nested --model when applying --provider Command Code preflight was last-wins on full argv, so a nested aimlapi/auto-mode --model could abort provider selection even when the root session model was valid. * fix: unmount Ink if /model wait times out The Command Code /model tests left the Ink instance registered when waitForCondition rejected, which can leak into later tests. * fix: enforce Command Code contracts at profile write time Reject incompatible models and capture dedicated CMD credentials in toProfile so Console OAuth env adoption and other add/update callers cannot persist Chat Completions-invalid Command Code state. Align background session metadata with the same root --model argv slice used at CLI startup. * fix: persist Command Code dedicated keys over leftover OpenAI env Env adoption that copies OPENAI_API_KEY must not store a generic secret on a canonical Command Code profile when CMD_API_KEY is present. Document that the route still requires explicit selection. * fix: test background session root --model from launch argv Replace the source-text assertion with the shared metadata helper used by handleBgFlag so nested aimlapi/auto-mode --model flags cannot silently become the recorded session model. * fix(commandcode): unify route validation contracts * fix(commandcode): preserve explicit profile credentials * fix(cli): preserve explicit provider routing * fix(cli): align provider option consumers * fix(commandcode): align credential and discovery contracts * docs(commandcode): clarify Claude model support * fix(bg): align persisted provider metadata * fix(commandcode): preserve model and base defaults |
||
|
|
0ea8eefbd0 |
feat(skills): enforce registry revocations.json on install (#2187)
* feat(skills): enforce registry revocations.json on install The registry ships a revocations.json kill switch that nothing reads. Installs now fetch it from beside the registry (or OPENCLAUDE_SKILLS_REVOCATIONS_URL) and refuse a skill whose id, version, or sha256 matches an entry. A missing list revokes nothing; a malformed list fails the install. * fix(skills): fail closed and validate revocation entries Review follow-up: only a confirmed-absent revocation list (ENOENT or HTTP 404) is treated as empty; other read failures block the install. The list must be a JSON array and every entry is schema-checked (non-empty id/version strings, 64-hex sha256, at least an id or a digest). Adds tests for the OPENCLAUDE_SKILLS_REVOCATIONS_URL override, invalid entries, non-array lists, and unreadable lists. * docs(skills): add docstrings to revocation helpers * test(skills): isolate revocation override and cover remote failure paths |
||
|
|
3451187aed |
fix(ctx): let explicit overrides beat discovered context windows (#2082)
* fix(ctx): prefer known model limits over generic 128k discovery Proxies such as OmniRoute often report context_length 128000 when per-model metadata is missing. That discovery value was beating known descriptors and settings.modelLimits, so 1M models auto-compacted against a 128k budget. Prefer larger known descriptors over the generic 128k discovery default, and let settings/env overrides beat discovery. Document the override path in /set-context-window help. Refs #2081 * test(ctx): cover OmniRoute + gpt-5.6-sol (user-reported gpt sol) The Discord report used GPT-5.6 Sol, not gpt-5.4. Regression now pins the catalog-less custom-route rescue to the 272k descriptor for gpt-5.6-sol. Refs #2081 * fix(ctx): let explicit overrides beat discovered context windows Addresses both review findings on #2082. P1 — drop the generic-128k rescue from the previous commit. The custom gateway discovery mapper copies an endpoint's own context_length / context_window into ModelCatalogEntry.contextWindow, and nothing synthesizes 128k on our side, so the numeric value carries no provenance: a flat 128000 is indistinguishable from a real per-deployment or tenant cap. Budgeting a known-larger descriptor over that cap traded an early auto-compact for a late context-window API failure. Discovery is authoritative over the model descriptor again. What remains is the safe half of the fix: an env prefix override and settings.json modelLimits now sit above discovery, so a user on a gateway that advertises the wrong window can pin the real one. Docs and /set-context-window help point at that path. Tests cover a gateway-advertised 128k and 200k window staying put for a model the catalog knows is larger, plus env and modelLimits overrides beating it. P3 — isolate the discovery-cache fixtures. getClaudeConfigHomeDir() ignores CLAUDE_CONFIG_DIR by design, so both the new modelLimits test and the pre-existing withTempConfigDir helper were writing fixtures into the caller's real config dir. Both now use setClaudeConfigHomeDirForTesting with save and restore, and clear the discovery cache on teardown so the in-memory sync snapshot cannot leak into a later suite. The modelLimits test now asserts the isolated cache resolves on its own before asserting the settings pin wins. Refs #2081 * test(ctx): cover env prefix overrides over discovery cache CodeRabbit on #2082 asked for a regression where CLAUDE_CODE_OPENAI_* prefix keys beat a seeded discovery cache for both contextWindow and maxOutputTokens, not just exact keys and settings.modelLimits. Refs #2081 * docs(ctx): Clarify permanent overrides for catalogued models Keep the documented workaround aligned with resolver precedence so users do not expect modelLimits to override built-in catalog entries. Refs #2081 |
||
|
|
aceacf0e59 |
feat(zai): add GLM-5.3-Flash Coding Plan support (#2185)
* feat(zai): add GLM-5.3-Flash Coding Plan support * test(effort): preserve scoped xhigh context * fix(zai): scope Coding Plan route metadata * fix(integrations): prefer explicit runtime endpoints * fix(integrations): preserve override runtime limits |
||
|
|
6c7efdeaf5 |
chore(main): release 0.30.0 (#2165)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>v0.30.0 |
||
|
|
b4af6f1884 |
test(settings): unit-test the multi-source merge customizer (#2176)
* test(settings): unit-test the multi-source merge customizer settingsMergeCustomizer is exported for testing but had no direct coverage, despite being the seam that combines policy, user, and project settings. Cover the documented behaviour: permission arrays concatenate with deduplication under target priority, modelPricing entries replace atomically per model id on a null-prototype map (including Object.prototype-named ids), and all other keys defer to lodash's default deep merge. * test(settings): assert the merged modelPricing map is null-prototype The previous assertion checked a fresh unrelated object, which would pass even if the customizer returned a plain object carrying the keys. Assert Object.getPrototypeOf on the merged map itself. |
||
|
|
aaccb57721 |
fix(integrations): keep managed AIMLAPI attribution over caller headers (#2179)
* fix(integrations): keep managed AIMLAPI attribution over caller headers getRouteDiscoveryHeaders spread options.headers after resolveAimlapiAttributionHeaders had already sanitized the descriptor headers, so caller-supplied values won every collision and undid the sanitizer: a partner id from ANTHROPIC_CUSTOM_HEADERS overrode the one resolvePartnerId had just re-stamped, and attribution headers were re-added after the non-canonical filter stripped them. Fold caller headers into the sanitizer's input so both branches see them, and keep the previous descriptor-then-caller precedence for every non-aimlapi route so ordinary custom headers are unaffected. Refs #2178 * fix(integrations): Strip AIMLAPI attribution headers case-insensitively. Fetch combines duplicate header names, so a caller `x-aimlapi-source` could ride alongside the managed `X-AIMLAPI-Source`. The shared resolver now removes every managed name case-insensitively before restamping a single canonical value, and the proxy path still drops the whole set. Refs #2178 --------- Co-authored-by: euxaristia <euxaristia@users.noreply.github.com> |
||
|
|
5f1ab9b80c |
fix(plugins): anchor marketplace hostPattern against lookalike hosts (#2177)
strictKnownMarketplaces hostPattern entries were compiled with new RegExp(pattern) and applied with regex.test(host). RegExp.test is a substring search, so an admin pattern that is not fully anchored matched any host merely containing it. Host authority reads right-to-left, so this is not just a missing leading anchor: a policy of `github\.mycompany\.com` is satisfied by an attacker-controlled `github.mycompany.com.evil.example`, which a leading `^` alone would still admit. It is also satisfied by `evil-github.mycompany.com`. isSourceAllowedByPolicy gates whether a marketplace may be installed at all, and installation leads to plugin code execution, so a bypass defeats the enterprise lockdown before anything is fetched. Anchor the pattern as `^(?:<pattern>)$` so it must match the entire host. The non-capturing group preserves a top-level alternation (`a\.com|b\.com` must not become `^a\.com|b\.com$`), and a pattern that is already fully anchored — the form the schema documents — behaves exactly as before. This tightens matching, so a deliberately loose pattern that relied on substring behavior now needs an explicit wildcard (`.*\.mycompany\.com`). That is the intended contract, and it can only ever narrow the allowlist, never widen it. The schema description now states the whole-host requirement. pathPattern is deliberately left alone: paths nest left-to-right, so its documented prefix form (`^/opt/approved/`) is correct and anchoring the end would break it. |
||
|
|
8db8830666 |
fix(settings): stop proto-named permission rules from aborting validation (#2170)
getCustomValidation looks a tool name up in the plain-object TOOL_VALIDATION_CONFIG.customValidation with a bare bracket access, so the prototype chain is live. validatePermissionRule gates tool names on an uppercase first character, which rejects the lowercase prototype members (constructor, toString, ...), but the double-underscore members slip through because '_'.toUpperCase() === '_'. A rule like "__proto__(x)" therefore reaches the lookup, which returns the inherited Object.prototype value (or, for "__defineGetter__(x)", a real inherited function). The caller treats that truthy value as a configured validator and invokes it, throwing an uncaught TypeError. filterInvalidPermissionRules runs that validation over every permissions allow/deny/ask entry when a settings.json is loaded. Its whole purpose is to skip one bad rule without rejecting the file, but the throw escapes: for a project .claude/settings.json the caller's catch discards the entire file's settings, and parseCommandOutputAsSettings (MDM) has no catch at all. A single hostile or fat-fingered rule in an untrusted cloned repo's settings thus silently wipes that file's configuration. Guard the lookup with Object.hasOwn so an unrecognized tool name resolves to undefined and the rule validates as an ordinary (inert) rule instead of crashing. Mirrors normalizeLegacyToolName, which already hardened the sibling LEGACY_TOOL_NAME_ALIASES lookup against the same class. |
||
|
|
30090c70e1 |
fix(api): scope Anthropic attribution to compatible request paths (#2147)
* fix(api): scope Anthropic attribution to compatible request paths * test(api): expand Anthropic attribution route coverage * fix(api): align managed OAuth attribution credentials * fix(api): preserve bare attribution auth * fix(api): align SSH proxy attribution auth |
||
|
|
ca7c3efb6e | fix(bg): identify sessions with persisted process markers (#2163) | ||
|
|
e8026263ca |
fix(tui): proper Unicode/IME input handling for composed sequences (#2018) (#2154)
* fix(tui): proper Unicode/IME input handling for composed sequences (#2018) * test(tui): address CodeRabbit review - hook-level IME coverage, full Unicode marks, astral code points, timeout regression tests |
||
|
|
54f963d006 | fix(openai-shim): drop synthetic tool-results marker and guard echoes (#2039) (#2153) | ||
|
|
39c3850c2e |
docs: tighten PR review expectations in CONTRIBUTING and AGENTS guides (#2151)
* docs: tighten PR review expectations in CONTRIBUTING and AGENTS guides - Add drift caveat to CodeRabbit findings: verify suggestions against PR intent before applying; decline out-of-scope with justification or ask a maintainer; never silently ignore findings - Add Keep Your Branch Current subsection (rebase duty, fix-churn warning) - Require full local CI-equivalent suite green before every push, with cross-platform exception - Add ignored/filler PR template submissions to close-without-review list - Expand follow-up guidance: multi-round review is normal, repeated fix requests signal root-cause investigation and better agent prompting - Mirror all of the above in AGENTS.md for coding agents * docs: address CodeRabbit findings on review-expectations guides - Make CONTRIBUTING.md Validation the single authoritative pre-push validation contract mirroring .github/workflows/pr-checks.yml exactly: --frozen-lockfile install, launcher compatibility checks, provider recommendation via npm as CI does, web job carve-out - Remove conflicting 'relevant subset' wording; cross-platform exception is the only carve-out from the full suite - AGENTS.md now defers to the CONTRIBUTING contract instead of defining a divergent core-checks list - Reword ambiguous 'submit the PR template ignored' bullet to 'submit a PR with the PR template ignored' * docs: align pre-push validation suite with CI semantics - Drop standalone 'bun run test:full'; bun run check already includes it - Document web workspace install (bun install --cwd web --frozen-lockfile) before web checks, matching the web CI job - Pass explicit --base/--head to security:pr-scan so local scans target the PR merge-base like CI does instead of script defaults * docs: use PR base commit ref for local security scan parity Replace git merge-base computation with origin/main and document the required invariant (fetch + keep branch rebased onto current origin/main) so the local scan matches CI's PR base.sha instead of diverging. * docs: use exact PR base for security scan * docs: make local validation contract portable * docs: scope local checks and baseline waivers * docs: harden contributor workflow guidance * docs: pin contributor safety contracts |
||
|
|
69aca780ea |
fix(effort): preserve known model exclusions when force-enabled (#2148)
* fix(effort): preserve known model exclusions when force-enabled * fix(effort): address review feedback * test(effort): cover provider-scoped capability overrides * fix(effort): preserve route-specific reasoning controls * fix(effort): honor scoped routing environment |
||
|
|
34536c6220 |
fix(settings): preserve concurrent updates (#2137)
* fix(settings): preserve concurrent updates Serialize the complete settings read-merge-write transaction under a physical-target lock with a bounded synchronous contention wait. Read the merge base fresh after ownership, preserve logical symlinks during publication, and route direct settings-sync replacements through the same lock. * fix(settings): address transaction review feedback * fix(settings): reject invalid merge bases * fix(settings): preserve lock ownership and apply outcomes * fix(settings): address transaction follow-up * fix(settings): avoid unsafe cleanup control flow * fix(settings): publish complete lock claims * test(settings): document pending lock claim * fix(settings): track lock owner process identity |
||
|
|
bb6d66faa3 |
feat(providers): live model lists for OpenRouter and OpenGateway (#2084)
* feat(providers): fetch live model lists for OpenRouter and OpenGateway Enable hybrid discovery so OpenGateway and OpenRouter load public GET /v1/models catalogs (with coding filters on OpenRouter), matching cairn-code and the Zero live-list fix. Refs #2083 * Address live model discovery review feedback. Remove hardcoded model allowlisting, deduplicate live MiMo routes, avoid duplicate startup probes, share mapping helpers, and strengthen provider documentation and tests.\n\nRefs #2083 * test(providers): Isolate OpenGateway picker discovery state. Prevent persisted live discovery cache entries from making the static catalog assertion nondeterministic. Refs #2083 * fix(test): restore OPENGATEWAY_API_KEY after discovery test The no-auth OpenGateway discovery test deletes OPENGATEWAY_API_KEY but originalEnv never snapshotted it and afterEach never restored it, so a worker starting with the credential set would run every later test in that worker without it. Snapshot and restore it like the other provider env vars. Refs #2084 * fix(integrations): preserve route shim maxTokensField for live-only discovered models * fix(test): drop unrelated permissions.test.ts optional-chaining tweak Not part of the OpenGateway/OpenRouter live discovery change; jatmn's review on #2084 flagged it as unrelated drift that should be dropped or split into its own PR. Refs #2084 * docs(integrations): Add JSDoc comments to model mapping helpers Add detailed JSDoc documentation for gateway model normalization, tooling and reasoning support detection, and core model mapping type guards and helpers across OpenGateway, OpenRouter, and modelMapping. Refs #2083 * fix(integrations): address review feedback on live discovery and proxy credentials Preserve caller credentials and custom headers for private route overrides, remove deep-research exclusion for text models, isolate test config directories, and align model picker assertions with upstream curated models. Refs #2083 Refs #2084 * test(integrations): test explicit openaiShim precedence and removeBodyFields merge Add unit test assertions verifying that explicit descriptor and catalog openaiShim configurations take precedence over inferred model settings and that removeBodyFields arrays merge correctly across layers. Refs #2083 Refs #2084 * Filter expired catalog entries at discovery boundary and revert permissions test hunk. Wrap static and merged route catalog model lists in filterAvailableCatalogEntries across all discoverModelsForRoute and refreshStartupDiscoveryForRoute return paths, preventing expired time-boxed catalog entries and live duplicates from resurfacing in model picker refresh, summary, or bootstrap additional options. Also restore permissions.test.ts to upstream/main without optional-chaining. Refs #2084 * Fix ModelCatalogEntry type import in model test suite. Import ModelCatalogEntry from descriptors.js rather than index.js to satisfy typecheck. Refs #2084 --------- Co-authored-by: euxaristia <euxaristia@users.noreply.github.com> |
||
|
|
1e56d4e7b2 |
feat(providers): add focused LLMTR hybrid gateway (#2150)
* feat: add LLMTR hybrid gateway * feat: support LLMTR_API_KEY * fix: allow LLMTR provider env files * fix: protect LLMTR credential routing * fix: protect LLMTR profile credentials * fix: complete LLMTR env lifecycle * fix: select LLMTR model before client setup * fix: address LLMTR review findings * fix: route LLMTR auxiliary models correctly * fix: complete LLMTR credential boundaries * fix: clear persisted LLMTR startup keys * fix: normalize LLMTR generic credentials * fix: scope LLMTR credential support * fix: align LLMTR credential boundaries * fix: close LLMTR credential boundaries * fix: clear stale LLMTR auth state * fix: clear persisted LLMTR credentials * fix: complete LLMTR setup contracts * fix: close LLMTR lifecycle gaps * fix(providers): close LLMTR credential boundaries * fix(providers): preserve saved LLMTR profile keys |
||
|
|
421f45992c |
chore(main): release 0.29.1 (#2143)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>v0.29.1 |
||
|
|
31ac8a6eca |
perf: stop busting the prompt cache and slim per-turn context (#2142)
* perf: stop busting the prompt cache and slim per-turn context Benchmarked against a comparable harness on grok-4.6 (identical one-shot coding task), OpenClaude used 84k total tokens per task with near-zero cache reuse. Root causes and fixes: - Auto-memory now defaults off in non-interactive (-p) sessions (src/memdir/paths.ts). The conversation-arc append gated behind it rewrote the system prompt every request (Date.now()-relative durations, running token counters, per-turn RAG retrieval), which invalidates implicit prefix caches from byte one on chat-completions providers. An explicit settings opt-in (autoMemoryEnabled / memory.autoWrite) still enables it; also drops the ~3.2k-token memory protocol section from one-shot runs. - The OpenAI shim no longer runs compressToolHistory for providers with implicit prefix caching (OpenAI, xAI, DeepSeek, Kimi/Moonshot, Codex) (requestPreparation.ts, both call sites). Its end-relative window retro-edits already-sent tool results each turn, mutating the middle of the request prefix — the native Anthropic transport already guards against exactly this (claude.ts shouldCompressNativeToolHistory). - Remove the wall-clock-relative "Ns ago" line from the multi-turn tracking block (conversationArc.ts) — it changed on every request. - Ship the ~1.7k-token git commit/PR protocol in the Bash tool description only when the session is inside a git repository (gitSettings.ts). The probe is cached per cwd, not per process, since worktree tools and daemon/SDK processes change directories mid-life. - Add a code-robustness bullet to the Doing-tasks system prompt section: derive timing-sensitive logic from elapsed time, and wire up every element introduced (prompts.ts). Measured on the same benchmark (8 runs): 84k -> ~46.6k total tokens per task (-45%), 89s -> ~60s wall clock, per-call cache reads up from a constant 128 tokens to 12k-29k, baseline context 16.8k -> 11.7k tokens. Tests: 573 targeted tests pass, including new coverage for the non-interactive memory default and the per-cwd git probe; tsc --noEmit clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: address review findings on the prompt-cache changes - Correct the prefix-caching route ids ('moonshot'/'kimi-code', not 'kimi'/'codex' — the latter never matched a real routeId) and replace the unanchored host regex with parsed-hostname comparison so path-routed gateways are not misclassified. - gitSettings: an explicit includeGitInstructions settings value now always wins over the repo probe (recourse for bare-repo/GIT_DIR layouts), and the probe reuses the existing LRU-memoized findGitRoot on getCwd() instead of a second process.cwd()-keyed implementation — fixing stale results after Bash `cd`, `git init`, and in daemon/SDK processes serving multiple directories. - Memory gate: env-provisioned memory (CLAUDE_COWORK_MEMORY_PATH_OVERRIDE, CLAUDE_CODE_REMOTE with a mounted memory dir) counts as explicit opt-in, so Cowork/remote sessions keep extraction and indexing. - Multi-turn tracking block: render only completed turns and drop the running token totals — the in-progress turn's tool-call list and the aggregate counters changed between model requests, still rewriting the system prompt mid-turn. - Update the Kimi K3 compression test to assert the new policy (history kept uncompressed on implicit-prefix-caching hosts) and extend gitSettings tests to cover settings overrides and session-cwd tracking. 569 tests pass, tsc --noEmit clean, benchmark re-run confirms metrics hold (45.1k total tokens, 62.8s, 3 calls). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: green CI and address CodeRabbit review on the prompt-cache changes CI: the conversation-arc suites assumed the multi-turn tracking block renders with only an in-progress turn, and that auto-memory is on in the (non-interactive) test process. Both now seed a completed prior turn, mark the session interactive where they exercise interactive behavior, and assert the new cache-stability invariants directly: the in-progress turn is never rendered, and no Duration/token-total lines appear. CodeRabbit findings: - Codex transport now skips tool-history compression too: Codex talks to OpenAI Responses backends with implicit prefix caching, and the end-relative compression window rewrites already-sent tool results, busting the cache (mirrors the openaiShim/requestPreparation skip). Its compression test now pins the uncompressed behavior. - New regression tests for both compression decision paths: an implicit-prefix-caching host skips compression on chat-completions and Responses requests, while a non-caching custom endpoint still compresses. - New byte-stability test: the same turn rendered twice with an advanced clock and a grown in-progress tool-call list produces an identical system prompt. - gitSettings: cover the CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=0 defined-falsy override outside a repository. - Focused system-prompt test asserting the new timing/wiring guidance without snapshotting the full prompt. bun run check (smoke, deadcode, full suite) passes; tsc --noEmit clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: isolate CLAUDE_CODE_SIMPLE in the doing-tasks prompt test getSystemPrompt short-circuits to a minimal prompt when CLAUDE_CODE_SIMPLE is truthy; save, unset, and restore it around the test so the full prompt path is always exercised regardless of process-level state. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
ef1a462faf |
chore(main): release 0.29.0 (#2116)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>v0.29.0 |
||
|
|
c461a0363d |
feat: merge knowledge graph + conversation arc into memdir (#1811)
* feat: merge knowledge graph + conversation arc into memdir
Replace the standalone KG/ARC system (SQLite + JSON + Orama storage)
with direct integration into the existing auto-memory directory.
What changed:
- New memdir/vectorIndex.ts — Orama full-text index over all memory/ .md
files, replacing the separate knowledge.orama binary
- New memdir/autoExtractFacts.ts — auto-detects env vars, paths,
versions, URLs, IPs, backtick concepts from conversation and writes
them as structured .md files into memory/.facts/ with frontmatter
- conversationArc.ts now persists arc state (goals, decisions,
milestones, phase) to memory/.arc.json sidecar instead of the KG
- knowledgeGraph.ts gutted from 728→165 lines — now a thin
compatibility layer that reads .facts/ files from memdir and
delegates vector search to vectorIndex.ts
- build.ts: enabled CONVERSATION_ARC and MULTI_TURN_CONTEXT feature
flags (previously undefined → dead-code eliminated in production)
Removed:
- src/utils/storage/ (SQLiteProvider, JSONProvider, 3 test files) —
unused after KG migration
- src/utils/knowledgeGraph.test.ts, .stress.test.ts
- src/utils/conversationArc.test.ts, .perf.test.ts
- ~1700 lines of redundant storage code
Benefits:
- Single memory system (memdir) instead of two parallel systems
- Auto-extracted facts are plain .md files — visible to the model,
discoverable by the existing Sonnet prefetch
- Vector search indexes real memory content, not a separate DB
- Arc state survives across sessions via .arc.json
- ~700 lines removed from the production bundle
* fix: type errors, add test suites, fix resetArc() disk-write bug
- Fix vectorIndex.ts: parseFrontmatter returns nested {frontmatter, content},
Orama DB typed as 'any' matching existing code pattern
- Fix resetArc(): was overwriting .arc.json on disk — now clears only in-memory state
- Add vectorIndex.test.ts (6 tests): build/search/persist/rebuild
- Add autoExtractFacts.test.ts (10 tests): env vars, paths, versions,
URLs, backtick concepts, PascalCase, React/Redux, file signatures, frontmatter
- Add conversationArc.test.ts (14 tests): arc init, persistence, goals,
decisions, milestones, phase detection, arc summary, finalize, stats
- Update verify-kg-merge.sh: add test suite check (33 tests)
* fix: remove generic type param from restore() call
* fix: address CodeRabbit findings — YAML injection, secrets leak, cache invalidation, frontmatter parsing, test weakness
* fix: redact URL credentials/query/hash in endpoint extraction; add persistence + reindex regression test
* test: add regression for URL credential/query/hash redaction in fact extraction
* feat: wire getOrchestratedMemory into query.ts prompt; remove dead promises array in autoExtractFacts
* feat: enhance memory management by adding clearArcArtifacts function and integrating it into the clear command; implement file count tracking in vector index
* feat: enhance fact extraction by adding tests for absolute paths, backtick concepts, technical terms, project file signatures, and IP addresses; implement clearArcArtifacts function in tests
* Review-fix: scoped IP tagging, scrubbedContent, arcMemoryDir null, vector-index cleanup
* Review-fix: isAutoMemoryEnabled gate, scrubbed paths, clearIndex in cleanup
* Review-fix: URL-stripped path scan, digit-key/quoted-value env redaction, rm isAutoMemory gate
* Review-fix: quoted multi-token env values fully redacted, regression test
* Review-fix: freshness check on each search, integration test, typecheck in verifier
* Review-fix: missing-index-file reinit, full-pipeline integration test
* Review-fix: gate arc/RAG on isAutoMemoryEnabled, add integration+stale-index tests
Addresses three P1/P2 findings from code review:
1. P1: Honor auto-memory opt-out before writing arc facts
- Add isAutoMemoryEnabled() checks in query.ts before calling
updateArcPhase() and getOrchestratedMemory()
- Add same check inside conversationArc.ts extractFactsAutomatically()
- Prevents .facts file writes when auto-memory disabled via --bare,
CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, or memory.autoWrite: false
2. P2: Add query-level integration test coverage
- New test in conversationArc.test.ts verifies query.ts path
- Confirms arc functions called behind feature gates and results
appended to system prompt (lines 555-575)
3. P2: Add stale-index regression tests
- 6 new tests in vectorIndex.test.ts cover:
* Searching after adding files
* Searching after editing files
* Searching after removing files
* Searching when .vector-index missing
* Searching when .vector-index-meta.json missing
* Mixed stale conditions
All tests pass (31 total, 99 assertions), typecheck clean.
* Review-fix: use >= for mtime staleness check to catch same-ms edits
The verification agent discovered a timing-dependent bug in the stale
index detection. When a file edit and index save occur within the same
millisecond, latestMtime equals indexMtime, causing the check
`latestMtime > indexMtime` to return false. The stale index is not
refreshed and searches miss the updated content.
Changed line 220 from `>` to `>=` in the mtime comparison. The file
count check catches add/remove operations, but edits that don't change
the file count rely on mtime comparison.
All 12 vector index tests now pass consistently, including the
"searching after editing a file picks up changes" test that previously
failed intermittently.
* Review-fix: move auto-memory gate to persistence layer
Addresses inline review comment: query.ts was incorrectly skipping
updateArcPhase() entirely when isAutoMemoryEnabled() returned false,
leaving the in-memory arc state stale.
Fixed by:
- Removed isAutoMemoryEnabled() gate from query.ts line 449
- Added gate inside conversationArc.ts updateArcPhase() at persistence
layer (line 223), so phase advances but only persistence is disabled
- Arc state tracking now works regardless of auto-memory setting
- Only disk writes (.arc.json, .facts files, index rebuilds) are gated
The 2ms delay in vectorIndex.test.ts is kept as a pragmatic fix for the
timing race. Content-hash detection would be ideal but adds complexity;
the mtime check works reliably in production.
All 31 tests pass, typecheck clean.
* Refactor memory handling: consolidate metadata retrieval and improve auto-memory checks
* Fix: update expectation to use toEqual for prompt comparison in conversationArc tests
* fix: detect same-size content changes via content hash; handle text-block user messages in arc query
* fix: skip symlinked dirs in vector index walk; enable arc/multi-turn flags; add production-path tests
* fix: follow symlinked dirs in vector index walk per review
* fix: skip symlinked dirs in vector index walk; add symlink-boundary regression tests
* fix: skip indexing symlinked directories and ensure only files are processed
* fix: show cmd output on failure in verifier; add multi-turn coverage; clear mempath cache; cover arc reset in knowledge clear test
* fix: clear memoized auto-mem path after teardown in knowledge + conversationArc tests
* fix: isolate vector index per memdir, filter secrets from backtick facts, clean trailing ws
* fix: extend credential filter for AWS/GitLab tokens; reject all symlinks in vector index
* fix: use repo's redactSecretSubstringsForDisplay; add npm/glpat/AKIA/ASIA/xox to shared patterns; cover NPM+JWT in tests
* fix: P1 backtick credential safety + untrusted-data boundary; P2 legacy migration + non-fatal writes; P3 type safety + build regression
* fix: B1-B5, M6, M8 — no message mutation, migration data loss, empty-file, non-fatal writes, probe, rebuildIndex resilience, dead import
* fix: address 8 reviewer findings (R1-R8)
P1:
- Keep retrieved facts in DATA ONLY block with strict system instruction
- Catch lowercase config secrets (api_key=...) in env scrubber
- Migrate SQLite working store (knowledge.db) before deleting provider
- /knowledge clear atomically archives legacy sources
P2:
- Run legacy migration on getOrchestratedMemory retrieval path
- Preserve entity attributes in migration frontmatter
- Only rebuild vector index when facts actually changed
- Fix feature-flag verifier --define syntax (declare const)
* fix: close 9 memory findings — approval gate, non-fatal writes, secret scrub, per-project migration, attribute/relation preservation, WAL cleanup, cheaper index
- Gate auto fact extraction on isMemoryWriteApprovalRequired() + isAutoMemoryEnabled() so default projects cannot silently persist conversation content
- Make ensureFactsDir/writeFactMemory degrade non-fatally (no turn-breaking throw on read-only dirs)
- Scrub token-like URL/path/hyphenated segments from durable facts via looksLikeSecret (reuses providerSecrets.looksLikeSecretValue)
- Restore passive project-rule extraction as rule facts
- Honor isAutoMemoryEnabled() before legacy migration; scope the migration guard per project (Set) instead of a single global
- Preserve legacy entity attributes and relations through migration (indented attributes + relation fact file, reconstructed in getGlobalGraph)
- Clear SQLite WAL/SHM sidecars on /knowledge clear
- Replace per-turn content hashing in vectorIndex getMdStats with size+mtime metadata; drop redundant initMemdirIndex call in getOrchestratedMemory
- Add knowledgeGraph tests covering P1#2/P1#4/P2#5/P2#8 and extend autoExtractFacts tests
* test: avoid global cwd pollution in knowledgeGraph tests
Replace process.chdir with a per-test setFsImplementation mock cwd that is
reset via setOriginalFsImplementation in afterEach, so the test no longer
leaks a changed process.cwd() into other test files. Assert the auto-memory
gate via the project-specific legacy file rather than the shared resolved
memdir dir (which bun runs concurrently across it blocks).
* fix: address 15 reviewer findings (R1-R15)
P1:
- Gate saveArcToDisk/finalizeArcTurn/saveIndex/migration on memory-write approval
- Retire legacy sources after successful migration (rmSync, backup preserved)
- Slugify entity.type and summary.id in migration filenames (path traversal)
- Fall back to JSON when SQLite has zero entities
- Scrub rule-fact extraction on scrubbedContent + looksLikeSecret/redact check
P2:
- Track skipped vs completed migration; re-enable clears skip marker
- Walk back to latest human text for tool-round vector queries
- Auto-extract goals/decisions from user messages in updateArcPhase
- /knowledge clear message says durable wipe, not session-only
- Bind arc state to projectKey (re-resolve on cwd change)
- clearIndex(memoryDir?) scopes to one memdir
- yamlQuote all migration frontmatter fields
- Real SHA-256 contentHash alongside fileFingerprint for same-size edits
- Stop claiming production-pipeline coverage in tests/verifier
* test: isolate governance mock by removing afterEach clear
Remove setGovernancePolicySettingsForSourceForTesting(null) from afterEach
in autoExtractFacts, conversationArc, and knowledgeGraph test files. The
module-level mock is set in each file's beforeEach and since there is no
afterEach cleardown, parallel test execution can no longer corrupt the
mock state across files.
This fixes 26 CI test failures caused by one file's afterEach clearing
the mock that another concurrently-running file had set in its beforeEach.
* fix: isolate governance mock per async context via executionAsyncId tracking
Replace the module-level variable in governancePolicy.ts with an
executionAsyncId-keyed Map and an async_hooks.createHook that propagates
the override from parent to child async resources. This ensures each
concurrent test's beforeEach/afterEach cannot corrupt the override set
by another test file, even when test bodies directly mutate the mock.
Also restore setGovernancePolicySettingsForSourceForTesting(null) calls
in afterEach hooks (removed in 39c68376), which are now safe because
each afterEach only clears its own async context.
Fixes 26 CI test failures across knowledgeGraph (2), conversationArc (7),
and autoExtractFacts (17/22, governance-gate tests).
* Refactor knowledge graph legacy migration, secure secrets and IP octets, optimize build-time feature flags, cap conversation arc collections, and resolve all verification check gaps
* Fix governancePolicy enablement in full test runs by checking for test runner globals
* fix: ensure auto memory is enabled in conversationArc, knowledgeGraph, autoExtractFacts tests
Delete CLAUDE_CODE_DISABLE_AUTO_MEMORY and CLAUDE_CODE_SIMPLE env vars
in beforeEach hooks so tests are not blocked when CI sets these vars.
Also revert governancePolicy.ts to the simple module-level variable
(removing the async ID tracking approach that broke with Bun v1.3.13).
Fixes 33 CI test failures where isAutoMemoryEnabled() returned false
causing all disk-persistence guards to fire.
* fix: address P1/P2 review findings — redaction, bounds, legacy backup
[P1] Redact goal/decision descriptions with redactLikelySecrets before
persisting to .arc.json, session summaries, and prompt summaries so
credentials captured by auto-extraction regexes are not durably stored.
[P1] Bound multi-turn tool input serialization to 2000 chars and apply
redactLikelySecrets, preventing oversized/credential-bearing tool inputs
from overflowing the next provider request or exposing secrets.
[P2] Archive the non-selected legacy store (JSON or SQLite) and its WAL
sidecars before retiring both sources, ensuring a recoverable snapshot
exists if generated fact files are incomplete or a migration bug surfaces.
* fix: address P1 findings — safe legacy retirement, multi-turn aggregate budget
[P1] Do not retire a legacy store unless every existing source was
successfully archived. Track archived sources in a Set and skip deletion
of any source whose backup failed (knowledgeGraph.ts).
[P1] Archive the selected SQLite WAL/SHM sidecars alongside its migration
backup, since committed state may reside only in the WAL file and the
advertised recovery backup would otherwise be incomplete (knowledgeGraph.ts).
[P1] Bound the aggregate multi-turn tool replay to 10KB total and stop
appending further turns once the budget is exceeded, preventing many
Agent/MCP calls per turn from adding unbounded text to system prompts
(conversationArc.ts).
* fix: address P1/P2 review findings — rule extraction gate, SQLite read status, atomic WAL/SHAM, KG status gate, byte budgets
* fix: tighten looksLikeOpaqueToken to avoid flagging compound model names
* fix: address P1/P2 review findings — rebase, test isolation, SQLite retry, attribute redaction, entity aliases, body content, project-scoped multiturn, skip unchanged writes, knowledge list gate
* fix: address P1/P2/P3 review findings — secret scrub on migrate, lean decision gate, git-root legacy lookup, backup retention, index rebuild chaining, single vector search, drop unreferenced fixture
* fix: scrub secret entity names on migrate, exclude summary facts from entities, reset multi-turn on /knowledge clear
* fix: address P1 review findings for legacy graph redaction, recovery-safe clear, stable change guards
- Redact embedded secrets in migrated legacy knowledge-graph entities,
summaries, and rules via shared sanitizeLegacyText() policy
- Preserve legacy artifacts (json/db/wal/shm) as migration-backup before
/knowledge clear; resetGlobalGraph returns { archived, failures }
- Skip rewrite + index rebuild on unchanged turns by stripping the volatile
detectedAt timestamp (facts and arc session summaries)
- Always recompute the authoritative content hash in getMdStats so edits of
equal size with preserved mtime are detected and served correctly
* Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* fix: redact protocol-relative URL userinfo in legacy migration
new URL() throws for scheme-less URLs, so the catch branch now redacts
obvious //user:pass@host userinfo instead of persisting credentials.
* fix(memory): harden memdir migration and retrieval
---------
Co-authored-by: Gravirei <gravirei@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Kevin Codex <kevin@gitlawb.com>
|
||
|
|
6e3590303b |
feat(partners): add Concentrate and Exa to partner roster (#2141)
Adds Concentrate (concentrate.ai) and Exa (exa.ai) to the README partners table and the web landing page, with light/dark logo variants self-hosted under docs/assets/ and web/public/partners/. Co-authored-by: OpenClaude <openclaude@gitlawb.com> |
||
|
|
645d596ea4 |
fix(code-reviewer): require inline diff input and preserve read-only search in embedded-search builds (#2102)
* feat: add code reviewer agent * feat(agent): add code-reviewer built-in agent implementation and tests Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(code-reviewer): address review comments - Fix broken step numbering in system prompt (glob/grep as sub-bullets) - Remove unnecessary wrapper in getSystemPrompt - Drop unused beforeEach/afterEach lifecycle in tests - Remove redundant registration test (beforeAll already throws) - Fix CLAUDE_CONFIG_DIR leak in beforeAll (restore in finally) - Replace @ts-ignore with explicit ToolUseContext cast - Use placeholder in README agentRouting example Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * ci: trigger rerun — pre-existing test failures on main * fix(code-reviewer): enforce read-only contract by disallowing Bash Add Bash to disallowedTools so the reviewer cannot run shell commands regardless of parent session's acceptEdits/bypassPermissions mode. resolveAgentTools() treated undefined tools as wildcard — Bash was available and could auto-approve mkdir/rm/mv in acceptEdits mode. Remove Bash guidance from system prompt; diff must now be supplied by the caller inline. Update test to assert Bash is in disallowedTools. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(code-reviewer): deny all shell tools (Bash and PowerShell) Use SHELL_TOOL_NAMES constant instead of just BASH_TOOL_NAME to ensure all shell-capable tools are denied from the code-reviewer agent. This prevents Windows sessions with PowerShell enabled from bypassing the read-only contract. - Import SHELL_TOOL_NAMES from shellToolUtils - Use spread operator to include both Bash and PowerShell in disallowedTools - Update test to verify PowerShell is denied Fixes the finding: [P2] Deny all shell tools for the reviewer agent * fix(code-reviewer): explicit read-only allow-list; drop unrelated artifacts Switch code-reviewer to an explicit `tools` allow-list (Read, Glob, Grep) instead of relying on wildcard access minus a deny-list. resolveAgentTools() resolves only the named tools, so write-capable mcp__* server tools (and any other mutation-capable tool) can never be handed to the read-only reviewer. Keep the mutation deny-list as defense-in-depth. Remove generated/scratch artifacts unrelated to the reviewer agent: AGENTS.md, ARCHITECTURE.md, the .openlore/ .gitignore rule, temp_reference/, and the .tmp/sdk-consumer-* scratch files. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix: restore temp_reference/ gitignore entry from main Entry was present on main from #1350 and was unintentionally removed during PR cleanup. Restoring it so temp_reference/ scratch directories remain untracked after merge. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(code-reviewer): require inline diff input and preserve read-only search in embedded-search builds Summary: - Update the `code-reviewer` built-in agent to require the caller to provide the diff or changed hunks inline in the prompt. - Preserve read-only search behavior in embedded-search builds by omitting `Glob`/`Grep` from the explicit tool allow-list when embedded search tools are enabled. - Keep a strict read-only policy by disallowing shell and mutation tools. Usage: - The `code-reviewer` agent is now explicitly guided to only review changes when the diff is provided inline. - In embedded-search builds, the agent only receives `Read` and cannot access `Glob`/`Grep`. - This prevents the agent from attempting shell-based diff discovery and enforces caller-provided diff input. Test plan: - `bun test src/tools/AgentTool/built-in/codeReviewerAgent.test.ts` — 12 pass, 0 fail - `bun run build` — success - `bun run smoke` — success - `bun run security:pr-scan` — success - `git diff --check` — success Credit: prior work from #1381/#1420. * fix(code-reviewer): clear cached agent definitions and markdown loader cache after test cleanup * fix(code-reviewer): address all P2/P3 review findings from jatmn - Always list [Read, Glob, Grep] in the tool allow-list; in embedded-search builds resolveAgentTools() silently drops unavailable Glob/Grep at runtime. The system prompt explicitly documents the narrowed search contract for embedded builds instead of silently degrading. - Update the code-reviewer invocation example in prompt.ts to include the diff inline, satisfying the reviewer's contract and preventing an avoidable extra turn. - Rewrite the test suite with the same isolation protocol as loadAgentsDir.test.ts: shared mutation lock, OPENCLAUDE_CONFIG_DIR, setClaudeConfigHomeDirForTesting, setAllowedSettingSources, and full env/cache restore in finally blocks. - Exercise both embedded-search branches: non-embedded tests verify Glob/Grep guidance, embedded tests verify the limited-search documentation and Read-only path. - Fix settings file path in README.md and docs/agent-routing.md from ~/.openclaude.json to ~/.openclaude/settings.json (the path the runtime actually loads). - Add blank line after fenced code block (MD031), add code-reviewer to the routable built-in agent list in both README and agent-routing docs. * fix(code-reviewer): restore prior setting sources in test cleanup, add credential security warning - Capture getAllowedSettingSources() before overwriting and restore it in the finally block instead of resetting to the default list, preventing state leakage to concurrent suites. - Add plaintext-credential security warning before the agentModels JSON example in README. - Update 'All settings-driven' to 'Configured via settings, agent frontmatter, and environment variables' for accuracy. * fix(code-reviewer): address remaining PR feedback (P1/P3) * docs: document feature gate for Explore and Plan agents * docs: document inline-diff requirement for code-reviewer agent * fix(code-reviewer): address P1/P2 review findings — teammate boundary, resume safety, lock-aware tests [P1] Reject built-in agent types from teammate spawn path to preserve read-only boundary. The teammate branch bypasses resolveAgentTools(), so built-ins like code-reviewer would receive Bash/Edit/Write tools. Guard added in AgentTool.tsx before spawnTeammate is called. [P1] Fail closed when resuming an unavailable agent type instead of silently falling back to GENERAL_PURPOSE_AGENT. A resumed code-reviewer must never gain edit-capable tools through a compatibility fallback. [P2] Snapshot environment and config state only after acquiring the shared mutation lock in codeReviewerAgent.test.ts. Moved from module- scope const to post-lock capture in beforeAll, with cleanup and lock release in afterAll's finally block. Regression tests added for all three findings. * fix(code-reviewer): guard lock release against failed acquisition Only call releaseSharedMutationLock() in afterAll when the lock was successfully acquired. Prevents releasing another suite's lock if acquireSharedMutationLock() throws on timeout. * fix(code-reviewer): remove trailing whitespace * fix(code-reviewer): reliably block built-in teammate spawns Reject built-in agent types from the teammate spawn path by looking them up in allAgents rather than activeAgents. This ensures the restriction remains intact even when built-in agents are disabled (e.g. via CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS) and omitted from activeAgents. Regression test added. * fix(code-reviewer): preserve original agent identity when resuming a read-only reviewer Background-agent metadata persisted only agentType, so resuming selected whichever active definition currently had that name. A built-in code-reviewer could be started, followed by a project/SDK definition named code-reviewer taking precedence; resuming the original agent would then use the replacement's ordinary wildcard tool set and grant that reviewer transcript Bash/Edit/Write tools. Persist the agent definition source and verify it matches the resolved definition on resume, rejecting the resumption if the original was spoofed. * fix(code-reviewer): address remaining CodeRabbit feedback on test cleanup and metadata source * fix(code-reviewer): address P1/P2 issues for teammate spawns and resume safety * docs: make OpenLore prerequisite explicitly optional in AGENTS.md * docs: fix pinned OpenLore version in AGENTS.md * Fix review issues * Revert AGENTS.md changes * Restore AGENTS.md to match upstream/main * fix(agent): address maintainer feedback on teammate spawns and resume persistence * test(agent): add regression coverage for legacy source-less agent resume * fix(agent): propagation pass — batch fork regression, TeamCreate policy, trailing whitespace, verification gate docs * fix(batch): allow specific custom agent types while requiring subagent_type --------- Co-authored-by: Laurent FRANCOISE <lfrancoise@gmail.com> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> |
||
|
|
787f2a9390 |
refactor(cli): commander-authoritative argv handling for SSH / cc:// and remote bypass (recovery of #1939) (#2098)
* fix(cli): mirror programmatic args onto process.argv (hardened) Address CodeRabbit's Critical finding: cliMain() parses process.argv directly, so a programmatic main(args) call must reflect args there or it silently runs the host's argv. Restores the args->argv sync but hardened against the three bugs the multi-agent review confirmed in the earlier scoped/serialized version: - no restore (was F3: a finally-restore flipped argv out from under the SIGINT handler and bypass-safety notice while the session was live) - length-guarded exec/script slots (was F4: <2 host argv entries, e.g. node -e, dropped the flag past commander's argv.slice(2)) - no serialization chain (was F2: overlapping calls hung indefinitely) For the normal binary launch (args defaulted from process.argv.slice(2)) the assignment is a value-identical no-op. Tests: programmatic args reach cliMain, argv is not restored, and the exec/script slots are padded under a short host argv. Verified: 48 entrypoint+safety tests, tsc, build, and e2e re-probes of all former --yolo bug scenarios on the built binary. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(cli): ssh strip-all dangerous-skip tokens; docs+tests for native alias Address the latest Copilot + CodeRabbit findings on the native-alias PR: - ssh argv pre-scan removed only the first dangerous-skip token, so `ssh --yolo --dangerously-skip-permissions host` (or a repeat) left a survivor that re-enabled bypass after the ssh rewrite. Strip every matching token. (connect already used the filter helper.) [Copilot] - web/src/data/cliFlags.ts: list the flag as '--yolo, --dangerously-skip-permissions' to match the commander registration, not just the description. [Copilot] - Replace the source-string-count registration test with (a) a behavioral test that the built CLI lists the alias in --help — proving the main-command registration is live, not dead code or the wrong command — and (b) a structured .option() assertion plus a check that the ssh pre-scan handles the alias (ssh --help renders root help, so the ssh --yolo path is the pre-scan, not the commander option). [CodeRabbit] - PR description rewritten to describe the native alias instead of the removed argv rewrite. [Copilot] Verified: 23 cli + 10 safety tests, tsc, build, e2e (--yolo --help lists the alias; ssh --help; mcp add --yolo names the typed flag). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(cli): runtime coverage for dangerous-skip strip; share one helper CodeRabbit (approved, follow-up): the strip-all fix was only source- checked, so the strip loop could regress unnoticed. Extract the argv scanners into src/utils/dangerousSkipFlags.ts (isDangerousSkipFlag / hasDangerousSkipFlag / stripDangerousSkipFlags) and unit-test them at runtime: both spellings detected, every token stripped (canonical + --yolo + repeats), input not mutated. Both the direct-connect and ssh rewrites in main.tsx now use the shared stripDangerousSkipFlags — the ssh path's bespoke single-splice while loop (the original survivor bug) is gone, replaced by an in-place splice(0, len, ...strip). One tested code path instead of two. Verified: helper + 23 cli + 10 safety tests, tsc, build, e2e. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * style(cli): semicolon + strip both spellings in safety-test reset Copilot review nits: - statusNoticeDefinitions.tsx: add the trailing semicolon to the parenthesized return to match the file's semicolon style. - safety.test.tsx: the beforeEach argv reset filtered only --dangerously-skip-permissions; strip --yolo too so the 'without the flag' cases can't go order-dependent if the runner is invoked with --yolo in argv. - PR description re-synced to the native-alias approach (the earlier edit had reverted to the old 'normalize via argv rewrite' wording). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(cli): notice names --yolo; move import out of boot-critical block Both bots on 50772d28: - The bypass-safety notice fires for --yolo but its text named only '--dangerously-skip-permissions is active'. Reword to '... (alias --yolo) is active' so the message matches what the user typed. Add a rendered-notice regression assertion for the --yolo case. [CodeRabbit + Copilot] - Move the dangerousSkipFlags import out of the boot-critical header block (it ran before profileCheckpoint('main_tsx_entry'), adding pre-checkpoint work in the order-preserving bundle) down to the regular internal-import group. [Copilot] Verified: 39 cli+safety+helper tests, tsc, build, e2e. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(cli): honor -- end-of-options in the raw-argv dangerous-skip scanners Copilot (3x on 5cd0e304): the pre-commander scanners matched --yolo / --dangerously-skip-permissions anywhere in argv, so a positional after the -- marker (openclaude -p -- --yolo, cc://… -- --yolo, ssh host -- --yolo) was misread as the bypass flag — enabling bypass / stripping the token / false-firing the safety notice, even though commander treats it as positional. Pre-existing for the canonical flag, but the short alias makes it far likelier. Make the shared helpers --aware in one place: hasDangerousSkipFlag and stripDangerousSkipFlags only consider option-position tokens (before the first --) and preserve everything from -- onward. Route the safety notice's hasDangerouslySkipPermissionsArg through the same helper. Regression tests: helper ignores/preserves post-- tokens; the notice does not fire for -p -- --yolo. Verified: 41 helper+safety+cli tests, tsc, build, e2e. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(cli): don't leak args via process.argv; stop simulating commander in the scanner Address jatmn's two P1 findings, both by removing a band-aid rather than adding another: - P1a: main() no longer mirrors its args onto the process-global process.argv. Verified there is no production or SDK caller that passes custom args (the sole entry is the no-arg auto-run), so the mirror only risked leaking a programmatic invocation's args (including a bypass flag) into an overlapping call or the host process. Back to the baseline signature; cliMain parses the real process.argv. - P1b: revert the end-of-options ("--") handling in the dangerous-skip scanner. As jatmn notes, correctly classifying "--yolo" (it can be a required option value like "--system-prompt --yolo", or follow a "--" consumed as a variadic value) requires commander's option-arity state machine, the exact simulation this feature was reworked to delete. The scanner now mirrors the canonical --dangerously-skip-permissions presence check exactly: both spellings behave identically, and the approximation is documented as a pre-existing limitation of pre-commander scanning. Net: every difference between --yolo and the canonical flag is now either native-commander-correct (the registration) or an identical approximation (the raw scanners). No new argv mutation, no parser simulation. Verified: 38 cli+helper+safety tests, tsc, build, e2e. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(cli): clarify main() argv comment — skills/--update do rewrite argv Copilot: the "does not mirror args onto process.argv" comment was misleading — the skills and --update fast-paths reassign process.argv to re-route to their subcommand. Note the exception; the no-mirror rule is about not injecting the caller's args into the general cliMain flow. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(setup): name the --yolo alias in the root/sudo bypass error Copilot: the root/sudo safety error printed only --dangerously-skip-permissions; a user who typed --yolo saw a flag they didn't use. Mention both spellings, matching the ssh help and cliFlags. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(cli): import Command from @commander-js/extra-typings, matching prod Copilot: the alias behavioral test built its probe Command from 'commander', but production registers options via @commander-js/extra-typings. Use the same package so the test exercises the exact parser prod uses. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ssh): don't treat an option value as the permission-bypass alias jatmn P1: `ssh host --permission-mode --yolo` stripped --yolo as a bypass flag (enabling bypass) and left --permission-mode valueless, whereas commander parses --yolo as the (invalid) mode value and rejects it — a silent privilege escalation. Same class affected --model / --resume / --fallback-model. Reorder the ssh pre-parser so value-taking flags consume their value — including a dangerous-skip token in the value slot — BEFORE the dangerous-skip strip runs. Extract the whole flag pre-parse into a pure, unit-tested helper (parseSshFlags) so the security-sensitive arity handling has regression coverage: escalation guards for --permission-mode/--model + a value of --yolo, plus genuine standalone --yolo still enabling bypass. Verified: 6 ssh + dangerousSkipFlags + cli tests, tsc, build, e2e. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(cli): update ssh-path source assertion for parseSshFlags extraction Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(cli): revert unrelated --bare doc; drop stray blank line CodeRabbit/Copilot on the rebased branch: - Revert the --bare help rewrite (background prefetches / CLAUDE_CODE_SIMPLE / expanded flag list) in main.tsx and web/src/data/cliFlags.ts — it is unrelated to the --yolo alias and broadens scope. cliFlags.ts now changes only the --yolo alias line. - Remove the stray double blank line before cliMain. Skipped CodeRabbit's "alias order breaks property naming" (Major): verified against @commander-js/extra-typings that '--yolo, --dangerously-skip- permissions' maps BOTH spellings to opts().dangerouslySkipPermissions (commander keys off the last long flag); opts().yolo is undefined. Bypass is not broken. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ssh): honor the -- end-of-options marker in the ssh pre-parser CodeRabbit Critical + jatmn P1 ("respect option arity/end-of-options semantics"): `ssh host -- --yolo` (or `-- --local`, `-- --permission-mode x`) parsed the post-`--` tokens as flags, so a positional --yolo escalated to bypass. parseSshFlags now parses only the prefix before `--` and keeps everything from `--` on positional. This is unambiguous here because the ssh subcommand registers no variadic options that could consume `--` as a value. The connect (cc://) path is deliberately left plain and documented: it rewrites to the main command, which HAS variadic options (--add-dir …) that commander lets consume `--` as a value, so a naive `--` split there would be the incomplete simulation flagged in P1b. That false-positive is pre-existing for the canonical flag. Skipped (both pre-existing, ported verbatim / out of scope): extractFlag mixed `--flag=x --flag y` precedence, and the setup.ts root/sudo message not naming --allow-dangerously-skip-permissions. Verified: 8 ssh + cli tests, tsc, build. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor: make --yolo/bypass Commander-authoritative on cc:// connect + notice * fixup! address CodeRabbit/Copilot review findings on #2098 - Restore parseMaxTurnsCommanderArgument for --max-turns validation. - Generalize root/sudo error message for all bypass modes/flags. - Clarify cli.tsx comment about main() not leaking args into process.argv. - Detect -p/--print in all commander-accepted forms (including --print= and -p<value>). - Correct dangerousSkipFlags.ts doc: SSH strips, cc:// preserves for Commander. - Extend live help test to ssh and open subcommands. * fixup! extract hasPrintFlag helper + regression tests - Move print-flag detection to src/utils/printFlag.ts so it is unit-testable. - Add regression tests for -p, --print, --print=prompt, -pprompt, and -- separator. - Import the helper in main.tsx and drop the local copy. * fixup! use hasPrintFlag in every startup print-mode check - Replace exact-string includes in the SSH headless rejection and the main print-mode gate with the shared hasPrintFlag predicate. - Add source assertions confirming cc:// rewrite, SSH rejection, and main print-mode gate all use the same helper. * fixup! align dangerously-skip notice comment with commander-authoritative mode - Remove stale 'reads from process.argv' text; the notice now keys off the resolved permissionMode. * fixup! add SIGINT handler to hasPrintFlag source assertions - Include the SIGINT print-mode gate in the source-level consistency check. * fixup! restore maxTurns forwarding dropped during rebase - Re-add options.maxTurns to sessionConfig and the interactive REPL props for direct-connect, SSH, remote viewer, and remote creation paths (matches main). * fixup! address Copilot suppressed comments on #2098 - parseSshFlags now consumes required-arg values unconditionally, matching commander and preventing flag-like values from leaking into later guards. - Drop the now-unused isDangerousSkipFlag import from sshPreParse.ts. - Make the dangerously-skip notice text mode-agnostic so settings-driven bypassPermissions is not mislabeled as a CLI flag. * fixup: left-to-right SSH parse and fullAccess sandbox warning - Rewrite parseSshFlags as a single left-to-right arity-aware scan. Value-taking flags now consume every occurrence (including equals forms) and always consume the next token as their value, even if it resembles a flag (e.g. --permission-mode --local or --model --yolo value). - Cover fullAccess with the dangerously-skip-permissions sandbox warning and add focused regression tests for bypassPermissions/fullAccess rendering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fixup: preserve missing SSH option values and embedded equals - Keep value-taking SSH flags in remaining when they have no available value (last token before -- or trailing), letting commander report the missing required argument. - Use slice after the prefix for equals-form values so embedded '=' characters are preserved (e.g. --model=provider=model). - Add regression tests for last-token, before--, and embedded-equals cases. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fixup: arity-aware print detection and optional --resume for SSH - hasPrintFlag now skips tokens consumed as values by preceding value-taking options (required, optional, and variadic), so --system-prompt --print=custom is no longer misclassified as print mode. - parseSshFlags treats --resume as an optional-value option: a bare --resume is forwarded, a non-option value is consumed, and following flags (e.g. --yolo) remain available for their own parsing. - Added focused regression tests for both fixes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fixup: handle inline values and -- in hasPrintFlag - Do not advance past a following flag when a required/optional/variadic option already provided its value inline via =. - Stop the scan when a value-taking option is immediately followed by --. - Added regression tests for --model=foo --print and --model -- --print. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fixup! address jatmn review: arity-aware print/SSH parsing + fullAccess notice Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fixup! correct bypassPermissions notice wording Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Address remaining CodeRabbit findings on #2098 - Sync hasPrintFlag with all root-command required/variadic/optional options, including hidden/feature-gated flags (--agent-id, --sdk-url, --channels, etc.). - Treat the SDK 'full-access' spelling as fullAccess in the dangerous-skip-permissions status notice so the stronger warning is shown. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(cli): make hasPrintFlag the single pre-Commander print classifier - Replace all startup .includes('-p')/.includes('--print') checks with the arity-aware hasPrintFlag() predicate so value-consumed tokens are not misclassified as print mode. - Centralize SSH headless detection in sshArgvImpliesHeadless(), covering both tail argv after host/cwd and flags forwarded via extraCliArgs (e.g. --resume=--print). - Soften the fullAccess status-notice wording to match runtime behavior: most consent checks are bypassed, but hard deny rules and user-interaction prompts still apply. - Add/extend tests for interactivity, SSH flag pre-parsing, status notices, and a regression check that prevents naive print-token checks from re-entering. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(ssh): preserve --resume= values and run headless guard before host extraction - Keep the inline value attached when forwarding --resume=... extraCliArgs so optional-value semantics are preserved (e.g. --resume=--print resumes a conversation named "--print", it does not enable print mode). - Move the SSH headless guard before host/cwd extraction in main.tsx so print flags that appear before the host are rejected. - Update tests: --resume=--print is no longer headless, required-value options like --model -p remain non-headless, and add coverage for print flags before the host. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(cli): remove repeatable single-value options from VARIADIC_OPTIONS --plugin-dir and --provider-env-file are registered as repeatable single-value options, not variadic. Keeping them in VARIADIC_OPTIONS made the arity model wrong and could consume extra tokens if check order changed. They are already covered by REQUIRED_VALUE_OPTIONS. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
294bd9a1df |
Add optional Sentry error reporting (env-driven, opt-in) (#2139)
* Add optional Sentry error reporting (env-driven, opt-in) * Fix Sentry init to use dynamic import instead of require (ESM compatibility) * Document SENTRY_DSN setup in advanced-setup docs * Disable Sentry default integrations; document runtime install requirement * Wire reportErrorToSentry into top-level error handlers; add sentry.test.ts |