From 48f7848a00628192d282efefa698f5190fb7ed5a Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 00:05:32 +0200 Subject: [PATCH 01/20] feat(flags): add the Code Mode flag Keep Code Mode off by default. Adopt an unclaimed on value and preserve other values unless the write explicitly turns the flag on. Refs #792 (feat/code-mode-direct) --- src/core/flags.ts | 159 ++++++++++++------ .../golden/install-snapshot-all-off.txt | 1 + .../golden/install-snapshot-github.txt | 1 + .../golden/install-snapshot-jira-hipaa.txt | 1 + tests/flags.test.ts | 112 +++++++++++- 5 files changed, 224 insertions(+), 50 deletions(-) diff --git a/src/core/flags.ts b/src/core/flags.ts index 5492b339f..363528d86 100644 --- a/src/core/flags.ts +++ b/src/core/flags.ts @@ -6,7 +6,7 @@ * * D14: Typed registry — flags carry kind (boolean|enum|number|string), target * (env|setting), and per-kind defaultValue. Neutral values delete their target - * key; active values write the appropriate payload. Number 0 is ACTIVE. Sink + * key when its guard permits deletion. Active values write the payload. Number 0 is ACTIVE. Sink * validation via coerceFlagValue (validate at the convergence * point every caller reaches). applyFlags(settingsJson, FlagsRecord) is the * sole API; init.ts works directly with FlagsRecord (no legacy string[] bridge). @@ -86,7 +86,9 @@ interface BooleanFlagDefCommon extends FlagDefCommon { export interface EnvBooleanFlagDef extends BooleanFlagDefCommon { readonly target: EnvFlagTarget; readonly onPayload: string; - /** Env keys are never shape-guarded — `never` makes that a compile error, not a silent no-op. */ + /** D-CODE-MODE-OWN-VALUE: manage only the exact `onPayload` for this env key. */ + readonly deleteOnlyOwnPayload?: true; + /** Only setting keys can use a shape guard. */ readonly settingDeleteGuard?: never; } @@ -391,7 +393,7 @@ export const FLAG_REGISTRY: readonly ClaudeCodeFlag[] = [ id: 'disable-nonessential-traffic', label: 'Disable non-essential traffic', description: 'Suppress usage metrics telemetry', - hint: 'Suppresses usage telemetry sent back to Anthropic', + hint: 'Suppresses usage telemetry sent to Anthropic; Code Mode does not start', blurb: 'suppress usage telemetry', kind: 'boolean', target: { type: 'env', key: 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC' }, @@ -502,6 +504,29 @@ export const FLAG_REGISTRY: readonly ClaudeCodeFlag[] = [ // src/core/teammate-mode-cleanup.ts during uninstall (stripDevflowTeammateModeFromJson). // The env var above is the only surface managed by FLAG_REGISTRY for this flag. }, + { + /** + * D-CODE-MODE-VENDOR: Claude Code docs, "Run tool calls from code with Code Mode" + * (read 2026-11-18). JavaScript can make several tool calls in one step. + * Deny and ask rules and PreToolUse hooks still apply per call. Auto mode + * reviews the code; other modes prompt per call when their rules require it. + * The blockers below apply. Code Mode does not work with `-p`, so `claude -p` + * workers are unaffected. The flag registry owns this key; the proxy never writes it. + */ + id: 'code-mode', + label: 'Code Mode (experimental)', + description: 'Blocked by the Devflow proxy, disable-nonessential-traffic, a custom ANTHROPIC_BASE_URL, ' + + 'apiKeyHelper, ANTHROPIC_AUTH_TOKEN, or OpenTelemetry export. ' + + 'Code Mode with agent-teams needs Claude Code v2.1.326+.', + hint: 'Enable experimental Code Mode for every new session', + blurb: 'tool calls run from code', + kind: 'boolean', + target: { type: 'env', key: 'CLAUDE_CODE_EXPERIMENTAL_CODE_MODE' }, + onPayload: '1', + deleteOnlyOwnPayload: true, + recommended: false, + defaultValue: false, + }, { // Upstream: restores Todo/TaskCreate tools removed by default in Opus 4.8+, @@ -1219,29 +1244,15 @@ export function settingHoldsUserValue(settingsJson: string, flagId: string): boo } /** - * D-ADOPT-RESPECTS-USER: seed a guarded setting flag OFF when adopting it ON would - * overwrite a value the user already owns. - * - * A flag the manifest does not record is adopted at its `defaultValue`. For a flag whose - * target is a settings.json key with a `settingDeleteGuard`, adopting ON writes its - * managed payload over whatever is on disk (the guard protects deletion, not writes). - * When the key already holds a value that is not the managed shape - a user's own `"1h"` - * under `subagentPromptCacheTtl` - that write would silently replace a deliberate choice. - * Such a flag is set `false` instead; with the record then claiming `false`, the converge - * pipeline neither writes nor deletes the user's value. - * - * Scope: only flags ABSENT from `manifestFlags` (or all of them on a fresh install, when - * it is null). A flag the manifest records keeps its value in `flags`, so an explicit - * enable still wins. `devflow init --reset` hands this an empty settings snapshot - * (resolveResetGatedInputs), so nothing is detected and the factory default stands. The rule is generic over guarded - * setting flags: no flag id is special-cased, and `settingHoldsUserValue` is the one place - * that decides "the disk holds something that is not ours". For a flag whose default is - * already OFF (suppress-attribution) it changes nothing. + * D-ADOPT-RESPECTS-USER: seed guarded flags from the current settings without + * replacing user values. For a setting with a shape guard, seed an unclaimed + * flag OFF when `settingHoldsUserValue` is true. Keep any claimed setting flag. + * For an env flag with an own-payload guard, adopt an unclaimed on payload as ON, + * or seed an ON record as OFF if the user has a different value. * - * Two callers apply the same rule: the init seed, and the flags TUI's starting rows (an - * upgrade that has not run init yet would otherwise offer a Save that overwrites the value). - * - * Pure function - the settings snapshot is read by the caller and passed in. + * Init and the flags TUI share this rule for their starting rows. An empty reset + * snapshot leaves the factory defaults intact. The caller supplies the pre-strip + * snapshot; this function does no I/O. */ export function respectUserOwnedSettings( flags: FlagsRecord, @@ -1254,7 +1265,13 @@ export function respectUserOwnedSettings( if (!adoptedAtDefault) continue; if (settingHoldsUserValue(settingsSnapshot, flag.id)) result[flag.id] = false; } - return result; + let env: Record | undefined; + try { + env = asPlainObject(asPlainObject(JSON.parse(settingsSnapshot))?.env); + } catch { + // Treat an unreadable seed snapshot as absent, as with guarded settings. + } + return foldOwnEnvPayloads(result, manifestFlags, env, []); } /** @@ -1269,7 +1286,8 @@ export function respectUserOwnedSettings( * across the entire apply/strip pipeline. * * Single-source invariant: both the disable path (applyFlags neutral branch) and - * the uninstall path (stripFlags) collapse to this predicate. + * the uninstall path (stripFlags) use this predicate for settings and its twin + * `canDeleteEnvKey` for env keys. */ function canDeleteSettingKey(flag: ClaudeCodeFlag, settings: Record): boolean { if (flag.kind !== 'boolean') return true; @@ -1277,6 +1295,49 @@ function canDeleteSettingKey(flag: ClaudeCodeFlag, settings: Record> | undefined, +): boolean { + return flag.deleteOnlyOwnPayload === true && env?.[flag.target.key] === flag.onPayload; +} + +/** Any other present value at a guarded env key belongs to the user. */ +export function holdsUserEnvValue( + flag: EnvBooleanFlagDef, + env: Readonly> | undefined, +): boolean { + return flag.deleteOnlyOwnPayload === true && env !== undefined + && Object.hasOwn(env, flag.target.key) && !holdsOwnEnvPayload(flag, env); +} + +function canDeleteEnvKey(flag: ClaudeCodeFlag, env: Readonly>): boolean { + return !isEnvBooleanFlag(flag) || flag.deleteOnlyOwnPayload === undefined + || holdsOwnEnvPayload(flag, env); +} + +/** Adopt unclaimed payloads and keep user values unless this write explicitly turns the flag on. */ +function foldOwnEnvPayloads( + record: FlagsRecord, + claimedIn: FlagsRecord | null, + env: Readonly> | undefined, + explicitOn: readonly string[], +): FlagsRecord { + const result = { ...record }; + for (const flag of FLAG_REGISTRY) { + if (!isEnvBooleanFlag(flag) || flag.deleteOnlyOwnPayload === undefined) continue; + const id = flag.id; + const claimed = claimedIn !== null && Object.hasOwn(claimedIn, id); + if (!claimed && holdsOwnEnvPayload(flag, env)) { + result[id] = true; + } else if (record[id] === true && holdsUserEnvValue(flag, env) && !explicitOn.includes(id)) { + result[id] = false; + } + } + return result; +} + /** * Return `v` as a `Record` only when it is a plain object. * Returns undefined for arrays, null, or non-objects. @@ -1321,7 +1382,7 @@ function buildPayload(flag: ClaudeCodeFlag, value: FlagValue): unknown { * * - Unknown flag IDs are skipped (forward-compatible with future flags). * - `coerceFlagValue` is called at the sink before applying. - * - Neutral values delete their target key. + * - Neutral values delete their target key when the ownership guard permits it. * - Env payloads for number flags are stringified ('40', never 40). * - Setting payloads for string flags with wrapKey are shaped ({ command: v }). * - env object is created on demand; deleted when it becomes empty. @@ -1348,11 +1409,10 @@ export function applyFlags(settingsJson: string, flags: FlagsRecord): string { const safe = coerceFlagValue(flag, value); if (isNeutral(flag, safe)) { - // Neutral → delete the target key if (flag.target.type === 'env') { // asPlainObject guard: "env": [] must not delete a user's env var (applies TS-M3) const env = asPlainObject(settings.env); - if (env) delete env[flag.target.key]; + if (env && canDeleteEnvKey(flag, env)) delete env[flag.target.key]; } else { if (canDeleteSettingKey(flag, settings)) delete settings[flag.target.key]; } @@ -1380,9 +1440,9 @@ export function applyFlags(settingsJson: string, flags: FlagsRecord): string { /** * Strip all flag-managed keys from a settings JSON string. - * Registry-driven unconditional delete. Now covers viewMode (via view-mode - * registry entry) and object-valued settings (spellcheck → key deleted). - * Cleans up empty env object. Strip-then-apply idempotence preserved (INV-1). + * Registry-driven guarded delete: respect setting shape guards and env own-payload + * guards. Remove the env object if it is empty. Preserve strip-then-apply + * idempotence with the converged record (INV-1). */ export function stripFlags(settingsJson: string): string { // REL-M2 sink guard: mirror of applyFlags — throw early on a @@ -1397,7 +1457,7 @@ export function stripFlags(settingsJson: string): string { for (const flag of FLAG_REGISTRY) { if (flag.target.type === 'env') { - if (env) delete env[flag.target.key]; + if (env && canDeleteEnvKey(flag, env)) delete env[flag.target.key]; } else { if (canDeleteSettingKey(flag, settings)) delete settings[flag.target.key]; } @@ -1493,18 +1553,18 @@ export function resolveFinalViewMode( * - `null` → nothing previously owned (fresh install) * - `FlagsRecord`→ the original manifest flags BEFORE seeding (init path) * - * A flag is "claimed" when it is present and non-null in the claimed set. + * A flag is "claimed" when its ID is present in the claimed set. * Claimed: record value wins (devflow previously set this value). * Unclaimed: fold from settings — if the user has a value in settings.json, * adopt it into the record (devflow takes ownership). * - * Boolean flags: never folded — on/off is always record-driven. + * Boolean flags: Step 2b adopts unclaimed managed settings. Step 2c adopts + * unclaimed env on payloads and folds ON to OFF for user values unless this + * write explicitly turns the flag on. All other booleans stay record-driven. * - * The fold MUST run on pre-strip content — `stripFlags` removes the target - * keys, making any fold after strip vacuous. + * The folds must use pre-strip content to see managed values before deletion. * - * Uninstall note: `src/cli/commands/uninstall.ts` calls `stripFlags` directly - * with no record argument, preserving its full-sweep semantics. Do not change. + * Uninstall uses `stripFlags` directly and honors the same delete guards. * * Pure function: no I/O. * @@ -1515,6 +1575,7 @@ export function resolveFinalViewMode( * @param opts.ownedRecord Prior ownership set; see semantics above. * Init path: `existingManifest?.features.flags ?? null`. * persistFlagConfig path: omit (undefined). + * @param opts.explicitOn IDs this write turns from OFF to ON. Default: none. * @returns `{ settings: updated JSON string, record: folded FlagsRecord }` */ export function convergeFlagsIntoSettings( @@ -1523,6 +1584,7 @@ export function convergeFlagsIntoSettings( opts: { viewModeExplicit: boolean; ownedRecord?: FlagsRecord | null; + explicitOn?: readonly string[]; }, ): { settings: string; record: FlagsRecord } { // ── Step 1: fold view-mode (must read pre-strip) ────────────────────────── @@ -1540,8 +1602,7 @@ export function convergeFlagsIntoSettings( // ── Step 2: fold existing values for valued flags (pre-strip) ──────────── // D15-adopt: for unclaimed valued flags, read the current settings value and - // adopt it into the record. Claimed flags (previously set by devflow) keep - // their record value; boolean flags are never folded. + // adopt it into the record. Claimed valued flags keep their record value. // // "Claimed" is determined by opts.ownedRecord: // undefined → use `record` (persistFlagConfig: manifest record = owned set) @@ -1559,7 +1620,7 @@ export function convergeFlagsIntoSettings( const env = asPlainObject(parsed.env); for (const flag of FLAG_REGISTRY) { - if (flag.kind === 'boolean') continue; // boolean flags: record-driven only + if (flag.kind === 'boolean') continue; // boolean folds follow below if (flag.id === 'view-mode') continue; // already handled above // Check whether devflow previously owned this flag's key. @@ -1601,8 +1662,7 @@ export function convergeFlagsIntoSettings( // ── Step 2b: adopt guarded boolean settings before the strip ───────────── // D-ATTR-ADOPT: a delete guard is evidence about the VALUE, // never about the record — a pre-existing on-disk key whose value matches the - // managed shape means devflow wrote it, so adopt it into the record now, before - // stripFlags can unconditionally remove it on the next line. + // managed shape qualifies for adoption before stripFlags removes that value. // // Mirror of the view-mode fold (Step 1): adopt only when: // (a) the flag has a settingDeleteGuard (guarded boolean only) @@ -1628,9 +1688,12 @@ export function convergeFlagsIntoSettings( } } - // ── Step 3: strip all managed keys, then apply the folded record ────────── + // ── Step 2c: fold guarded env values before the strip ─────────────────── + const finalRecord = foldOwnEnvPayloads(folded, claimedIn, env, opts.explicitOn ?? []); + + // ── Step 3: strip managed keys, then apply the folded record ───────────── const stripped = stripFlags(settingsJson); - const applied = JSON.parse(applyFlags(stripped, folded)) as Record; + const applied = JSON.parse(applyFlags(stripped, finalRecord)) as Record; // ── Step 4: restore the pre-strip key order (D-KEY-ORDER) ──────────────── const ordered = orderKeysLike(parsed, applied); @@ -1640,7 +1703,7 @@ export function convergeFlagsIntoSettings( ? { ...ordered, env: orderKeysLike(beforeEnv, afterEnv) } : ordered; - return { settings: JSON.stringify(settings, null, 2) + '\n', record: folded }; + return { settings: JSON.stringify(settings, null, 2) + '\n', record: finalRecord }; } /** diff --git a/tests/fixtures/golden/install-snapshot-all-off.txt b/tests/fixtures/golden/install-snapshot-all-off.txt index 617eb042c..dbb7a3e1f 100644 --- a/tests/fixtures/golden/install-snapshot-all-off.txt +++ b/tests/fixtures/golden/install-snapshot-all-off.txt @@ -533,6 +533,7 @@ d sub/ "disable-1m-context": false, "disable-autoupdater": false, "agent-teams": false, + "code-mode": false, "enable-todo-tools": false, "suppress-attribution": false, "subagent-spawn-depth": null, diff --git a/tests/fixtures/golden/install-snapshot-github.txt b/tests/fixtures/golden/install-snapshot-github.txt index 22c3f54f4..241819265 100644 --- a/tests/fixtures/golden/install-snapshot-github.txt +++ b/tests/fixtures/golden/install-snapshot-github.txt @@ -595,6 +595,7 @@ d sub/ "disable-1m-context": false, "disable-autoupdater": false, "agent-teams": false, + "code-mode": false, "enable-todo-tools": false, "suppress-attribution": false, "subagent-spawn-depth": null, diff --git a/tests/fixtures/golden/install-snapshot-jira-hipaa.txt b/tests/fixtures/golden/install-snapshot-jira-hipaa.txt index 6a25c27c3..4a74fdb60 100644 --- a/tests/fixtures/golden/install-snapshot-jira-hipaa.txt +++ b/tests/fixtures/golden/install-snapshot-jira-hipaa.txt @@ -613,6 +613,7 @@ d sub/ "disable-1m-context": false, "disable-autoupdater": false, "agent-teams": false, + "code-mode": false, "enable-todo-tools": false, "suppress-attribution": false, "subagent-spawn-depth": null, diff --git a/tests/flags.test.ts b/tests/flags.test.ts index 74c9d7707..aea7c2d05 100644 --- a/tests/flags.test.ts +++ b/tests/flags.test.ts @@ -21,6 +21,7 @@ import { convergeFlagsIntoSettings, settingHoldsManagedShape, settingHoldsUserValue, + respectUserOwnedSettings, isEnvBooleanFlag, // Kept verbatim VIEW_MODES, @@ -1034,6 +1035,113 @@ describe('bash-max-timeout-ms flag', () => { // ─── New flag: auto-compact-window ──────────────────────────────────────────── +describe('code-mode registry entry', () => { + it('offers Code Mode after Agent Teams and leaves it off by default', () => { + const agentTeams = FLAG_REGISTRY.findIndex(f => f.id === 'agent-teams'); + expect(FLAG_REGISTRY[agentTeams + 1]).toMatchObject({ + id: 'code-mode', + label: 'Code Mode (experimental)', + kind: 'boolean', + target: { type: 'env', key: 'CLAUDE_CODE_EXPERIMENTAL_CODE_MODE' }, + onPayload: '1', + defaultValue: false, + recommended: false, + }); + expect(getDefaultFlagsRecord()['code-mode']).toBe(false); + }); + + it('names the Code Mode blockers and the minimum Agent Teams version', () => { + const flag = FLAG_REGISTRY.find(f => f.id === 'code-mode'); + expect(flag?.description).toContain('Claude Code v2.1.326+'); + for (const blocker of [ + 'Devflow proxy', + 'disable-nonessential-traffic', + 'ANTHROPIC_BASE_URL', + 'apiKeyHelper', + 'ANTHROPIC_AUTH_TOKEN', + 'OpenTelemetry export', + ]) { + expect(flag?.description).toContain(blocker); + } + expect(flag?.hint).toMatch(/experimental.*every new session/i); + }); + + it('warns that the non-essential traffic flag stops Code Mode', () => { + const flag = FLAG_REGISTRY.find(f => f.id === 'disable-nonessential-traffic'); + expect(flag?.hint).toContain('Code Mode does not start'); + }); +}); + +describe('code-mode own-value rule', () => { + const id = 'code-mode'; + const key = 'CLAUDE_CODE_EXPERIMENTAL_CODE_MODE'; + const settingsWith = (value: unknown): string => JSON.stringify({ env: { [key]: value } }); + const opts = { viewModeExplicit: false }; + + it.each(['0', 'true', '', 1])('preserves user value %j on disable', value => { + expect(JSON.parse(applyFlags(settingsWith(value), { [id]: false }))) + .toEqual({ env: { [key]: value } }); + }); + + it('deletes the exact on payload on disable', () => { + const enabled = applyFlags('{}', { [id]: true }); + expect(JSON.parse(enabled)).toEqual({ env: { [key]: '1' } }); + expect(JSON.parse(applyFlags(enabled, { [id]: false }))).toEqual({}); + }); + + it('strips only the exact on payload', () => { + expect(JSON.parse(stripFlags(settingsWith('0')))).toEqual({ env: { [key]: '0' } }); + expect(JSON.parse(stripFlags(settingsWith('1')))).toEqual({}); + }); + + it.each([ + { path: 'flags', record: {}, options: opts }, + { path: 'init', record: { [id]: false }, options: { ...opts, ownedRecord: {} } }, + ])('adopts a hand-set on payload before the strip on the $path path', ({ record, options }) => { + const result = convergeFlagsIntoSettings(settingsWith('1'), record, options); + expect(result.record[id]).toBe(true); + expect(JSON.parse(result.settings)).toEqual({ env: { [key]: '1' } }); + }); + + it('keeps a claimed off value and strips the exact on payload', () => { + const result = convergeFlagsIntoSettings(settingsWith('1'), { [id]: false }, opts); + expect(result.record[id]).toBe(false); + expect(JSON.parse(result.settings)).toEqual({}); + }); + + it('folds a stale on record to off without a second change on the next pass', () => { + const initial = { [id]: true }; + const result = convergeFlagsIntoSettings(settingsWith('0'), initial, opts); + expect(result.record[id]).toBe(false); + expect(initial[id]).toBe(true); + expect(JSON.parse(result.settings)).toEqual({ env: { [key]: '0' } }); + expect(convergeFlagsIntoSettings(result.settings, result.record, opts)).toEqual(result); + }); + + it('replaces a user value only if this flag is explicit on', () => { + const record = { [id]: true }; + const settings = settingsWith('0'); + const unrelated = convergeFlagsIntoSettings(settings, record, { ...opts, explicitOn: ['lsp'] }); + expect(unrelated.record[id]).toBe(false); + expect(JSON.parse(unrelated.settings)).toEqual({ env: { [key]: '0' } }); + + const requested = convergeFlagsIntoSettings(settings, record, { ...opts, explicitOn: [id] }); + expect(requested.record[id]).toBe(true); + expect(JSON.parse(requested.settings)).toEqual({ env: { [key]: '1' } }); + }); + + it('seeds on for a hand-set on payload with no manifest claim', () => { + const seed = respectUserOwnedSettings({ [id]: false }, {}, settingsWith('1')); + expect(seed[id]).toBe(true); + }); + + it('seeds off when settings hold a user value and the manifest claims on', () => { + const record = { [id]: true }; + const seed = respectUserOwnedSettings(record, record, settingsWith('0')); + expect(seed[id]).toBe(false); + }); +}); + /** * D-AUTO-COMPACT-WINDOW-OPT-IN (AC-406). The flag is opt-in: unset by default, so a * fresh install and a re-init (init applies the seeded record without asking) never @@ -1070,8 +1178,8 @@ describe('auto-compact-window flag', () => { expect(ids.indexOf('auto-compact-window')).toBeGreaterThan(lastBoolean); }); - it('the registry holds 32 flags (docs/cli-reference.md and file-organization.md state the count)', () => { - expect(FLAG_REGISTRY).toHaveLength(32); + it('the registry holds 33 flags', () => { + expect(FLAG_REGISTRY).toHaveLength(33); }); it('a set value is written to the settings env block as a decimal string', () => { From b8ec662851129a38b42ac46575b2f2b45fa7a1f3 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 00:17:10 +0200 Subject: [PATCH 02/20] feat(code-mode): centralize local checks Move proxy URL classification into core. Give Code Mode one read-only source for local signals, refusals and warnings. Keep the existing proxy command interface. Task: feat/code-mode-direct (phase 2) Refs #792 --- src/cli/commands/proxy.ts | 29 +---- src/core/code-mode.ts | 149 ++++++++++++++++++++++ src/core/proxy-state.ts | 22 ++++ tests/code-mode.test.ts | 261 ++++++++++++++++++++++++++++++++++++++ tests/proxy-state.test.ts | 14 ++ 5 files changed, 449 insertions(+), 26 deletions(-) create mode 100644 src/core/code-mode.ts create mode 100644 tests/code-mode.test.ts diff --git a/src/cli/commands/proxy.ts b/src/cli/commands/proxy.ts index 104c47093..621419d26 100644 --- a/src/cli/commands/proxy.ts +++ b/src/cli/commands/proxy.ts @@ -29,6 +29,7 @@ import { buildProxyState, buildRoutingConfigJson, proxyBaseUrl, + readProxyEnvState, proxyJsonExists, resolveProxyBin, DEFAULT_PROXY_PORT, @@ -65,6 +66,8 @@ import { type Settings, } from '../../targets/claude-code/hooks.js'; +export { readProxyEnvState } from '../../core/proxy-state.js'; + // ─── Result type (local pattern) ────────────────────────────────────────────── type Result = { ok: true; value: T } | { ok: false; error: E }; @@ -93,9 +96,6 @@ const isProxyHook = devflowHookOwner([PROXY_HOOK_MARKER]); /** The events the ensure-proxy hook is registered on. */ const PROXY_HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit'] as const; -/** Pattern matching our relay's ANTHROPIC_BASE_URL value. */ -const OUR_BASE_URL_PATTERN = /^http:\/\/127\.0\.0\.1:\d+$/; - /** Timeout for individual TCP connect probes and HTTP health checks (ms). */ const PROBE_TIMEOUT_MS = 2000; /** @@ -258,29 +258,6 @@ export function stripProxyEnv(settingsJson: string, managedPort: number): string return JSON.stringify(settings, null, 2) + '\n'; } -/** - * Read the proxy env state from a settings JSON string. - * - * Returns: - * 'ours' — ANTHROPIC_BASE_URL = our relay on the given port - * 'ours-other-port'— ANTHROPIC_BASE_URL = our relay on a different port - * 'foreign' — ANTHROPIC_BASE_URL set but not our relay - * 'absent' — ANTHROPIC_BASE_URL not set - */ -export function readProxyEnvState( - settingsJson: string, - port: number, -): 'ours' | 'ours-other-port' | 'foreign' | 'absent' { - const settings = JSON.parse(settingsJson) as Settings; - const s = settings as Record; - const env = s.env as Record | undefined; - const url = env?.ANTHROPIC_BASE_URL; - if (typeof url !== 'string') return 'absent'; - if (url === proxyBaseUrl(port)) return 'ours'; - if (OUR_BASE_URL_PATTERN.test(url)) return 'ours-other-port'; - return 'foreign'; -} - // ─── Pure hook helpers ────────────────────────────────────────────────────────── /** diff --git a/src/core/code-mode.ts b/src/core/code-mode.ts new file mode 100644 index 000000000..e3564a7b6 --- /dev/null +++ b/src/core/code-mode.ts @@ -0,0 +1,149 @@ +import { constants, promises as fs } from 'node:fs'; +import { join } from 'node:path'; +import { findFlag, holdsOwnEnvPayload, holdsUserEnvValue, isEnvBooleanFlag } from './flags.js'; +import { readGateManifest } from './gate-level.js'; +import { classifyProxyBaseUrl, DEFAULT_PROXY_PORT, readProxyState } from './proxy-state.js'; +import type { ProxyEnvState, Result } from './proxy-state.js'; + +export const CODE_MODE_ENABLE_REFUSAL = 'Cannot enable Code Mode while the Devflow proxy is on. Run `devflow proxy --disable` first.'; +export const PROXY_ENABLE_REFUSAL = 'Cannot enable the Devflow proxy while Code Mode is on. Run `devflow flags --disable code-mode` first.'; +export const CODE_MODE_READ_FAILURE = 'Cannot make this change because Devflow could not check the Code Mode and proxy state.'; +export const CODE_MODE_PROXY_BLOCKER = 'Code Mode does not start while the Devflow proxy is on. Run `devflow flags --disable code-mode` or `devflow proxy --disable`.'; +export const CODE_MODE_TRAFFIC_BLOCKER = 'Code Mode does not start while disable-nonessential-traffic is on. Run `devflow flags --disable code-mode`.'; +export const CODE_MODE_USER_VALUE_NOTE = 'Code Mode is off because your settings override the flag.'; +export const CODE_MODE_RECORD_FALSE_NOTE = 'Your settings enable Code Mode, but the flag record is off. The next flag write removes the Code Mode setting.'; +export const CODE_MODE_NEW_SESSIONS_SUFFIX = 'This change applies to new sessions only.'; + +const codeModeFlag = findFlag('code-mode'); +const trafficFlag = findFlag('disable-nonessential-traffic'); +const MAX_SETTINGS_BYTES = 1024 * 1024; + +type RawRecord = Readonly>; + +export interface CodeModeSignals { + readonly env: RawRecord | undefined; + readonly record: RawRecord | null; + readonly proxyOn: boolean; +} + +export interface CodeModeBlockerState { + readonly codeModeOn: boolean; + readonly proxyOn: boolean; + readonly trafficOn: boolean; +} + +export function isCodeModeOn(record: RawRecord | null, env: RawRecord | undefined): boolean { + if (codeModeFlag && isEnvBooleanFlag(codeModeFlag)) { + if (holdsOwnEnvPayload(codeModeFlag, env)) return true; + if (holdsUserEnvValue(codeModeFlag, env)) return false; + } + return record?.['code-mode'] === true; +} + +export function isTrafficOn(record: RawRecord | null, env: RawRecord | undefined): boolean { + if (record?.['disable-nonessential-traffic'] === true) return true; + if (!env || !trafficFlag || !isEnvBooleanFlag(trafficFlag)) return false; + const key = trafficFlag.target.key; + return Object.hasOwn(env, key) && env[key] !== '0' && env[key] !== 'false'; +} + +export function isProxyOn({ proxyJsonOn, manifestProxy, urlState }: { + readonly proxyJsonOn: boolean; + readonly manifestProxy: boolean; + readonly urlState: ProxyEnvState; +}): boolean { + return proxyJsonOn || manifestProxy || urlState === 'ours' || urlState === 'ours-other-port'; +} + +export function turnsOnCodeMode(beforeOn: boolean, requestedOn: boolean): boolean { + return !beforeOn && requestedOn; +} + +export function codeModeRefusal(before: Pick, turnsOn: boolean): string | undefined { + return turnsOn && before.proxyOn ? CODE_MODE_ENABLE_REFUSAL : undefined; +} + +/** D-CODE-MODE-BLOCKERS: Report conflicts only while Code Mode is on. */ +export function codeModeBlockers({ codeModeOn, proxyOn, trafficOn }: CodeModeBlockerState): string[] { + if (!codeModeOn) return []; + const lines: string[] = []; + if (proxyOn) lines.push(CODE_MODE_PROXY_BLOCKER); + if (trafficOn) lines.push(CODE_MODE_TRAFFIC_BLOCKER); + return lines; +} + +/** Warn once per blocker in the final state, even if the write did not add it. */ +export function writeTimeWarnings(_before: CodeModeBlockerState, after: CodeModeBlockerState): string[] { + return codeModeBlockers(after); +} + +export function initCodeModeWarnings({ proxyEnabled, record, env }: { + readonly proxyEnabled: boolean; + readonly record: RawRecord | null; + readonly env: RawRecord | undefined; +}): string[] { + return codeModeBlockers({ + codeModeOn: isCodeModeOn(record, env), + proxyOn: proxyEnabled, + trafficOn: isTrafficOn(record, env), + }); +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +async function readSettingsEnv(settingsPath: string): Promise { + try { + // O_NONBLOCK prevents a pipe at this path from blocking the open. + const file = await fs.open(settingsPath, constants.O_RDONLY | constants.O_NONBLOCK); + try { + const stat = await file.stat(); + if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return undefined; + const buffer = Buffer.alloc(stat.size + 1); + const { bytesRead } = await file.read(buffer); + if (bytesRead !== stat.size) return undefined; + const settings: unknown = JSON.parse(buffer.toString('utf8', 0, bytesRead)); + if (!isPlainObject(settings)) return undefined; + return isPlainObject(settings.env) ? settings.env : {}; + } finally { + await file.close(); + } + } catch (err) { + return err instanceof Error && 'code' in err && err.code === 'ENOENT' ? {} : undefined; + } +} + +/** + * D-CODE-MODE-SIGNALS: Read only local files. Never probe the relay or heal the manifest. + * Count an unreadable proxy state file as on. Ignore an absent or corrupt manifest. + * A null Devflow directory limits the check to the user settings env. + */ +export async function readCodeModeSignals( + claudeDir: string, + devflowDir: string | null, +): Promise> { + try { + const env = await readSettingsEnv(join(claudeDir, 'settings.json')); + const [proxy, manifest] = devflowDir === null + ? [null, null] + : await Promise.all([readProxyState(devflowDir), readGateManifest(devflowDir)]); + const rawFeatures = manifest && 'raw' in manifest ? manifest.raw.features : null; + const features = isPlainObject(rawFeatures) ? rawFeatures : null; + const urlState = classifyProxyBaseUrl(env?.ANTHROPIC_BASE_URL, proxy?.ok ? proxy.value.port : DEFAULT_PROXY_PORT); + return { + ok: true, + value: { + env, + record: isPlainObject(features?.flags) ? features.flags : null, + proxyOn: isProxyOn({ + proxyJsonOn: proxy !== null && (!proxy.ok || proxy.value.enabled), + manifestProxy: features?.proxy === true, + urlState, + }), + }, + }; + } catch { + return { ok: false, error: CODE_MODE_READ_FAILURE }; + } +} diff --git a/src/core/proxy-state.ts b/src/core/proxy-state.ts index cb1b34ef7..1ebfddd1a 100644 --- a/src/core/proxy-state.ts +++ b/src/core/proxy-state.ts @@ -294,6 +294,28 @@ export function proxyBaseUrl(port: number): string { return `http://127.0.0.1:${port}`; } +const OUR_BASE_URL_PATTERN = /^http:\/\/127\.0\.0\.1:\d+$/; + +export type ProxyEnvState = 'ours' | 'ours-other-port' | 'foreign' | 'absent'; + +/** Classify a settings URL. A relay URL on any port counts as a proxy signal. */ +export function classifyProxyBaseUrl(url: unknown, port: number): ProxyEnvState { + if (typeof url !== 'string') return 'absent'; + if (url === proxyBaseUrl(port)) return 'ours'; + if (OUR_BASE_URL_PATTERN.test(url)) return 'ours-other-port'; + return 'foreign'; +} + +/** Read the proxy env state from settings JSON. Invalid JSON still raises a parse error. */ +export function readProxyEnvState(settingsJson: string, port: number): ProxyEnvState { + const settings = JSON.parse(settingsJson) as Record; + const env = settings.env; + const url = typeof env === 'object' && env !== null && 'ANTHROPIC_BASE_URL' in env + ? env.ANTHROPIC_BASE_URL + : undefined; + return classifyProxyBaseUrl(url, port); +} + // --------------------------------------------------------------------------- // isProxyEnabled — the primary contract other modules consume // --------------------------------------------------------------------------- diff --git a/tests/code-mode.test.ts b/tests/code-mode.test.ts new file mode 100644 index 000000000..ef1591f51 --- /dev/null +++ b/tests/code-mode.test.ts @@ -0,0 +1,261 @@ +import { promises as fs } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as codeMode from '../src/core/code-mode.js'; +import * as proxyState from '../src/core/proxy-state.js'; + +const CODE_ENV = 'CLAUDE_CODE_EXPERIMENTAL_CODE_MODE'; +const TRAFFIC_ENV = 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'; +const proxyBlocker = 'Code Mode does not start while the Devflow proxy is on.'; +const trafficBlocker = 'Code Mode does not start while disable-nonessential-traffic is on. Run `devflow flags --disable code-mode`.'; +const onRecord = { 'code-mode': true }; + +const bothBlockers = { codeModeOn: true, proxyOn: true, trafficOn: true }; +const codeModeOff = { ...bothBlockers, codeModeOn: false }; + +describe('Code Mode and traffic state', () => { + it.each(['0', 'true', '', 1, null, false])('counts a settings value of %j as off despite an on record', (value) => { + expect(codeMode.isCodeModeOn(onRecord, { [CODE_ENV]: value })).toBe(false); + }); + + it('counts the owned payload as active even if the recorded flag is off', () => { + expect(codeMode.isCodeModeOn({ 'code-mode': false }, { [CODE_ENV]: '1' })).toBe(true); + }); + + it('uses the record when the settings key is absent', () => { + expect(codeMode.isCodeModeOn(onRecord, {})).toBe(true); + }); + + it('counts Code Mode as off when no source has a value', () => { + expect(codeMode.isCodeModeOn(null, undefined)).toBe(false); + }); + + it.each(['1', 'FALSE', 'no', '', 0, false, null])('counts a present traffic value of %j as on', (value) => { + expect(codeMode.isTrafficOn(null, { [TRAFFIC_ENV]: value })).toBe(true); + }); + + it.each(['0', 'false'])('counts a traffic value of %j as off without a record', (value) => { + expect(codeMode.isTrafficOn(null, { [TRAFFIC_ENV]: value })).toBe(false); + }); + + it('counts missing traffic settings and record as off', () => { + expect(codeMode.isTrafficOn(null, {})).toBe(false); + }); + + it('counts a true traffic record as on even if the settings value is off', () => { + expect(codeMode.isTrafficOn({ 'disable-nonessential-traffic': true }, { [TRAFFIC_ENV]: '0' })).toBe(true); + }); +}); + +describe('Code Mode refusals and warnings', () => { + it.each([ + [false, true, true], + [true, true, false], + [false, false, false], + [true, false, false], + ])('detects a transition from %s to %s: %s', (beforeOn, requestedOn, turnsOn) => { + expect(codeMode.turnsOnCodeMode(beforeOn, requestedOn)).toBe(turnsOn); + }); + + it('directs an off-to-on request to disable the proxy when the proxy is on', () => { + expect(codeMode.codeModeRefusal({ proxyOn: true }, true)).toContain('devflow proxy --disable'); + }); + + it.each([[false, true], [true, false], [false, false]])('does not refuse with proxy %s and transition %s', (proxyOn, turnsOn) => { + expect(codeMode.codeModeRefusal({ proxyOn }, turnsOn)).toBeUndefined(); + }); + + it('does not print blocker lines while Code Mode is off', () => { + expect(codeMode.codeModeBlockers(codeModeOff)).toEqual([]); + }); + + it('returns both blocker lines once while Code Mode and both blockers are on', () => { + expect(codeMode.codeModeBlockers(bothBlockers)).toEqual([ + expect.stringContaining(proxyBlocker), + trafficBlocker, + ]); + }); + + it('returns no blocker line when Code Mode is on alone', () => { + expect(codeMode.codeModeBlockers({ codeModeOn: true, proxyOn: false, trafficOn: false })).toEqual([]); + }); + + it('warns about the final blockers even when they were present before the write', () => { + expect(codeMode.writeTimeWarnings(bothBlockers, bothBlockers)).toEqual([ + expect.stringContaining(proxyBlocker), + trafficBlocker, + ]); + }); + + it('does not warn when the write turns Code Mode off', () => { + expect(codeMode.writeTimeWarnings(bothBlockers, codeModeOff)).toEqual([]); + }); + + it('warns once about the proxy when init keeps both features on', () => { + expect(codeMode.initCodeModeWarnings({ proxyEnabled: true, record: onRecord, env: {} })).toEqual([ + expect.stringContaining(proxyBlocker), + ]); + }); + + it('does not warn when the user settings override an on record at init', () => { + expect(codeMode.initCodeModeWarnings({ + proxyEnabled: true, record: onRecord, env: { [CODE_ENV]: '0' }, + })).toEqual([]); + }); + + it('does not warn about the proxy when init preflight turns it off', () => { + expect(codeMode.initCodeModeWarnings({ proxyEnabled: false, record: onRecord, env: {} })).toEqual([]); + }); + + it('warns about traffic alone when init ends with the proxy off', () => { + expect(codeMode.initCodeModeWarnings({ + proxyEnabled: false, record: onRecord, env: { [TRAFFIC_ENV]: '1' }, + })).toEqual([trafficBlocker]); + }); + + it('says that a successful change applies to new sessions only', () => { + expect(codeMode.CODE_MODE_NEW_SESSIONS_SUFFIX).toContain('applies to new sessions only'); + }); + + it('directs a proxy enable request to disable Code Mode', () => { + expect(codeMode.PROXY_ENABLE_REFUSAL).toContain('devflow flags --disable code-mode'); + }); + + it('does not name the routing runtime in any exported message', () => { + for (const value of Object.values(codeMode)) { + if (typeof value === 'string') expect(value).not.toMatch(/subswitch/i); + } + }); +}); + +describe('readCodeModeSignals', () => { + let root: string; + let settingsPath: string; + let claudeDir: string; + let devflowDir: string; + + beforeEach(async () => { + root = await fs.mkdtemp(join(tmpdir(), 'code-mode-test-')); + claudeDir = join(root, 'claude'); + devflowDir = join(root, 'devflow'); + settingsPath = join(claudeDir, 'settings.json'); + await Promise.all([fs.mkdir(claudeDir), fs.mkdir(devflowDir)]); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await fs.rm(root, { recursive: true, force: true }); + }); + + async function writeSettings(env: Record): Promise { + await fs.writeFile(settingsPath, JSON.stringify({ env })); + } + + async function read() { + return codeMode.readCodeModeSignals(claudeDir, devflowDir); + } + + async function expectRefusal(shouldRefuse: boolean): Promise { + const signals = await read(); + expect(signals).toMatchObject({ ok: true, value: { proxyOn: shouldRefuse } }); + if (signals.ok) { + expect(Boolean(codeMode.codeModeRefusal(signals.value, true))).toBe(shouldRefuse); + } + } + + it('refuses when only proxy.json says the proxy is on', async () => { + await fs.writeFile(join(devflowDir, 'proxy.json'), '{"enabled":true}'); + await expectRefusal(true); + }); + + it('refuses when proxy.json cannot be parsed', async () => { + await fs.writeFile(join(devflowDir, 'proxy.json'), '{'); + await expectRefusal(true); + }); + + it.each([ + ['http://127.0.0.1:4141', true], + ['http://127.0.0.1:4123', true], + ['https://gateway.example', false], + ])('uses the settings URL %s as a proxy signal: %s', async (url, shouldRefuse) => { + await writeSettings({ ANTHROPIC_BASE_URL: url }); + await expectRefusal(shouldRefuse); + }); + + it('reports no proxy signal when all files are absent', async () => { + expect(await read()).toEqual({ ok: true, value: { record: null, env: {}, proxyOn: false } }); + expect(await fs.readdir(devflowDir)).toEqual([]); + expect(await fs.readdir(claudeDir)).toEqual([]); + }); + + it.each(['{', 'null', '[]', '42'])('reports unavailable settings for a root of %s', async (body) => { + await fs.writeFile(settingsPath, body); + expect(await read()).toMatchObject({ ok: true, value: { env: undefined, proxyOn: false } }); + }); + + it('reports unavailable settings when the path is a directory', async () => { + await fs.mkdir(settingsPath); + expect(await read()).toMatchObject({ ok: true, value: { env: undefined } }); + }); + + it.skipIf(process.getuid?.() === 0 || process.platform === 'win32')('reports unavailable settings for permission errors', async () => { + await writeSettings({ [CODE_ENV]: '1' }); + await fs.chmod(settingsPath, 0o000); + expect(await read()).toMatchObject({ ok: true, value: { env: undefined } }); + }); + + it('reports unavailable settings when the file exceeds the read limit', async () => { + await writeSettings({ [CODE_ENV]: '1', OTHER: 'x'.repeat(1024 * 1024) }); + expect(await read()).toMatchObject({ ok: true, value: { env: undefined } }); + }); + + it.each(['{}', '{"env":null}', '{"env":[]}', '{"env":"1"}'])('reports an empty env for %s', async (body) => { + await fs.writeFile(settingsPath, body); + expect(await read()).toMatchObject({ ok: true, value: { env: {} } }); + }); + + it.each([ + ['accepted', { version: '1', plugins: [], installedAt: 'before', updatedAt: 'after' }], + ['rejected', {}], + ])('reads flags and proxy from a %s manifest without a write', async (_status, rootFields) => { + const body = JSON.stringify({ + ...rootFields, + features: { ambient: false, memory: false, flags: onRecord, proxy: true }, + }); + const manifestPath = join(devflowDir, 'manifest.json'); + await fs.writeFile(manifestPath, body); + expect(await read()).toMatchObject({ ok: true, value: { record: onRecord, proxyOn: true } }); + await expectRefusal(true); + expect(await fs.readFile(manifestPath, 'utf8')).toBe(body); + }); + + it.each(['{', '{"features":false}', '{"features":{"flags":[],"proxy":"true"}}'])( + 'does not adopt invalid flag or proxy signals from %s', async (body) => { + await fs.writeFile(join(devflowDir, 'manifest.json'), body); + expect(await read()).toMatchObject({ ok: true, value: { record: null, proxyOn: false } }); + }, + ); + + it('ignores the machine files when no Devflow directory is given', async () => { + await fs.writeFile(join(devflowDir, 'proxy.json'), '{"enabled":true}'); + await fs.writeFile(join(devflowDir, 'manifest.json'), '{"features":{"proxy":true,"flags":{"code-mode":true}}}'); + const env = { [CODE_ENV]: '1' }; + await writeSettings(env); + expect(await codeMode.readCodeModeSignals(claudeDir, null)).toEqual({ + ok: true, value: { record: null, env, proxyOn: false }, + }); + }); + + it('still sees a settings relay URL when no Devflow directory is given', async () => { + await writeSettings({ ANTHROPIC_BASE_URL: 'http://127.0.0.1:4123' }); + expect(await codeMode.readCodeModeSignals(claudeDir, null)).toMatchObject({ + ok: true, value: { record: null, proxyOn: true }, + }); + }); + + it('returns a fixed error without the cause if a reader rejects', async () => { + vi.spyOn(proxyState, 'readProxyState').mockRejectedValueOnce(new Error('private details')); + expect(await read()).toEqual({ ok: false, error: codeMode.CODE_MODE_READ_FAILURE }); + }); +}); diff --git a/tests/proxy-state.test.ts b/tests/proxy-state.test.ts index 88764d165..be1c17102 100644 --- a/tests/proxy-state.test.ts +++ b/tests/proxy-state.test.ts @@ -21,6 +21,7 @@ import { promises as fs } from 'fs'; import * as os from 'os'; import * as path from 'path'; import { + classifyProxyBaseUrl, readProxyState, writeProxyState, buildRoutingConfigJson, @@ -44,6 +45,19 @@ afterEach(async () => { await fs.rm(tmpDir, { recursive: true, force: true }); }); +describe('proxy URL classification', () => { + it.each([ + ['http://127.0.0.1:5050', 'ours'], + ['http://127.0.0.1:4141', 'ours-other-port'], + ['https://gateway.example', 'foreign'], + ['http://127.0.0.1:5050/', 'foreign'], + [{ href: 'http://127.0.0.1:5050' }, 'absent'], + [undefined, 'absent'], + ])('classifies %j as %s', (url, state) => { + expect(classifyProxyBaseUrl(url, 5050)).toBe(state); + }); +}); + // --------------------------------------------------------------------------- // readProxyState — ENOENT is not an error (TEST-2) // --------------------------------------------------------------------------- From 2273c72f576ca324ff4b5c3961edcdeb3f46bc8e Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 00:33:23 +0200 Subject: [PATCH 03/20] feat(flags): guard Code Mode enables Refuse off-to-on changes while the proxy is on. Show local blockers after a successful write and in the flag tables without extra writes. Refs #792 Task: feat/code-mode-direct --- src/cli/commands/flags.ts | 139 +++++++++++++---- src/core/code-mode.ts | 11 +- src/core/manifest.ts | 5 +- tests/flags-cli.test.ts | 285 ++++++++++++++++++++++++++++++++++ tests/write-set-fence.test.ts | 15 ++ 5 files changed, 422 insertions(+), 33 deletions(-) diff --git a/src/cli/commands/flags.ts b/src/cli/commands/flags.ts index eb6e576af..77e8a11b0 100644 --- a/src/cli/commands/flags.ts +++ b/src/cli/commands/flags.ts @@ -40,6 +40,19 @@ import { type FlagsRecord, type FlagsRecordValue, } from '../../core/flags.js'; +import { + CODE_MODE_NEW_SESSIONS_SUFFIX, + CODE_MODE_READ_FAILURE, + codeModeBlockers, + codeModeRefusal, + codeModeStatusNotes, + isCodeModeOn, + isTrafficOn, + readCodeModeSignals, + turnsOnCodeMode, + writeTimeWarnings, +} from '../../core/code-mode.js'; +import type { CodeModeBlockerState, CodeModeSignals } from '../../core/code-mode.js'; import { readManifest, writeManifest } from '../../core/manifest.js'; import { writeSettingsFileAtomic } from '../../core/fs-atomic.js'; import { sanitizeCell } from '../tui/cells.js'; @@ -51,6 +64,39 @@ import type { FlagsTuiResult } from '../flags-view/terminal.js'; // ─── Internal helpers ───────────────────────────────────────────────────────── +function blockerState({ record, env, proxyOn }: CodeModeSignals): CodeModeBlockerState { + return { codeModeOn: isCodeModeOn(record, env), trafficOn: isTrafficOn(record, env), proxyOn }; +} + +interface CodeModeWrite { + readonly before: CodeModeBlockerState | undefined; + readonly explicitOn?: readonly string[]; +} + +/** Preflight must finish before any path that can write. */ +async function checkCodeModeWrite( + claudeDir: string, + devflowDir: string, + requestedOn: boolean, +): Promise<{ ok: true; value: CodeModeWrite } | { ok: false }> { + const signals = await readCodeModeSignals(claudeDir, devflowDir); + const before = signals.ok ? blockerState(signals.value) : undefined; + const turnsOn = before !== undefined && turnsOnCodeMode(before.codeModeOn, requestedOn); + const refusal = requestedOn && (!signals.ok || signals.value.env === undefined) + ? CODE_MODE_READ_FAILURE + : before && codeModeRefusal(before, turnsOn); + if (refusal) { + p.log.error(refusal); + process.exitCode = 1; + return { ok: false }; + } + return { ok: true, value: { before, explicitOn: turnsOn ? ['code-mode'] : undefined } }; +} + +function logFlagSuccess(id: string, line: string): void { + p.log.success(id === 'code-mode' ? `${line}. ${CODE_MODE_NEW_SESSIONS_SUFFIX}` : line); +} + /** * Read and parse settings.json. * ENOENT → returns `{ content: '{}', ok: true }`. @@ -134,7 +180,7 @@ async function persistFlagConfig( // does not re-read it (two snapshots, one write; readManifest also self-heals // = extra write). null → {ok:false,reason:'no-manifest'} (C2 discriminant intact). manifest: NonNullable>> | null, - opts: { viewModeExplicit: boolean } = { viewModeExplicit: false }, + opts: CodeModeWrite & { readonly viewModeExplicit?: boolean }, ): Promise { // D15: convergeFlagsIntoSettings is the fold-before-strip pipeline entry point // (REG-H1, ARCH-H1). ownedRecord is omitted so the @@ -144,7 +190,7 @@ async function persistFlagConfig( const { settings: updatedSettings, record: foldedRecord } = convergeFlagsIntoSettings( settingsContent, newRecord, - opts, + { viewModeExplicit: opts.viewModeExplicit ?? false, explicitOn: opts.explicitOn }, ); // Accumulate each artifact's failure independently; combine at the end. @@ -185,8 +231,13 @@ async function persistFlagConfig( process.exitCode = 1; } - // OR the locals afterwards — never compose required side effects with ||/&&. - return failed.length > 0 ? { ok: false, failed } : { ok: true }; + if (failed.length > 0) return { ok: false, failed }; + + const after = await readCodeModeSignals(claudeDir, devflowDir); + if (after.ok) { + for (const line of writeTimeWarnings(opts.before, blockerState(after.value))) p.log.warn(line); + } + return { ok: true }; } // ─── Shared utilities ───────────────────────────────────────────────────────── @@ -210,7 +261,8 @@ async function loadFlagContext( claudeDir: string, devflowDir: string, ): Promise<{ ok: true; value: FlagContext } | { ok: false; reason: string }> { - const manifest = await readManifest(devflowDir); + // Defer manifest writes until persist, so a refused or canceled TUI save leaves no changes. + const manifest = await readManifest(devflowDir, { heal: false }); if (!manifest) { return { ok: false, reason: 'No devflow installation found — run devflow init first' }; } @@ -255,8 +307,8 @@ function formatStatusRows(record: FlagsRecord): string[] { // carries one responsibility. The dispatcher (createFlagsCommand action) is ~15 // lines and routes without logic of its own (ARCH-M1, CPLX-H1). -/** Handle --list: read-only registry dump, no manifest required. */ -async function handleList(): Promise { +/** Handle --list: read only the registry and user settings env. */ +async function handleList(claudeDir: string): Promise { p.intro(color.bgCyan(color.black(' Claude Code Flags '))); for (const flag of FLAG_REGISTRY) { const kindLabel = describeFlagKind(flag); @@ -278,13 +330,25 @@ async function handleList(): Promise { ` ${color.dim(flag.hint)} — default: ${color.cyan(defaultLabel)}`, ); } + const signals = await readCodeModeSignals(claudeDir, null); + if (signals.ok && signals.value.env !== undefined) { + for (const line of codeModeBlockers(blockerState(signals.value))) p.log.warn(line); + } p.outro(color.dim('Use --enable / --disable / --set / --unset to manage flags')); } +async function statusCodeModeLines(claudeDir: string, devflowDir: string): Promise { + const signals = await readCodeModeSignals(claudeDir, devflowDir); + return signals.ok ? [ + ...codeModeBlockers(blockerState(signals.value)), + ...codeModeStatusNotes(signals.value), + ] : []; +} + /** Handle --status: read-only status table, degrades gracefully without a manifest. */ -async function handleStatus(devflowDir: string): Promise { +async function handleStatus(claudeDir: string, devflowDir: string): Promise { p.intro(color.bgCyan(color.black(' Claude Code Flags — Status '))); - const manifest = await readManifest(devflowDir); + const manifest = await readManifest(devflowDir, { heal: false }); if (!manifest) { p.log.warn('Devflow is not installed — run devflow init first'); p.log.info('Showing registry defaults only:'); @@ -293,6 +357,7 @@ async function handleStatus(devflowDir: string): Promise { for (const row of formatStatusRows(record)) { p.log.info(row); } + for (const line of await statusCodeModeLines(claudeDir, devflowDir)) p.log.warn(line); p.outro(color.dim('Use --enable / --disable / --set / --unset to change flags')); } @@ -331,6 +396,9 @@ async function handleSetBooleans( flagDefs.push(flag); } + const check = await checkCodeModeWrite(claudeDir, devflowDir, value && ids.includes('code-mode')); + if (!check.ok) return; + // Manifest required for mutating ops (avoids settings/manifest desync) const ctx = await loadFlagContext(claudeDir, devflowDir); if (!ctx.ok) { @@ -345,13 +413,13 @@ async function handleSetBooleans( newRecord[flag.id] = value; } - const result = await persistFlagConfig(claudeDir, devflowDir, ctx.value.settingsContent, newRecord, ctx.value.manifest); + const result = await persistFlagConfig(claudeDir, devflowDir, ctx.value.settingsContent, newRecord, ctx.value.manifest, check.value); if (result.ok) { for (const flag of flagDefs) { // D-EFFDV: formatFlagValue routes through effectiveDisplay — one vocabulary // shared with --status and TUI so the three surfaces cannot drift. - p.log.success(`${flag.id} ${formatFlagValue(flag, value)}`); + logFlagSuccess(flag.id, `${flag.id} ${formatFlagValue(flag, value)}`); } } } @@ -364,6 +432,7 @@ async function handleSet( ): Promise { // Phase: parse and validate ALL assignments before any mutation. const assignments: Array<{ id: string; flag: ClaudeCodeFlag; value: FlagsRecordValue }> = []; + let requestedOn = false; for (const assignment of setValues) { // Split on first = only — rest is the value (e.g. spellcheck=a=b → id='spellcheck', value='a=b') @@ -402,8 +471,13 @@ async function handleSet( } assignments.push({ id, flag, value }); + // The last assignment wins in both preflight and the record. + if (id === 'code-mode') requestedOn = value === true; } + const check = await checkCodeModeWrite(claudeDir, devflowDir, requestedOn); + if (!check.ok) return; + // All assignments valid — load manifest + settings const ctx = await loadFlagContext(claudeDir, devflowDir); if (!ctx.ok) { @@ -424,7 +498,7 @@ async function handleSet( const viewModeExplicit = assignments.some(a => a.id === 'view-mode'); const result = await persistFlagConfig( claudeDir, devflowDir, ctx.value.settingsContent, newRecord, ctx.value.manifest, - { viewModeExplicit }, + { ...check.value, viewModeExplicit }, ); if (result.ok) { @@ -432,7 +506,7 @@ async function handleSet( // null means the user typed 'unset' explicitly — echo their word back. // For active values, route through formatFlagValue (D-EFFDV vocabulary). const displayText = value === null ? 'unset' : formatFlagValue(flag, value); - p.log.success(`${id} = ${displayText}`); + logFlagSuccess(id, `${id} = ${displayText}`); } } } @@ -473,14 +547,16 @@ async function handleUnset( // viewModeExplicit: true when the user explicitly unset view-mode. const viewModeExplicit = ids.includes('view-mode'); + const check = await checkCodeModeWrite(claudeDir, devflowDir, false); + if (!check.ok) return; const result = await persistFlagConfig( claudeDir, devflowDir, ctx.value.settingsContent, newRecord, ctx.value.manifest, - { viewModeExplicit }, + { ...check.value, viewModeExplicit }, ); if (result.ok) { for (const id of ids) { - p.log.success(`${id} unset`); + logFlagSuccess(id, `${id} unset`); } } } @@ -499,9 +575,8 @@ async function handleUnset( * @param manifest Loaded manifest threaded from loadFlagContext before TUI launch. * @param claudeDir Path to ~/.claude directory (for settings.json write). * @param devflowDir Path to ~/.devflow directory (for manifest write). - * @returns 'saved' on successful persist, 'unchanged' for cancel/abort, - * or the PersistResult error discriminant when persist fails - * (persistFlagConfig already logged + set exitCode in that case). + * @returns 'saved' on success, 'unchanged' for cancel/abort, 'refused' on preflight failure, + * or the PersistResult error discriminant when persist fails. Errors are already logged. */ export async function applyTuiResult( result: FlagsTuiResult, @@ -509,7 +584,7 @@ export async function applyTuiResult( manifest: NonNullable>>, claudeDir: string, devflowDir: string, -): Promise<'saved' | 'unchanged' | Extract> { +): Promise<'saved' | 'unchanged' | 'refused' | Extract> { if (result.action !== 'save') { return 'unchanged'; } @@ -519,11 +594,18 @@ export async function applyTuiResult( // viewModeExplicit: true if the user changed the view-mode row in the TUI const viewModeExplicit = newRecord['view-mode'] !== existingRecord['view-mode']; + const codeModeRow = result.rows.find(row => row.id === 'code-mode'); + const check = await checkCodeModeWrite(claudeDir, devflowDir, codeModeRow?.configuredValue === true); + if (!check.ok) return 'refused'; + const persistResult = await persistFlagConfig( claudeDir, devflowDir, freshSettingsContent, newRecord, manifest, - { viewModeExplicit }, + { ...check.value, viewModeExplicit }, ); if (persistResult.ok) { + if (codeModeRow && codeModeRow.configuredValue !== codeModeRow.originalValue) { + logFlagSuccess(codeModeRow.id, `${codeModeRow.id} ${formatFlagValue(codeModeRow.def, codeModeRow.configuredValue)}`); + } return 'saved'; } return persistResult; @@ -569,12 +651,8 @@ async function handleBare( // ── Build initial rows from registry + current record ────────────── // buildFlagRows is a static import (pure — no TTY); only runFlagsTui is lazy. - // D-ADOPT-RESPECTS-USER: a guarded setting flag the manifest has not recorded yet - // (an upgrade before the first init) would show its registry default, and a Save - // would write the managed payload over a value the user owns. The same rule init - // applies decides the starting row: respectUserOwnedSettings (the one authority, - // built on settingHoldsUserValue) flips such a flag to OFF. The settings snapshot - // is read here and passed in, so the reducer and renderer stay pure. + // Use the same settings fold as init. It preserves user-owned values and + // adopts an unclaimed exact payload before the editor builds its rows. const initialRows = buildFlagRows( respectUserOwnedSettings(record, record, ctx.value.settingsContent), ); @@ -611,17 +689,18 @@ async function handleBare( if (outcome === 'saved') { p.outro(color.green('Flags saved.')); } - // Error outcomes: persistFlagConfig already logged and set exitCode. + // A refusal or persist error is already logged with exitCode set. } else { p.outro(color.dim('No changes made.')); } } else { // non-TTY: status table — degrades gracefully without manifest (read-only). - const manifest = await readManifest(devflowDir); + const manifest = await readManifest(devflowDir, { heal: false }); const record: FlagsRecord = manifest?.features.flags ?? {}; for (const row of formatStatusRows(record)) { process.stdout.write(`${row}\n`); } + for (const line of await statusCodeModeLines(claudeDir, devflowDir)) process.stdout.write(`${line}\n`); process.stderr.write('Note: interactive TUI requires a TTY. Use --enable/--disable/--set/--unset for mutations.\n'); process.exitCode = 1; } @@ -671,8 +750,8 @@ export function createFlagsCommand(): Command { const devflowDir = getDevFlowDirectory(); const splitIds = (s: string): string[] => s.split(',').map(t => t.trim()).filter(Boolean); - if (options.list) return handleList(); - if (options.status) return handleStatus(devflowDir); + if (options.list) return handleList(claudeDir); + if (options.status) return handleStatus(claudeDir, devflowDir); if (options.enable !== undefined) return handleSetBooleans(claudeDir, devflowDir, splitIds(options.enable), true); if (options.disable !== undefined) return handleSetBooleans(claudeDir, devflowDir, splitIds(options.disable), false); if (options.set && options.set.length > 0) return handleSet(claudeDir, devflowDir, options.set); diff --git a/src/core/code-mode.ts b/src/core/code-mode.ts index e3564a7b6..2934e3a75 100644 --- a/src/core/code-mode.ts +++ b/src/core/code-mode.ts @@ -73,10 +73,19 @@ export function codeModeBlockers({ codeModeOn, proxyOn, trafficOn }: CodeModeBlo } /** Warn once per blocker in the final state, even if the write did not add it. */ -export function writeTimeWarnings(_before: CodeModeBlockerState, after: CodeModeBlockerState): string[] { +export function writeTimeWarnings(_before: CodeModeBlockerState | undefined, after: CodeModeBlockerState): string[] { return codeModeBlockers(after); } +export function codeModeStatusNotes({ record, env }: CodeModeSignals): string[] { + if (!codeModeFlag || !isEnvBooleanFlag(codeModeFlag)) return []; + if (holdsUserEnvValue(codeModeFlag, env)) return [CODE_MODE_USER_VALUE_NOTE]; + if (record?.['code-mode'] === false && holdsOwnEnvPayload(codeModeFlag, env)) { + return [CODE_MODE_RECORD_FALSE_NOTE]; + } + return []; +} + export function initCodeModeWarnings({ proxyEnabled, record, env }: { readonly proxyEnabled: boolean; readonly record: RawRecord | null; diff --git a/src/core/manifest.ts b/src/core/manifest.ts index cc8b6cf7c..e98a5032f 100644 --- a/src/core/manifest.ts +++ b/src/core/manifest.ts @@ -255,10 +255,11 @@ export function hasRequiredManifestFields(data: Record): boolea * write, because the next read heals. Under the lock it reads the file again and * writes only when those bytes are the bytes it parsed, so a toggle that landed after * the parse is never written over with the older snapshot. + * Pass `heal: false` to normalize in memory without a write. */ export async function readManifest( devflowDir: string, - opts?: { readonly onWarning?: (message: string) => void }, + opts?: { readonly onWarning?: (message: string) => void; readonly heal?: boolean }, ): Promise { const manifestPath = path.join(devflowDir, 'manifest.json'); try { @@ -381,7 +382,7 @@ export async function readManifest( ...(Object.hasOwn(data, 'installedVariants') ? { installedVariants: data.installedVariants } : {}), }; - if (needsHeal) { + if (needsHeal && opts?.heal !== false) { // D39: wrap the heal-write in its own try/catch so a write failure does NOT // propagate to the caller. The migrated in-memory manifest is returned even // when the on-disk heal fails. The next read will retry the heal. diff --git a/tests/flags-cli.test.ts b/tests/flags-cli.test.ts index e187c044d..e43e60ee9 100644 --- a/tests/flags-cli.test.ts +++ b/tests/flags-cli.test.ts @@ -53,6 +53,7 @@ import { createFlagsCommand, applyTuiResult } from '../src/cli/commands/flags.js import { makeManifest } from './helpers.js'; import type { FlagsRecord } from '../src/core/flags.js'; import { readManifest } from '../src/core/manifest.js'; +import * as codeMode from '../src/core/code-mode.js'; // Direct import from terminal.js (not index.js) so the REL-M3 mock of index.js // does not affect the seam test's runFlagsTui reference. import { runFlagsTui } from '../src/cli/flags-view/terminal.js'; @@ -132,6 +133,290 @@ describe('flags CLI — createFlagsCommand factory', () => { await fs.rm(tmpHome, { recursive: true, force: true }); }); + describe('Code Mode', () => { + const codeKey = 'CLAUDE_CODE_EXPERIMENTAL_CODE_MODE'; + const trafficKey = 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'; + const relayUrl = 'http://127.0.0.1:4141'; + const otherRelayUrl = 'http://127.0.0.1:4142'; + const foreignUrl = 'https://gateway.example.test'; + const fixtureAuth = 'fixture-auth-value'; + const fixtureHelper = 'fixture-helper-command'; + + async function seed(flags: FlagsRecord, env: Record, proxy = false) { + const base = makeManifest(); + const manifest = { ...base, features: { ...base.features, flags, proxy } }; + // Use the legacy layout so an accidental call to the heal-write path changes bytes. + const manifestPath = path.join(tmpDevflowDir, 'manifest.json'); + const settingsPath = path.join(tmpClaudeDir, 'settings.json'); + const manifestBytes = JSON.stringify(manifest); + const settingsBytes = JSON.stringify({ env: { ANTHROPIC_AUTH_TOKEN: fixtureAuth, ...env }, apiKeyHelper: fixtureHelper }); + await fs.writeFile(manifestPath, manifestBytes); + await fs.writeFile(settingsPath, settingsBytes); + return { manifestPath, settingsPath, manifestBytes, settingsBytes }; + } + + async function seedProxy(contents = '{"enabled":true}') { + await fs.writeFile(path.join(tmpDevflowDir, 'proxy.json'), contents); + } + + async function expectUnchanged(files: Awaited>) { + expect(await fs.readFile(files.manifestPath, 'utf-8')).toBe(files.manifestBytes); + expect(await fs.readFile(files.settingsPath, 'utf-8')).toBe(files.settingsBytes); + } + + async function expectSaved(value: boolean, payload: string | undefined) { + const manifest = await fs.readFile(path.join(tmpDevflowDir, 'manifest.json'), 'utf-8'); + const { env } = parseSettings(await fs.readFile(path.join(tmpClaudeDir, 'settings.json'), 'utf-8')); + expect(parseFlagsRecord(manifest)['code-mode']).toBe(value); + expect((env as Record | undefined)?.[codeKey]).toBe(payload); + expect(process.exitCode).toBe(0); + } + + async function runTui(changes: FlagsRecord) { + const streams = [process.stdin, process.stdout]; + const tty = streams.map(stream => stream.isTTY); + streams.forEach(stream => Object.defineProperty(stream, 'isTTY', { value: true, configurable: true })); + vi.doMock('../src/cli/flags-view/index.js', () => ({ + runFlagsTui: async (rows: ReturnType) => ({ + action: 'save', + rows: rows.map(row => Object.hasOwn(changes, row.id) + ? { ...row, configuredValue: changes[row.id] } + : row), + }), + })); + vi.resetModules(); + try { + const { createFlagsCommand } = await import('../src/cli/commands/flags.js'); + await createFlagsCommand().parseAsync([], { from: 'user' }); + } finally { + streams.forEach((stream, i) => Object.defineProperty(stream, 'isTTY', { value: tty[i], configurable: true })); + vi.doUnmock('../src/cli/flags-view/index.js'); + vi.resetModules(); + } + } + + function expectRefusal(message = codeMode.CODE_MODE_ENABLE_REFUSAL) { + expect(process.exitCode).toBe(1); + expect(vi.mocked(p.log.error).mock.calls).toEqual([[message]]); + expect(p.log.success).not.toHaveBeenCalled(); + expect(p.outro).not.toHaveBeenCalled(); + } + + beforeEach(() => vi.clearAllMocks()); + + it.each([ + ['--enable', 'code-mode'], + ['--enable', 'lsp,code-mode'], + ['--set', 'lsp=true', '--set', 'code-mode=true'], + ].map(args => ({ args })))('refuses $args as a whole before any file changes', async ({ args }) => { + const files = await seed({}, {}); + await seedProxy(); + + await flagsCmd.parseAsync(args, { from: 'user' }); + + expectRefusal(); + await expectUnchanged(files); + }); + + it.each([ + { name: 'manifest', manifestProxy: true }, + { name: 'corrupt state file', proxyJson: '{' }, + { name: 'managed relay URL', url: relayUrl }, + { name: 'relay URL on another port', url: otherRelayUrl }, + ])('refuses enable on the $name signal alone', async ({ manifestProxy, proxyJson, url }) => { + const files = await seed({}, url ? { ANTHROPIC_BASE_URL: url } : {}, manifestProxy); + if (proxyJson) await seedProxy(proxyJson); + + await flagsCmd.parseAsync(['--enable', 'code-mode'], { from: 'user' }); + + expectRefusal(); + await expectUnchanged(files); + }); + + it('refuses a TUI save before it can heal a legacy manifest', async () => { + const files = await seed({ 'code-mode': false }, {}); + await seedProxy(); + + await runTui({ 'code-mode': true }); + + expectRefusal(); + await expectUnchanged(files); + }); + + it('refuses enable when a user value makes the recorded on state off', async () => { + const files = await seed({ 'code-mode': true }, { [codeKey]: '0' }); + await seedProxy(); + + await flagsCmd.parseAsync(['--enable', 'code-mode'], { from: 'user' }); + + expectRefusal(); + await expectUnchanged(files); + }); + + it('refuses enable when the signal reader fails', async () => { + const files = await seed({}, {}); + const reader = vi.spyOn(codeMode, 'readCodeModeSignals').mockResolvedValue({ ok: false, error: fixtureAuth }); + try { + await flagsCmd.parseAsync(['--enable', 'code-mode'], { from: 'user' }); + } finally { + reader.mockRestore(); + } + + expectRefusal(codeMode.CODE_MODE_READ_FAILURE); + await expectUnchanged(files); + }); + + it.each([ + { args: ['--disable', 'code-mode'] }, + { args: ['--unset', 'code-mode'] }, + { args: ['--set', 'code-mode=false'] }, + { args: ['--set', 'code-mode=unset'] }, + { args: ['--set', 'code-mode=true', '--set', 'code-mode=false'], initiallyOn: false }, + ])('allows $args while the proxy is on', async ({ args, initiallyOn = true }) => { + await seed({ 'code-mode': initiallyOn }, initiallyOn ? { [codeKey]: '1' } : {}); + await seedProxy(); + + await flagsCmd.parseAsync(args, { from: 'user' }); + + await expectSaved(false, undefined); + expect(p.log.warn).not.toHaveBeenCalled(); + }); + + it.each([ + { name: '--disable', args: ['--disable', 'code-mode'] }, + { name: 'an unrelated CLI write', args: ['--enable', 'lsp'] }, + { name: 'an unrelated TUI save', args: [] }, + ])('keeps a user value and records off on $name', async ({ args }) => { + await seed({ 'code-mode': true }, { [codeKey]: '0' }); + await seedProxy(); + + if (args.length > 0) await flagsCmd.parseAsync(args, { from: 'user' }); + else await runTui({ lsp: true }); + + await expectSaved(false, '0'); + expect(p.log.warn).not.toHaveBeenCalled(); + }); + + it.each([ + { name: '--enable', args: ['--enable', 'code-mode'] }, + { name: '--set', args: ['--set', 'code-mode=true'] }, + { name: 'TUI save', args: [] }, + ])('replaces a user value on explicit enable via $name when the proxy is off', async ({ args }) => { + const files = await seed({ 'code-mode': true }, { [codeKey]: '0', ANTHROPIC_BASE_URL: foreignUrl }); + + if (args.length > 0) await flagsCmd.parseAsync(args, { from: 'user' }); + else await runTui({ 'code-mode': true }); + + await expectSaved(true, '1'); + const { env, apiKeyHelper } = parseSettings(await fs.readFile(files.settingsPath, 'utf-8')); + expect(env).toMatchObject({ ANTHROPIC_BASE_URL: foreignUrl, ANTHROPIC_AUTH_TOKEN: fixtureAuth }); + expect(apiKeyHelper).toBe(fixtureHelper); + expect(vi.mocked(p.log.success).mock.calls.flat().join('\n')).toContain(codeMode.CODE_MODE_NEW_SESSIONS_SUFFIX); + }); + + it('keeps a hand-set on value on an unrelated TUI save', async () => { + await seed({}, { [codeKey]: '1' }); + + await runTui({ lsp: true }); + + await expectSaved(true, '1'); + }); + + it('allows an unrelated TUI save when Code Mode and the proxy are already on', async () => { + await seed({ 'code-mode': true }, { [codeKey]: '1' }); + await seedProxy(); + + await runTui({ lsp: true }); + + await expectSaved(true, '1'); + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[codeMode.CODE_MODE_PROXY_BLOCKER]]); + }); + + it.each([ + { id: 'code-mode', flags: { 'disable-nonessential-traffic': true } }, + { id: 'disable-nonessential-traffic', flags: { 'code-mode': true } }, + ])('warns once when a successful enable of $id leaves both flags on', async ({ id, flags }) => { + await seed(flags, {}); + + await flagsCmd.parseAsync(['--enable', id], { from: 'user' }); + + await expectSaved(true, '1'); + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[codeMode.CODE_MODE_TRAFFIC_BLOCKER]]); + }); + + it('warns on --unset of an unrelated flag when the proxy and Code Mode stay on', async () => { + await seed({ 'code-mode': true, lsp: true }, { [codeKey]: '1', ANTHROPIC_BASE_URL: relayUrl }); + + await flagsCmd.parseAsync(['--unset', 'lsp'], { from: 'user' }); + + await expectSaved(true, '1'); + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[codeMode.CODE_MODE_PROXY_BLOCKER]]); + }); + + it('lists settings-only blockers without a manifest or any file changes', async () => { + const settingsPath = path.join(tmpClaudeDir, 'settings.json'); + const settings = JSON.stringify({ env: { [codeKey]: '1', [trafficKey]: '1', ANTHROPIC_BASE_URL: relayUrl } }); + await fs.writeFile(settingsPath, settings); + + await flagsCmd.parseAsync(['--list'], { from: 'user' }); + + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[codeMode.CODE_MODE_PROXY_BLOCKER], [codeMode.CODE_MODE_TRAFFIC_BLOCKER]]); + expect(process.exitCode).toBe(0); + expect(await fs.readdir(tmpDevflowDir)).toEqual([]); + expect(await fs.readFile(settingsPath, 'utf-8')).toBe(settings); + }); + + it('does not use machine signals when it lists flags', async () => { + const files = await seed({ 'code-mode': true, 'disable-nonessential-traffic': true }, { [codeKey]: '1' }, true); + await seedProxy(); + + await flagsCmd.parseAsync(['--list'], { from: 'user' }); + + expect(p.log.warn).not.toHaveBeenCalled(); + await expectUnchanged(files); + }); + + it.each([ + { name: 'a hand-set on value', flags: { 'code-mode': false }, payload: '1', + lines: [codeMode.CODE_MODE_PROXY_BLOCKER, codeMode.CODE_MODE_TRAFFIC_BLOCKER, codeMode.CODE_MODE_RECORD_FALSE_NOTE] }, + { name: 'a user override', flags: { 'code-mode': true }, payload: '0', + lines: [codeMode.CODE_MODE_USER_VALUE_NOTE] }, + ])('reports $name with fixed status lines and does not heal files', async ({ flags, payload, lines }) => { + const files = await seed(flags, { [codeKey]: payload, [trafficKey]: '1', ANTHROPIC_BASE_URL: relayUrl }); + + await flagsCmd.parseAsync(['--status'], { from: 'user' }); + + const reported = [...vi.mocked(p.log.warn).mock.calls, ...vi.mocked(p.log.info).mock.calls].flat().join('\n'); + for (const line of lines) expect(reported).toContain(line); + if (payload === '0') { + expect(reported).not.toContain(codeMode.CODE_MODE_PROXY_BLOCKER); + expect(reported).not.toContain(codeMode.CODE_MODE_TRAFFIC_BLOCKER); + } + for (const fixture of [relayUrl, fixtureAuth, fixtureHelper]) expect(reported).not.toContain(fixture); + expect(process.exitCode).toBe(0); + await expectUnchanged(files); + }); + + it('prints blockers after the bare non-TTY table and keeps its exit code', async () => { + const files = await seed({ 'code-mode': true, 'disable-nonessential-traffic': true }, { ANTHROPIC_BASE_URL: relayUrl }); + const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); + const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true); + let output: string; + try { + await flagsCmd.parseAsync([], { from: 'user' }); + output = stdout.mock.calls.map(([line]) => String(line)).join(''); + } finally { + stdout.mockRestore(); + stderr.mockRestore(); + } + + expect(output).toMatch(/code-mode\s+on/); + expect(output).toContain(`${codeMode.CODE_MODE_PROXY_BLOCKER}\n${codeMode.CODE_MODE_TRAFFIC_BLOCKER}\n`); + expect(process.exitCode).toBe(1); + await expectUnchanged(files); + }); + }); + // ─── --list ─────────────────────────────────────────────────────────────────── describe('--list', () => { diff --git a/tests/write-set-fence.test.ts b/tests/write-set-fence.test.ts index 9dd30f4c8..c848a452b 100644 --- a/tests/write-set-fence.test.ts +++ b/tests/write-set-fence.test.ts @@ -329,6 +329,21 @@ export const FENCE_ROWS: readonly FenceRow[] = [ { args: ['flags', '--unset', 'max-concurrent-subagents'], allow: [SETTINGS, MANIFEST], mustWrite: true }, { args: ['flags', '--status'], allow: NONE, mustWrite: false }, { args: ['flags', '--list'], allow: NONE, mustWrite: false }, + { + args: ['flags', '--enable', 'code-mode'], allow: NONE, mustWrite: false, exitCode: 1, + seed: sb => writeFileSync(path.join(sb.home, '.devflow', 'proxy.json'), '{"enabled":true}\n'), + }, + { + args: ['flags', '--disable', 'code-mode'], allow: [SETTINGS, MANIFEST], mustWrite: true, + seed: sb => { + rewriteHomeJson(sb, '.claude/settings.json', settings => { + (settings.env as Record).CLAUDE_CODE_EXPERIMENTAL_CODE_MODE = '1' + }) + rewriteHomeJson(sb, '.devflow/manifest.json', manifest => { + ((manifest.features as Record).flags as Record)['code-mode'] = true + }) + }, + }, { args: ['debug', '--enable'], allow: [SETTINGS], mustWrite: true }, { args: ['debug', '--disable'], allow: [SETTINGS], mustWrite: true }, From 954174125e9bbb92c86541f30231e7a68c3ce107 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 00:43:40 +0200 Subject: [PATCH 04/20] feat(proxy): guard enable with Code Mode on Refuse proxy enable before it writes or starts the relay when Code Mode is on. Show the shared blocker warnings in proxy status without writes. Refs #792 Task: feat/code-mode-direct --- src/cli/commands/proxy.ts | 43 ++++++- tests/proxy-code-mode.test.ts | 203 ++++++++++++++++++++++++++++++++++ tests/write-set-fence.test.ts | 13 ++- 3 files changed, 253 insertions(+), 6 deletions(-) create mode 100644 tests/proxy-code-mode.test.ts diff --git a/src/cli/commands/proxy.ts b/src/cli/commands/proxy.ts index 621419d26..f169ef8d4 100644 --- a/src/cli/commands/proxy.ts +++ b/src/cli/commands/proxy.ts @@ -29,11 +29,21 @@ import { buildProxyState, buildRoutingConfigJson, proxyBaseUrl, + classifyProxyBaseUrl, readProxyEnvState, proxyJsonExists, resolveProxyBin, DEFAULT_PROXY_PORT, } from '../../core/proxy-state.js'; +import { + CODE_MODE_READ_FAILURE, + PROXY_ENABLE_REFUSAL, + codeModeBlockers, + isCodeModeOn, + isProxyOn, + isTrafficOn, + readCodeModeSignals, +} from '../../core/code-mode.js'; import { syncManifestFeature, readManifest } from '../../core/manifest.js'; import { writeSettingsFileAtomic } from '../../core/fs-atomic.js'; import { scrubChildEnv, openProxyLog, rotateProxyLogIfLarge } from '../../core/proxy-log.js'; @@ -1380,6 +1390,10 @@ export const proxyCommand = new Command('proxy') // ─── Status ─────────────────────────────────────────────────────────────────── +function isSettingsRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + async function runStatus(): Promise { const devflowDir = getDevFlowDirectory(); const claudeDir = getClaudeDirectory(); @@ -1392,7 +1406,7 @@ async function runStatus(): Promise { p.intro(color.bgBlue(color.white(' Devflow Proxy Status '))); // Feature state: manifest + proxy.json - const manifest = await readManifest(devflowDir); + const manifest = await readManifest(devflowDir, { heal: false }); const proxyStateResult = await readProxyState(devflowDir); const proxyState = proxyStateResult.ok ? proxyStateResult.value : null; @@ -1443,12 +1457,14 @@ async function runStatus(): Promise { } // Env state - let envState: 'ours' | 'ours-other-port' | 'foreign' | 'absent' = 'absent'; + let env: Record | undefined; try { const settingsJson = await fs.readFile(settingsPath, 'utf-8'); - envState = readProxyEnvState(settingsJson, port); - } catch { /* settings missing */ } + const settings: unknown = JSON.parse(settingsJson); + if (isSettingsRecord(settings) && isSettingsRecord(settings.env)) env = settings.env; + } catch { /* settings unavailable */ } + const envState = classifyProxyBaseUrl(env?.ANTHROPIC_BASE_URL, port); const envStateLabels: Record = { 'ours': color.green('set (our relay)'), 'ours-other-port': color.yellow('set (our relay, different port)'), @@ -1457,6 +1473,13 @@ async function runStatus(): Promise { }; p.log.info(`ANTHROPIC_BASE_URL: ${envStateLabels[envState]}`); + const record = manifest?.features.flags ?? null; + for (const line of codeModeBlockers({ + codeModeOn: isCodeModeOn(record, env), + proxyOn: isProxyOn({ proxyJsonOn: !proxyStateResult.ok || stateEnabled, manifestProxy: manifestEnabled, urlState: envState }), + trafficOn: isTrafficOn(record, env), + })) p.log.warn(line); + // Codex auth — inspect contents, not just existence. A file the relay would // reject (bad JSON, no account id) 401s every request while an existence check // still reports "present"; that gap is what this check closes. @@ -1533,6 +1556,18 @@ async function runEnable(portOption: string | undefined): Promise { } const port = portResult.value; + const signals = await readCodeModeSignals(claudeDir, devflowDir); + if (!signals.ok || signals.value.env === undefined) { + p.log.error(CODE_MODE_READ_FAILURE); + process.exitCode = 1; + return; + } + if (isCodeModeOn(signals.value.record, signals.value.env)) { + p.log.error(PROXY_ENABLE_REFUSAL); + process.exitCode = 1; + return; + } + const s = p.spinner(); s.start('Running preflight checks...'); diff --git a/tests/proxy-code-mode.test.ts b/tests/proxy-code-mode.test.ts new file mode 100644 index 000000000..aa2eef9a0 --- /dev/null +++ b/tests/proxy-code-mode.test.ts @@ -0,0 +1,203 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import * as p from '@clack/prompts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + CODE_MODE_PROXY_BLOCKER, + CODE_MODE_READ_FAILURE, + CODE_MODE_TRAFFIC_BLOCKER, + PROXY_ENABLE_REFUSAL, +} from '../src/core/code-mode.js'; +import type { FlagsRecord } from '../src/core/flags.js'; +import { makeManifest } from './helpers.js'; +import { excludeGit, readTree } from './install-snapshot-helpers.js'; + +const { binUnavailable, resolveBin } = vi.hoisted(() => { + const binUnavailable = 'Fixture: routing executable unavailable'; + return { binUnavailable, resolveBin: vi.fn(async () => ({ ok: false, error: binUnavailable })) }; +}); + +vi.mock('../src/core/proxy-state.js', async (importOriginal) => ({ + ...await importOriginal(), + resolveProxyBin: resolveBin, +})); + +vi.mock('net', async (importOriginal) => { + const net = await importOriginal(); + return { + ...net, + createConnection: () => { + const socket = new net.Socket(); + queueMicrotask(() => socket.destroy(new Error('Fixture: port closed'))); + return socket; + }, + }; +}); + +vi.mock('@clack/prompts', () => ({ + intro: vi.fn(), + note: vi.fn(), + log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() }, + spinner: vi.fn(() => ({ start: vi.fn(), stop: vi.fn(), message: vi.fn() })), +})); + +const codeKey = 'CLAUDE_CODE_EXPERIMENTAL_CODE_MODE'; +const trafficKey = 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'; +const codeOn = { 'code-mode': true }; +const fixtureUrl = 'https://gateway.example.test'; +const fixtureAuth = 'fixture-auth-value'; +const fixtureHelper = 'fixture-helper-command'; + +let home: string; +let previousExitCode: typeof process.exitCode; + +beforeEach(() => { + vi.resetModules(); + vi.clearAllMocks(); + home = mkdtempSync(join(tmpdir(), 'proxy-code-mode-')); + vi.stubEnv('HOME', home); + vi.stubEnv('CLAUDE_CONFIG_DIR', join(home, '.claude')); + previousExitCode = process.exitCode; + process.exitCode = 0; +}); + +afterEach(() => { + vi.doUnmock('../src/core/code-mode.js'); + vi.unstubAllEnvs(); + process.exitCode = previousExitCode; + rmSync(home, { recursive: true, force: true }); +}); + +function seedFile(relative: string, contents: string) { + const file = join(home, relative); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, contents); +} + +function seedManifest(flags: FlagsRecord, proxy = false) { + // The legacy fixture exposes any accidental manifest heal write. + const base = makeManifest(); + seedFile('.devflow/manifest.json', JSON.stringify({ ...base, features: { ...base.features, flags, proxy } })); +} + +function seedSettings(env: Record) { + seedFile('.claude/settings.json', JSON.stringify({ + env: { ANTHROPIC_BASE_URL: fixtureUrl, ANTHROPIC_AUTH_TOKEN: fixtureAuth, ...env }, + apiKeyHelper: fixtureHelper, + })); +} + +async function run(...args: string[]) { + const { proxyCommand } = await import('../src/cli/commands/proxy.js'); + await proxyCommand.parseAsync(args, { from: 'user' }); +} + +function snapshot() { + return readTree(home, excludeGit, true); +} + +async function expectRefusal(message = PROXY_ENABLE_REFUSAL) { + const before = snapshot(); + await run('--enable'); + expect(vi.mocked(p.log.error).mock.calls).toEqual([[message]]); + expect(process.exitCode).toBe(1); + expect(p.spinner).not.toHaveBeenCalled(); + expect(resolveBin).not.toHaveBeenCalled(); + expect(snapshot()).toEqual(before); +} + +describe('proxy --enable with Code Mode', () => { + it('refuses a recorded enable before writes or the spinner', async () => { + seedManifest(codeOn); + seedSettings({}); + await expectRefusal(); + }); + + it('refuses a hand-set enable without a manifest', async () => { + seedSettings({ [codeKey]: '1' }); + await expectRefusal(); + }); + + it('refuses drift repair when proxy.json is on and the manifest proxy is off', async () => { + seedManifest(codeOn); + seedFile('.devflow/proxy.json', '{"enabled":true}'); + await expectRefusal(); + }); + + it('refuses a hand-set enable if the manifest is corrupt', async () => { + seedFile('.devflow/manifest.json', '{'); + seedSettings({ [codeKey]: '1' }); + await expectRefusal(); + }); + + it.each([false, true])('continues to proxy preflight with a user "0" (record on: %s)', async (recorded) => { + if (recorded) seedManifest(codeOn); + seedSettings({ [codeKey]: '0' }); + await run('--enable'); + expect(vi.mocked(p.log.error).mock.calls).toEqual([[binUnavailable]]); + expect(resolveBin).toHaveBeenCalledOnce(); + }); + + it('refuses without side effects if the signal reader fails', async () => { + vi.doMock('../src/core/code-mode.js', async (importOriginal) => ({ + ...await importOriginal(), + readCodeModeSignals: async () => ({ ok: false, error: CODE_MODE_READ_FAILURE }), + })); + await expectRefusal(CODE_MODE_READ_FAILURE); + }); + + it('refuses without side effects if settings cannot be parsed', async () => { + seedFile('.claude/settings.json', '{'); + await expectRefusal(CODE_MODE_READ_FAILURE); + }); +}); + +describe('proxy --status Code Mode warnings', () => { + it('warns once per blocker after the env line, without writes or settings values in output', async () => { + seedManifest(codeOn, true); + seedFile('.devflow/proxy.json', '{"enabled":true}'); + seedSettings({ [trafficKey]: '1' }); + const before = snapshot(); + + await run('--status'); + + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[CODE_MODE_PROXY_BLOCKER], [CODE_MODE_TRAFFIC_BLOCKER]]); + const info = vi.mocked(p.log.info).mock; + const envLine = info.calls.findIndex(([line]) => line.startsWith('ANTHROPIC_BASE_URL:')); + expect(vi.mocked(p.log.warn).mock.invocationCallOrder[0]).toBeGreaterThan(info.invocationCallOrder[envLine] ?? Infinity); + const output = [p.log.info, p.log.error, p.log.warn, p.note].flatMap(fn => vi.mocked(fn).mock.calls).flat().join('\n'); + for (const value of [fixtureUrl, fixtureAuth, fixtureHelper]) expect(output).not.toContain(value); + expect(process.exitCode).toBe(0); + expect(snapshot()).toEqual(before); + }); + + it('uses a relay URL on another port as a proxy signal', async () => { + seedSettings({ [codeKey]: '1', ANTHROPIC_BASE_URL: 'http://127.0.0.1:4142' }); + await run('--status'); + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[CODE_MODE_PROXY_BLOCKER]]); + }); + + it('uses the recorded traffic flag without a proxy signal', async () => { + seedManifest({ ...codeOn, 'disable-nonessential-traffic': true }); + seedFile('.claude/settings.json', '{"env":[]}'); + await run('--status'); + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[CODE_MODE_TRAFFIC_BLOCKER]]); + }); + + it('uses unreadable proxy state as a proxy signal', async () => { + seedManifest(codeOn); + seedFile('.devflow/proxy.json', '{'); + await run('--status'); + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[CODE_MODE_PROXY_BLOCKER]]); + }); + + it('does not warn about Code Mode when a user "0" overrides it', async () => { + seedManifest(codeOn, true); + seedFile('.devflow/proxy.json', '{"enabled":true}'); + seedSettings({ [codeKey]: '0', [trafficKey]: '1' }); + await run('--status'); + expect(p.log.warn).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(0); + }); +}); diff --git a/tests/write-set-fence.test.ts b/tests/write-set-fence.test.ts index c848a452b..dfa5d8d56 100644 --- a/tests/write-set-fence.test.ts +++ b/tests/write-set-fence.test.ts @@ -333,6 +333,15 @@ export const FENCE_ROWS: readonly FenceRow[] = [ args: ['flags', '--enable', 'code-mode'], allow: NONE, mustWrite: false, exitCode: 1, seed: sb => writeFileSync(path.join(sb.home, '.devflow', 'proxy.json'), '{"enabled":true}\n'), }, + { + args: ['proxy', '--enable'], allow: NONE, mustWrite: false, exitCode: 1, + seed: sb => { + writeFileSync(path.join(sb.home, '.devflow', 'proxy.json'), '{"enabled":false}\n') + rewriteHomeJson(sb, '.devflow/manifest.json', manifest => { + ((manifest.features as Record).flags as Record)['code-mode'] = true + }) + }, + }, { args: ['flags', '--disable', 'code-mode'], allow: [SETTINGS, MANIFEST], mustWrite: true, seed: sb => { @@ -381,14 +390,14 @@ export const UNFENCED_COMMANDS: Readonly> = { uninstall: 'its keep list and removals are the install-snapshot golden\'s uninstall sections (TP-6)', } -/** Toggle actions a command defines that have no row, each with the reason. */ +/** Toggle paths without a fence row, each with the reason. */ export const UNFENCED_ACTIONS: Readonly> = { 'security --disable': 'after stripping the user settings it removes every Devflow deny entry from the platform managed-settings file ' + '(getManagedSettingsPath: /Library/Application Support/ClaudeCode or /etc/claude-code), an absolute system path ' + 'with no seam the sandbox can redirect; on a machine whose managed file carries the deny list, a run would strip ' + 'that machine\'s protection (or prompt for sudo), and the walk could not see the write anyway', - 'proxy --enable': 'starts the relay process, whose writes outlive the command', + 'proxy --enable': 'on success it starts the relay process, whose writes outlive the command; the Code Mode refusal has a row', 'proxy --disable': 'stops the relay process started by --enable', 'safe-delete --enable': 'writes the shell profile only when the platform trash tool is on PATH, a machine fact the table cannot pin', 'safe-delete --disable': 'removes what --enable wrote', From 5ea183d53987c1fcb71d6b7f97f6b14a85c47da6 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 00:55:16 +0200 Subject: [PATCH 05/20] feat(init): warn about Code Mode blockers Use the final proxy state and flag record so init does not warn about a proxy that failed preflight. Keep both settings when a conflict remains. Task: feat/code-mode-direct Refs #792 --- src/cli/commands/init.ts | 10 +++ tests/init-e2e-flags.test.ts | 122 +++++++++++++++++++++++++++++++---- 2 files changed, 120 insertions(+), 12 deletions(-) diff --git a/src/cli/commands/init.ts b/src/cli/commands/init.ts index 9b2a86a3f..b9d778be4 100644 --- a/src/cli/commands/init.ts +++ b/src/cli/commands/init.ts @@ -57,6 +57,7 @@ import { addHudStatusLine, removeHudStatusLine } from './hud.js'; import { loadConfig as loadHudConfig, saveConfig as saveHudConfig } from '../../hud/config.js'; import { readManifest, writeManifest, resolvePluginList, detectUpgrade, type ManifestData, type UpgradeInfo } from '../../core/manifest.js'; import { convergeFlagsIntoSettings, countActiveFlags, readViewMode, type FlagsRecord } from '../../core/flags.js'; +import { initCodeModeWarnings } from '../../core/code-mode.js'; import { addContextHook, removeContextHook, hasContextHook } from './context.js'; import { writeSettingsFileAtomic } from '../../core/fs-atomic.js'; import { writeManagedConfig, readConfigIfPresent, DEFAULT_CONFIG, type FeatureConfig, type ManagedConfigWriteError } from '../../core/feature-config.js'; @@ -987,6 +988,10 @@ async function discoverRepoRoots(claudeDir: string, homeDir: string): Promise { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + export const initCommand = new Command('init') .description('Initialize Devflow for Claude Code') .addOption(new Option('--scope ', 'Retired: Devflow installs machine-wide only').hideHelp()) @@ -2587,6 +2592,11 @@ export const initCommand = new Command('init') // Parse Settings once for the hook mutation; env mutation stays in string space. { const parsedSettings = JSON.parse(content) as Settings; + const env = isJsonObject(parsedSettings.env) ? parsedSettings.env : undefined; + /** D-CODE-MODE-INIT-WARN: Use the converged flags and the proxy state after preflight. */ + const warnings = initCodeModeWarnings({ proxyEnabled, record: enabledFlags, env }); + for (const warning of warnings) p.log.warn(warning); + removeProxyHooks(parsedSettings); if (proxyEnabled) addProxyHooks(parsedSettings, devflowDir); content = JSON.stringify(parsedSettings, null, 2) + '\n'; diff --git a/tests/init-e2e-flags.test.ts b/tests/init-e2e-flags.test.ts index ba41848b0..8a5ce0c4c 100644 --- a/tests/init-e2e-flags.test.ts +++ b/tests/init-e2e-flags.test.ts @@ -28,7 +28,11 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { promises as fs, readdirSync, readFileSync, lstatSync } from 'fs'; import * as path from 'path'; import * as os from 'os'; -import { spawnSync, execFileSync } from 'child_process'; +import { spawnSync, execFile, execFileSync } from 'child_process'; +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import { promisify } from 'node:util'; +import { CODE_MODE_PROXY_BLOCKER, CODE_MODE_TRAFFIC_BLOCKER } from '../src/core/code-mode.js'; import { type ManifestData } from '../src/core/manifest.js'; import { resolveRetiredScopeOption } from '../src/cli/commands/init.js'; import { requireBuiltCli, sandboxEnv } from './helpers.js'; @@ -37,6 +41,7 @@ import { requireBuiltCli, sandboxEnv } from './helpers.js'; const CLI_PATH = requireBuiltCli(); const SUBPROCESS_TIMEOUT_MS = 60_000; +const MINIMAL_INIT = ['init', '--recommended', '--no-ambient', '--no-memory', '--no-curation', '--no-knowledge', '--no-rules']; // ── Helpers ─────────────────────────────────────────────────────────────────── @@ -44,19 +49,12 @@ const SUBPROCESS_TIMEOUT_MS = 60_000; function runInit(tmpHome: string, extraArgs: string[] = []): { status: number | null; stdout: string; stderr: string } { const result = spawnSync( process.execPath, - [CLI_PATH, 'init', '--recommended', '--no-ambient', '--no-memory', '--no-curation', '--no-knowledge', '--no-rules', ...extraArgs], + [CLI_PATH, ...MINIMAL_INIT, ...extraArgs], { cwd: os.tmpdir(), // non-git dir → earlyGitRoot=null → no project discovery encoding: 'utf-8', timeout: SUBPROCESS_TIMEOUT_MS, - env: { - ...process.env, - HOME: tmpHome, - // Suppress memory worker spawn (no real claude binary in test env) - DEVFLOW_HOOK_DEBUG: undefined, - // Ensure non-interactive mode - FORCE_COLOR: '0', - }, + env: sandboxEnv(tmpHome), }, ); if (result.error) throw result.error; @@ -711,6 +709,108 @@ describe('init e2e — subagent-cache-5m (D-SUBAGENT-CACHE-5M, D-ADOPT-RESPECTS- }, SUBPROCESS_TIMEOUT_MS); }); +describe('init e2e — Code Mode convergence and warnings', () => { + const codeModeKey = 'CLAUDE_CODE_EXPERIMENTAL_CODE_MODE'; + const trafficOn = { 'disable-nonessential-traffic': true }; + + async function seed(value: string, flags: Record, proxy = false) { + const manifest = manifestWithFlags(flags); + await fs.writeFile(path.join(tmpHome, '.devflow', 'manifest.json'), JSON.stringify({ + ...manifest, features: { ...manifest.features, proxy }, + })); + await fs.writeFile(path.join(tmpHome, '.claude', 'settings.json'), JSON.stringify({ env: { [codeModeKey]: value } })); + } + + async function expectCodeMode(value: string, on: boolean) { + expect((await readManifest(tmpHome)).features.flags).toHaveProperty('code-mode', on); + expect((await readSettings(tmpHome)).env).toHaveProperty(codeModeKey, value); + } + + function initOutput(args: string[] = []) { + const { status, stdout, stderr } = runInit(tmpHome, args); + const output = stdout + stderr; + expect(status, output).toBe(0); + expect(output).not.toContain('Could not configure settings.json'); + return output; + } + + function expectWarningOnce(output: string, warning: string) { + expect(output.split(warning), output).toHaveLength(2); + } + + it.each([{ value: '0', on: false }, { value: '1', on: true }])( + 'keeps an unrecorded Code Mode value of $value and records the flag as $on', + async ({ value, on }) => { + await seed(value, {}); + initOutput(); + await expectCodeMode(value, on); + }, + SUBPROCESS_TIMEOUT_MS, + ); + + it('keeps a user override, records Code Mode off, and prints no blocker', async () => { + await seed('0', { 'code-mode': true, ...trafficOn }); + const output = initOutput(); + + await expectCodeMode('0', false); + expect(output).not.toContain(CODE_MODE_TRAFFIC_BLOCKER); + expect(output).not.toContain(CODE_MODE_PROXY_BLOCKER); + }, SUBPROCESS_TIMEOUT_MS); + + it('warns once about traffic when preflight fails, but not about the proxy', async () => { + await seed('1', { 'code-mode': true, ...trafficOn }, true); + const output = initOutput(['--proxy']); + + expect(output).toContain('External model routing preflight failed:'); + expect(output).not.toContain(CODE_MODE_PROXY_BLOCKER); + expectWarningOnce(output, CODE_MODE_TRAFFIC_BLOCKER); + expect((await readManifest(tmpHome)).features.proxy).toBe(false); + await expectCodeMode('1', true); + }, SUBPROCESS_TIMEOUT_MS); + + it('warns once about traffic when both flags are on', async () => { + await seed('1', { 'code-mode': true, ...trafficOn }); + const output = initOutput(); + + expectWarningOnce(output, CODE_MODE_TRAFFIC_BLOCKER); + expect((await readManifest(tmpHome)).features.flags).toMatchObject(trafficOn); + await expectCodeMode('1', true); + }, SUBPROCESS_TIMEOUT_MS); + + it('warns once about the proxy after successful preflight and keeps both on', async () => { + await seed('1', {}); + await fs.mkdir(path.join(tmpHome, '.codex')); + await fs.writeFile(path.join(tmpHome, '.codex', 'auth.json'), '{}'); + // The loopback fixture serves a fixed health response. It sends no auth data. + const server = createServer((req, res) => { + if (req.method !== 'GET' || req.url !== '/__subswitch/health') { + res.writeHead(404).end(); + return; + } + res.end('{"name":"subswitch"}'); + }); + try { + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Expected a TCP port'); + const proxyPath = path.join(tmpHome, '.devflow', 'proxy.json'); + await fs.writeFile(proxyPath, JSON.stringify({ enabled: false, port: address.port })); + + const { stdout, stderr } = await promisify(execFile)(process.execPath, [CLI_PATH, ...MINIMAL_INIT, '--proxy'], { + cwd: tmpHome, env: sandboxEnv(tmpHome), timeout: SUBPROCESS_TIMEOUT_MS, + }); + + expectWarningOnce(stdout + stderr, CODE_MODE_PROXY_BLOCKER); + expect((await readManifest(tmpHome)).features.proxy).toBe(true); + expect(JSON.parse(await fs.readFile(proxyPath, 'utf-8'))).toMatchObject({ enabled: true, port: address.port }); + await expectCodeMode('1', true); + } finally { + await server[Symbol.asyncDispose](); + } + }, SUBPROCESS_TIMEOUT_MS); +}); + // ── One home: --scope retired, CLAUDE_CONFIG_DIR honoured, DEVFLOW_DIR ignored ── // // #389 (D-SCOPE-RETIRED, D-CLAUDE-CONFIG-DIR, D-ONE-HOME). Each init spawn is ~0.5 s; @@ -757,8 +857,6 @@ function runCli( return { status: r.status, out: `${r.stdout ?? ''}${r.stderr ?? ''}` }; } -const MINIMAL_INIT = ['init', '--recommended', '--no-ambient', '--no-memory', '--no-curation', '--no-knowledge', '--no-rules']; - describe('resolveRetiredScopeOption (D-SCOPE-RETIRED)', () => { it('no flag and `user` in any case proceed', () => { expect(resolveRetiredScopeOption(undefined)).toEqual({ kind: 'proceed' }); From 3f52715cc47a70b7214d7f424dec88ff7e7c3262 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 01:04:16 +0200 Subject: [PATCH 06/20] docs: document the Code Mode flag List the blockers and the user settings rules. Explain why Code Mode and the Devflow proxy cannot run in the same session. Task: feat/code-mode-direct Refs: #792 --- CHANGELOG.md | 6 +++++- docs/cli-reference.md | 16 ++++++++++++---- docs/reference/file-organization.md | 3 ++- docs/reference/proxy.md | 11 +++++++++++ 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8f4fde28..efb2f8d0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **Experimental Code Mode flag.** Use `devflow flags --enable code-mode` for direct Claude Code sessions. The flag is off by default. This change applies to new sessions only. Code Mode does not start while the Devflow proxy or `disable-nonessential-traffic` is on. + ### Changed -- **Routing runtime pinned to `subswitch@0.7.0`** — before: `0.6.0`. The Devflow proxy adds `gpt-6.2-sol`, `gpt-6.2-astra`, and `gpt-6.1-terra` to the model catalog. The runtime marks `gpt-6.1-terra` as a preview model. The `sol` and `astra` aliases now select their GPT-6.2 models. An agent set to either alias moves to the new model at its next session. To keep the old model, use `devflow agents --set --model ` with `gpt-6.1-sol` or `gpt-6-astra`. The `terra` alias still selects `gpt-5.6-terra`; select `gpt-6.1-terra` by exact ID. The `proxy-routing.json` format stays the same. The relay now keeps private rate-limit records in `~/.cache/subswitch/limits//` (four files, at most 8 MiB for each port, owner-only permissions). `devflow uninstall` does not remove this folder. +- **Devflow proxy runtime update.** The runtime moves from `0.6.0` to `0.7.0`. The Devflow proxy adds `gpt-6.2-sol`, `gpt-6.2-astra`, and `gpt-6.1-terra` to the model catalog. The runtime marks `gpt-6.1-terra` as a preview model. The `sol` and `astra` aliases now select their GPT-6.2 models. An agent set to either alias moves to the new model at its next session. To keep the old model, use `devflow agents --set --model ` with `gpt-6.1-sol` or `gpt-6-astra`. The `terra` alias still selects `gpt-5.6-terra`; select `gpt-6.1-terra` by exact ID. The `proxy-routing.json` format stays the same. The relay now keeps private rate-limit records in its cache, in a separate folder for each port. Each folder holds up to four files and 8 MiB, with owner-only permissions. `devflow uninstall` does not remove these folders. --- diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 571da208e..0669bf34b 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -461,7 +461,7 @@ npx devflow-kit flags --unset # Reset flag(s) to neutral, comma-separ `--enable` and `--disable` accept boolean flags only. Non-boolean flags (enum, number, string) use `--set id=value`. Passing a non-boolean id to `--enable`/`--disable` prints an error and redirects to `--set`. -All 32 flags by kind and devflow default: +All 33 flags by kind and Devflow default: | Flag ID | Kind | Target | Devflow Default | |---------|------|--------|-----------------| @@ -478,7 +478,7 @@ All 32 flags by kind and devflow default: | `brief` | boolean | env `CLAUDE_CODE_BRIEF` | `false` | | `thinking-summaries` | boolean | setting `showThinkingSummaries` | `false` | | `subprocess-env-scrub` | boolean | env `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` | `false` | -| `disable-nonessential-traffic` | boolean | env `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | `false` | +| `disable-nonessential-traffic` | boolean | env `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | `false` (Code Mode does not start if this flag is on) | | `forked-subagents` | boolean | env `CLAUDE_CODE_FORK_SUBAGENT` | `false` | | `disable-adaptive-thinking` | boolean | env `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` | `false` | | `always-thinking` | boolean | setting `alwaysThinkingEnabled` | `false` | @@ -487,6 +487,7 @@ All 32 flags by kind and devflow default: | `disable-1m-context` | boolean | env `CLAUDE_CODE_DISABLE_1M_CONTEXT` | `false` | | `disable-autoupdater` | boolean | env `DISABLE_AUTOUPDATER` | `false` | | `agent-teams` | boolean | env `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | `false` | +| `code-mode` | boolean | env `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE` | `false`⁶ | | `enable-todo-tools` | boolean | env `CLAUDE_CODE_ENABLE_TODO_TOOLS` | `false` | | `suppress-attribution` | boolean | setting `attribution` | `false` ²| | `subagent-spawn-depth` | number | env `CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH` | unset (upstream: 3) | @@ -508,6 +509,13 @@ All 32 flags by kind and devflow default: ⁵ `subagent-cache-5m` writes `"5m"`, so subagents write 5-minute prompt-cache entries while the main session keeps the 1-hour TTL of `prompt-caching-1h`. Disabling or uninstalling deletes the key only when it holds `"5m"`. When the key already holds another value (say `"1h"`), `devflow init` and the flags TUI record the flag off and keep your value; `init --reset` writes `"5m"`. +⁶ `code-mode` is experimental and off by default. This change applies to new sessions only. Code Mode does not work with `claude -p`. + +- **Blockers.** Code Mode does not start with the Devflow proxy or `disable-nonessential-traffic` on. A custom `ANTHROPIC_BASE_URL`, `apiKeyHelper`, `ANTHROPIC_AUTH_TOKEN`, or OpenTelemetry export also blocks Code Mode. Code Mode with `agent-teams` needs Claude Code v2.1.326 or later. +- **User settings only.** Claude Code reads the enable value only from `env` in user settings. A `0` in the shell or in any settings file takes priority. A project setting cannot turn Code Mode on. Devflow checks only local state and the user settings `env`, not shell exports or project settings. +- **Values Devflow keeps.** Devflow writes `"1"` to enable Code Mode. If the key has a different value, Devflow keeps your value and records `code-mode` off on the next flag write. An explicit request to turn `code-mode` on can replace that value. Devflow removes the key only if it holds `"1"`. +- **Refusals and warnings.** Devflow refuses to turn `code-mode` on while the Devflow proxy is on. Run `devflow proxy --disable` first. Devflow warns about the proxy and `disable-nonessential-traffic` only while Code Mode is on. Devflow does not check the other blockers. If both Code Mode and the proxy are on after proxy preflight, `devflow init` warns and keeps both on. + ## External Model Routing (Devflow Proxy) Route Devflow agents through GPT models via your OpenAI/Codex subscription. When enabled, a local Devflow proxy relay intercepts agent requests and forwards them to the configured model. @@ -523,9 +531,9 @@ npx devflow-kit proxy --enable --port # Enable on a specific port (default: | Option | Description | |--------|-------------| -| `--enable` | Enable routing — runs preflight, writes `~/.devflow/proxy.json` and `~/.devflow/proxy-routing.json`, starts and verifies the relay, injects `ANTHROPIC_BASE_URL` and `CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT` into `settings.json`, applies saved agent model mapping | +| `--enable` | Enable routing — runs preflight, writes `~/.devflow/proxy.json` and `~/.devflow/proxy-routing.json`, starts and verifies the relay, injects `ANTHROPIC_BASE_URL` and `CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT` into `settings.json`, applies saved agent model mapping. If Code Mode is on, this command refuses the change. Run `devflow flags --disable code-mode` first. | | `--disable` | Disable routing — reverts agent frontmatter to Claude defaults, removes env override; mapping is preserved for re-enable; the relay process is left running for live sessions (a manual `kill ` hint is shown) | -| `--status` | Show feature state (enabled/disabled, port), relay process and PID, `ANTHROPIC_BASE_URL` and `CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT` env state, Codex auth content (not just existence), external-mapped agent count, cached model registry, and proxy log path | +| `--status` | Show feature state (enabled/disabled, port), relay process and PID, `ANTHROPIC_BASE_URL` and `CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT` env state, Codex auth content (not just existence), external-mapped agent count, cached model registry, and proxy log path. Warn about the proxy or `disable-nonessential-traffic` only while Code Mode is on. | | `--port ` | Override the relay port (default 4141); takes effect on next enable | Takes effect in new Claude Code sessions after `--enable`. The relay auto-starts on `SessionStart` via the `ensure-proxy` hook; `UserPromptSubmit` exits immediately with no action (SessionStart handles all relay-start and warning logic). Routing state is stored in `~/.devflow/proxy.json`; per-agent model mapping in `~/.devflow/agent-models.json`. diff --git a/docs/reference/file-organization.md b/docs/reference/file-organization.md index 6863a1158..0809a82b7 100644 --- a/docs/reference/file-organization.md +++ b/docs/reference/file-organization.md @@ -24,7 +24,8 @@ devflow/ │ │ ├── paths.ts # getPackageRoot + asset path helpers │ │ ├── assets.ts # skillsDir, agentsDir, rulesDir, scriptsDir, commandsDir, │ │ │ # compiledAgentsDir, agentSourceDirs (dist-first order owner) -│ │ ├── flags.ts # Claude Code flag registry (32 flags) +│ │ ├── flags.ts # Claude Code flag registry (33 flags) +│ │ ├── code-mode.ts # Code Mode checks, warnings, and refusal messages │ │ ├── fs-atomic.ts # Atomic write helper (D34) │ │ ├── claude-md-audit.ts # Typed seam onto scripts/claude-md-audit.cjs: roots, the one init note, the stamp write (lstat-checked) │ │ ├── manifest.ts # Manifest read/write diff --git a/docs/reference/proxy.md b/docs/reference/proxy.md index 5b5bc65b2..81af5f805 100644 --- a/docs/reference/proxy.md +++ b/docs/reference/proxy.md @@ -5,3 +5,14 @@ External model routing: running Devflow agents on GPT models through a local rel ## External Model Routing **External Model Routing (Devflow Proxy)**: Routes Devflow agents through GPT models via an OpenAI/Codex subscription using a local relay. Feature state is manifest-gated (like ambient/hud/rules): `manifest.features.proxy` is the source of truth; `~/.devflow/proxy.json` holds runtime authority (enabled, port, binPath, configPath, resolvedAt, devflowVersion). `~/.devflow/proxy-routing.json` holds the routing config; `buildRoutingConfigJson` writes port-only on a fresh write (no `anthropic` block injected — the relay's own default governs); user-set keys in `logLevel`/`anthropic`/`providers`/`limits` blocks are preserved from existing content; the 0.4.0 routing runtime rejects unrecognised top-level keys and hard-fails on registered legacy keys — `anthropic.streamIdleTimeoutMs`, `limits.connectTimeoutMs`, `limits.maxConcurrentRequests`, `limits.maxBodyBytes`, `limits.maxUpstreamSockets`, `limits.streamIdleTimeoutMs`, `limits.requestTimeoutMs`, `limits.maxSseEventBytes` — which `buildRoutingConfigJson` strips. The `ensure-proxy` hook (SessionStart + UserPromptSubmit, registered/removed by `addProxyHooks`/`removeProxyHooks`) auto-starts the relay when a session begins; hook removal is unconditional on disable. `ANTHROPIC_BASE_URL` and `CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT` are injected into (and stripped from) `settings.json` at CLI enable/disable time via `applyProxyEnv`/`applyProxyTeardownToSettings`, not by the hook; env stripping is evidence-gated on `~/.devflow/proxy.json` existing (`proxyJsonExists()`); the URL delete is port-scoped to avoid clobbering foreign gateways; preflight refuses a foreign `ANTHROPIC_BASE_URL` before adopting a healthy relay; the `ensure-proxy` hook re-resolves a missing `binPath` before warning. Toggle via `devflow proxy --enable/--disable/--status` or via the Advanced init wizard. Enabling runs `runProxyPreflight` (4 checks: bin, codex auth, port, settings), spawns the relay, then gates on a post-spawn doctor verification against the live relay (doctor requires a running relay to pass); on doctor failure the enable rolls back, killing the relay only if it spawned it. Init runs the same preflight but never spawns or runs doctor — the first session's ensure-proxy hook starts the relay; on init preflight failure: warning + force-disabled, init never aborted. Disabling reverts agent frontmatter to Claude defaults but preserves the model mapping for re-enable. Default OFF; Advanced-only — never part of Recommended defaults. + +## Code Mode + +Code Mode needs a direct Claude Code session. It does not start while the Devflow proxy is on. + +- To turn Code Mode on, first run `devflow proxy --disable`. +- If Code Mode is on, `devflow proxy --enable` refuses the change. First run `devflow flags --disable code-mode`. +- `devflow proxy --status` warns about the proxy and `disable-nonessential-traffic` only while Code Mode is on. +- If both Code Mode and the proxy are on after proxy preflight, `devflow init` warns and keeps both on. + +See [Feature Flags](../cli-reference.md#feature-flags) for the other Code Mode blockers. From 0241a513b3c1a19b08b6870917e75457ae9bd963 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 01:14:02 +0200 Subject: [PATCH 07/20] fix: address self-review issues --- src/cli/commands/flags.ts | 10 ++++++-- src/cli/commands/proxy.ts | 12 ++++++---- src/core/code-mode.ts | 42 ++++++++++++++++----------------- src/core/gate-level.ts | 44 ++++------------------------------- src/core/proxy-state.ts | 27 +++++++++------------ src/core/read-file-bytes.ts | 38 ++++++++++++++++++++++++++++++ tests/code-mode.test.ts | 16 +++++++++++++ tests/flags-cli.test.ts | 26 +++++++++++++++------ tests/proxy-code-mode.test.ts | 9 +++++++ 9 files changed, 132 insertions(+), 92 deletions(-) create mode 100644 src/core/read-file-bytes.ts diff --git a/src/cli/commands/flags.ts b/src/cli/commands/flags.ts index 77e8a11b0..1a7569e08 100644 --- a/src/cli/commands/flags.ts +++ b/src/cli/commands/flags.ts @@ -595,7 +595,13 @@ export async function applyTuiResult( const viewModeExplicit = newRecord['view-mode'] !== existingRecord['view-mode']; const codeModeRow = result.rows.find(row => row.id === 'code-mode'); - const check = await checkCodeModeWrite(claudeDir, devflowDir, codeModeRow?.configuredValue === true); + const codeModeEdited = codeModeRow !== undefined && codeModeRow.configuredValue !== codeModeRow.originalValue; + if (!codeModeEdited) { + // A save of other rows must respect a settings edit made while the editor was open. + const seed = respectUserOwnedSettings(existingRecord, existingRecord, freshSettingsContent); + newRecord['code-mode'] = seed['code-mode'] === true; + } + const check = await checkCodeModeWrite(claudeDir, devflowDir, codeModeEdited && codeModeRow.configuredValue === true); if (!check.ok) return 'refused'; const persistResult = await persistFlagConfig( @@ -603,7 +609,7 @@ export async function applyTuiResult( { ...check.value, viewModeExplicit }, ); if (persistResult.ok) { - if (codeModeRow && codeModeRow.configuredValue !== codeModeRow.originalValue) { + if (codeModeEdited) { logFlagSuccess(codeModeRow.id, `${codeModeRow.id} ${formatFlagValue(codeModeRow.def, codeModeRow.configuredValue)}`); } return 'saved'; diff --git a/src/cli/commands/proxy.ts b/src/cli/commands/proxy.ts index f169ef8d4..d19be5c83 100644 --- a/src/cli/commands/proxy.ts +++ b/src/cli/commands/proxy.ts @@ -39,12 +39,14 @@ import { CODE_MODE_READ_FAILURE, PROXY_ENABLE_REFUSAL, codeModeBlockers, + codeModeManifestSignals, isCodeModeOn, isProxyOn, isTrafficOn, readCodeModeSignals, } from '../../core/code-mode.js'; -import { syncManifestFeature, readManifest } from '../../core/manifest.js'; +import { syncManifestFeature } from '../../core/manifest.js'; +import { readGateManifest } from '../../core/gate-level.js'; import { writeSettingsFileAtomic } from '../../core/fs-atomic.js'; import { scrubChildEnv, openProxyLog, rotateProxyLogIfLarge } from '../../core/proxy-log.js'; import { inspectCodexAuth, classifyCodexAuthReadError, type CodexAuthState } from '../../core/codex-auth-inspect.js'; @@ -1406,11 +1408,12 @@ async function runStatus(): Promise { p.intro(color.bgBlue(color.white(' Devflow Proxy Status '))); // Feature state: manifest + proxy.json - const manifest = await readManifest(devflowDir, { heal: false }); + const manifest = await readGateManifest(devflowDir); + const { record, manifestProxy } = codeModeManifestSignals(manifest); const proxyStateResult = await readProxyState(devflowDir); const proxyState = proxyStateResult.ok ? proxyStateResult.value : null; - const manifestEnabled = manifest?.features.proxy ?? false; + const manifestEnabled = manifest.kind === 'object' && manifestProxy; const stateEnabled = proxyState?.enabled ?? false; if (manifestEnabled !== stateEnabled) { @@ -1473,10 +1476,9 @@ async function runStatus(): Promise { }; p.log.info(`ANTHROPIC_BASE_URL: ${envStateLabels[envState]}`); - const record = manifest?.features.flags ?? null; for (const line of codeModeBlockers({ codeModeOn: isCodeModeOn(record, env), - proxyOn: isProxyOn({ proxyJsonOn: !proxyStateResult.ok || stateEnabled, manifestProxy: manifestEnabled, urlState: envState }), + proxyOn: isProxyOn({ proxyJsonOn: !proxyStateResult.ok || stateEnabled, manifestProxy, urlState: envState }), trafficOn: isTrafficOn(record, env), })) p.log.warn(line); diff --git a/src/core/code-mode.ts b/src/core/code-mode.ts index 2934e3a75..891d9a532 100644 --- a/src/core/code-mode.ts +++ b/src/core/code-mode.ts @@ -1,7 +1,7 @@ -import { constants, promises as fs } from 'node:fs'; +import { readFileBytes } from './read-file-bytes.js'; import { join } from 'node:path'; import { findFlag, holdsOwnEnvPayload, holdsUserEnvValue, isEnvBooleanFlag } from './flags.js'; -import { readGateManifest } from './gate-level.js'; +import { readGateManifest, type GateManifestRead } from './gate-level.js'; import { classifyProxyBaseUrl, DEFAULT_PROXY_PORT, readProxyState } from './proxy-state.js'; import type { ProxyEnvState, Result } from './proxy-state.js'; @@ -103,26 +103,25 @@ function isPlainObject(value: unknown): value is Record { } async function readSettingsEnv(settingsPath: string): Promise { + const bytes = await readFileBytes(settingsPath, MAX_SETTINGS_BYTES); + if (bytes === 'absent') return {}; + if (typeof bytes === 'string') return undefined; try { - // O_NONBLOCK prevents a pipe at this path from blocking the open. - const file = await fs.open(settingsPath, constants.O_RDONLY | constants.O_NONBLOCK); - try { - const stat = await file.stat(); - if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return undefined; - const buffer = Buffer.alloc(stat.size + 1); - const { bytesRead } = await file.read(buffer); - if (bytesRead !== stat.size) return undefined; - const settings: unknown = JSON.parse(buffer.toString('utf8', 0, bytesRead)); - if (!isPlainObject(settings)) return undefined; - return isPlainObject(settings.env) ? settings.env : {}; - } finally { - await file.close(); - } - } catch (err) { - return err instanceof Error && 'code' in err && err.code === 'ENOENT' ? {} : undefined; + const settings: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)); + if (!isPlainObject(settings)) return undefined; + return isPlainObject(settings.env) ? settings.env : {}; + } catch { + return undefined; } } +/** An unrelated manifest defect does not erase a readable switch. */ +export function codeModeManifestSignals(manifest: GateManifestRead | null) { + const rawFeatures = manifest && 'raw' in manifest ? manifest.raw.features : null; + const features = isPlainObject(rawFeatures) ? rawFeatures : null; + return { record: isPlainObject(features?.flags) ? features.flags : null, manifestProxy: features?.proxy === true }; +} + /** * D-CODE-MODE-SIGNALS: Read only local files. Never probe the relay or heal the manifest. * Count an unreadable proxy state file as on. Ignore an absent or corrupt manifest. @@ -137,17 +136,16 @@ export async function readCodeModeSignals( const [proxy, manifest] = devflowDir === null ? [null, null] : await Promise.all([readProxyState(devflowDir), readGateManifest(devflowDir)]); - const rawFeatures = manifest && 'raw' in manifest ? manifest.raw.features : null; - const features = isPlainObject(rawFeatures) ? rawFeatures : null; + const { record, manifestProxy } = codeModeManifestSignals(manifest); const urlState = classifyProxyBaseUrl(env?.ANTHROPIC_BASE_URL, proxy?.ok ? proxy.value.port : DEFAULT_PROXY_PORT); return { ok: true, value: { env, - record: isPlainObject(features?.flags) ? features.flags : null, + record, proxyOn: isProxyOn({ proxyJsonOn: proxy !== null && (!proxy.ok || proxy.value.enabled), - manifestProxy: features?.proxy === true, + manifestProxy, urlState, }), }, diff --git a/src/core/gate-level.ts b/src/core/gate-level.ts index f366cd0c3..09a1c63f2 100644 --- a/src/core/gate-level.ts +++ b/src/core/gate-level.ts @@ -1,4 +1,4 @@ -import { promises as fs, constants as fsConstants } from 'fs'; +import { readFileBytes } from './read-file-bytes.js'; import * as path from 'path'; import { writeFileAtomicExclusive } from './fs-atomic.js'; import { hasRequiredManifestFields } from './manifest.js'; @@ -147,42 +147,6 @@ function startsWithBom(bytes: Uint8Array): boolean { return bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf; } -/** Bytes of the manifest, or why not: one bounded read of a regular file, followed through links. */ -async function readManifestBytes(manifestPath: string): Promise { - try { - let st; - try { - st = await fs.stat(manifestPath); - } catch (err: unknown) { - const code = (err as NodeJS.ErrnoException).code; - return code === 'ENOENT' || code === 'ENOTDIR' ? 'absent' : 'corrupt'; - } - if (!st.isFile() || st.size > MAX_MANIFEST_BYTES) return 'corrupt'; - - // O_NONBLOCK: a FIFO swapped in after the stat cannot block the open. - const handle = await fs.open(manifestPath, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK || 0)); - try { - const opened = await handle.stat(); - if (!opened.isFile() || opened.size > MAX_MANIFEST_BYTES) return 'corrupt'; - // One byte past the stat'd size: a file that grew between the stat and the - // read is refused rather than truncated into something that parses. Each - // pass reads at least one byte or stops, so the loop is bounded by the buffer. - const buf = Buffer.alloc(opened.size + 1); - let total = 0; - for (let pass = 0; pass < buf.length && total < buf.length; pass++) { - const { bytesRead } = await handle.read(buf, total, buf.length - total, null); - if (bytesRead === 0) break; - total += bytesRead; - } - return total > opened.size ? 'corrupt' : buf.subarray(0, total); - } finally { - await handle.close().catch(() => undefined); - } - } catch { - return 'corrupt'; - } -} - /** * Read `/manifest.json` raw, for the gate level. Never throws, never * exits and never writes: unlike readManifest() it heals nothing, models no key @@ -196,9 +160,9 @@ async function readManifestBytes(manifestPath: string): Promise { - const bytes = await readManifestBytes(path.join(devflowDir, 'manifest.json')); - if (bytes === 'absent') return ABSENT; - if (bytes === 'corrupt') return CORRUPT; + const bytes = await readFileBytes(path.join(devflowDir, 'manifest.json'), MAX_MANIFEST_BYTES); + if (bytes === 'absent' || bytes === 'not-directory') return ABSENT; + if (bytes === 'unreadable') return CORRUPT; let parsed: unknown; try { parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); diff --git a/src/core/proxy-state.ts b/src/core/proxy-state.ts index 1ebfddd1a..e68e294d0 100644 --- a/src/core/proxy-state.ts +++ b/src/core/proxy-state.ts @@ -18,6 +18,7 @@ import { createRequire } from 'module'; import { join } from 'path'; import { promises as fs } from 'fs'; import { writeFileAtomicExclusive } from './fs-atomic.js'; +import { readFileBytes } from './read-file-bytes.js'; // --------------------------------------------------------------------------- // Result type (local; matches codebase pattern of per-module definitions) @@ -41,6 +42,7 @@ function Err(error: E): Result { /** Default port for the Devflow proxy. */ export const DEFAULT_PROXY_PORT = 4141; +const MAX_PROXY_STATE_BYTES = 1024 * 1024; /** * State persisted to ~/.devflow/proxy.json. @@ -70,8 +72,14 @@ export interface ProxyState { */ export async function readProxyState(devflowDir: string): Promise> { const statePath = join(devflowDir, 'proxy.json'); + const bytes = await readFileBytes(statePath, MAX_PROXY_STATE_BYTES); + if (bytes === 'absent') { + return Ok({ version: 1, enabled: false, port: DEFAULT_PROXY_PORT, + binPath: null, configPath: null, resolvedAt: null, devflowVersion: null }); + } + if (typeof bytes === 'string') return Err('Cannot read the Devflow proxy state file.'); try { - const content = await fs.readFile(statePath, 'utf-8'); + const content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); const data = JSON.parse(content) as Record; // Tolerant parse: provide safe defaults for missing/invalid fields. @@ -85,21 +93,8 @@ export async function readProxyState(devflowDir: string): Promise { + try { + let stat; + try { + stat = await fs.stat(filePath); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + if (code === 'ENOENT') return 'absent'; + return code === 'ENOTDIR' ? 'not-directory' : 'unreadable'; + } + if (!stat.isFile() || stat.size > maxBytes) return 'unreadable'; + + // A pipe substituted after the stat must not block the open. + const file = await fs.open(filePath, constants.O_RDONLY | (constants.O_NONBLOCK || 0)); + try { + const opened = await file.stat(); + if (!opened.isFile() || opened.size > maxBytes) return 'unreadable'; + const bytes = Buffer.alloc(opened.size + 1); + let total = 0; + for (let pass = 0; pass < bytes.length && total < bytes.length; pass++) { + const { bytesRead } = await file.read(bytes, total, bytes.length - total, null); + if (bytesRead === 0) break; + total += bytesRead; + } + return total > opened.size ? 'unreadable' : bytes.subarray(0, total); + } finally { + await file.close(); + } + } catch { + return 'unreadable'; + } +} diff --git a/tests/code-mode.test.ts b/tests/code-mode.test.ts index ef1591f51..11624b3c6 100644 --- a/tests/code-mode.test.ts +++ b/tests/code-mode.test.ts @@ -169,6 +169,16 @@ describe('readCodeModeSignals', () => { await expectRefusal(true); }); + it('refuses when proxy.json exceeds the local state size limit', async () => { + await fs.writeFile(join(devflowDir, 'proxy.json'), JSON.stringify({ enabled: false, padding: ' '.repeat(1024 * 1024) })); + await expectRefusal(true); + }); + + it('refuses when proxy.json is not a regular file', async () => { + await fs.mkdir(join(devflowDir, 'proxy.json')); + await expectRefusal(true); + }); + it('refuses when proxy.json cannot be parsed', async () => { await fs.writeFile(join(devflowDir, 'proxy.json'), '{'); await expectRefusal(true); @@ -194,6 +204,12 @@ describe('readCodeModeSignals', () => { expect(await read()).toMatchObject({ ok: true, value: { env: undefined, proxyOn: false } }); }); + it('reports unavailable settings when a JSON string has invalid UTF-8 bytes', async () => { + const bytes = Buffer.concat([Buffer.from('{"value":"'), Buffer.from([0xff]), Buffer.from('"}')]); + await fs.writeFile(settingsPath, bytes); + expect(await read()).toMatchObject({ ok: true, value: { env: undefined } }); + }); + it('reports unavailable settings when the path is a directory', async () => { await fs.mkdir(settingsPath); expect(await read()).toMatchObject({ ok: true, value: { env: undefined } }); diff --git a/tests/flags-cli.test.ts b/tests/flags-cli.test.ts index e43e60ee9..aee5c37bf 100644 --- a/tests/flags-cli.test.ts +++ b/tests/flags-cli.test.ts @@ -172,17 +172,20 @@ describe('flags CLI — createFlagsCommand factory', () => { expect(process.exitCode).toBe(0); } - async function runTui(changes: FlagsRecord) { + async function runTui(changes: FlagsRecord, beforeSave?: () => Promise) { const streams = [process.stdin, process.stdout]; const tty = streams.map(stream => stream.isTTY); streams.forEach(stream => Object.defineProperty(stream, 'isTTY', { value: true, configurable: true })); vi.doMock('../src/cli/flags-view/index.js', () => ({ - runFlagsTui: async (rows: ReturnType) => ({ - action: 'save', - rows: rows.map(row => Object.hasOwn(changes, row.id) - ? { ...row, configuredValue: changes[row.id] } - : row), - }), + runFlagsTui: async (rows: ReturnType) => { + await beforeSave?.(); + return { + action: 'save', + rows: rows.map(row => Object.hasOwn(changes, row.id) + ? { ...row, configuredValue: changes[row.id] } + : row), + }; + }, })); vi.resetModules(); try { @@ -314,6 +317,15 @@ describe('flags CLI — createFlagsCommand factory', () => { expect(vi.mocked(p.log.success).mock.calls.flat().join('\n')).toContain(codeMode.CODE_MODE_NEW_SESSIONS_SUFFIX); }); + it.each([ + { flags: { 'code-mode': true }, initial: '1', fresh: '0', on: false }, + { flags: {}, initial: '0', fresh: '1', on: true }, + ])('keeps a user change from $initial to $fresh while the editor is open', async ({ flags, initial, fresh, on }) => { + const { settingsPath } = await seed(flags, { [codeKey]: initial }); + await runTui({ lsp: true }, () => fs.writeFile(settingsPath, JSON.stringify({ env: { [codeKey]: fresh } }))); + await expectSaved(on, fresh); + }); + it('keeps a hand-set on value on an unrelated TUI save', async () => { await seed({}, { [codeKey]: '1' }); diff --git a/tests/proxy-code-mode.test.ts b/tests/proxy-code-mode.test.ts index aa2eef9a0..76d7a7834 100644 --- a/tests/proxy-code-mode.test.ts +++ b/tests/proxy-code-mode.test.ts @@ -178,6 +178,15 @@ describe('proxy --status Code Mode warnings', () => { expect(vi.mocked(p.log.warn).mock.calls).toEqual([[CODE_MODE_PROXY_BLOCKER]]); }); + it('uses readable switches even if another manifest field is absent', async () => { + seedFile('.devflow/manifest.json', JSON.stringify({ features: { flags: codeOn, proxy: true } })); + const before = snapshot(); + await run('--status'); + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[CODE_MODE_PROXY_BLOCKER]]); + expect(process.exitCode).toBe(0); + expect(snapshot()).toEqual(before); + }); + it('uses the recorded traffic flag without a proxy signal', async () => { seedManifest({ ...codeOn, 'disable-nonessential-traffic': true }); seedFile('.claude/settings.json', '{"env":[]}'); From c7f498ee14cac5077fb492bcf34b4d981babf551 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 01:38:30 +0200 Subject: [PATCH 08/20] test: unmock flags view after each test Use the non-hoisted call so the cleanup runs after the test. Task: feat/code-mode-direct --- tests/flags-cli.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/flags-cli.test.ts b/tests/flags-cli.test.ts index aee5c37bf..44d80876b 100644 --- a/tests/flags-cli.test.ts +++ b/tests/flags-cli.test.ts @@ -1359,7 +1359,7 @@ describe('flags CLI — createFlagsCommand factory', () => { Object.defineProperty(process.stdin, 'isTTY', { value: origStdinIsTTY, configurable: true }); // Remove the doMock registration and clear module cache so subsequent tests // get the real flags-view implementation. - vi.unmock('../src/cli/flags-view/index.js'); + vi.doUnmock('../src/cli/flags-view/index.js'); vi.resetModules(); }); @@ -1440,7 +1440,7 @@ describe('flags CLI — createFlagsCommand factory', () => { afterEach(() => { Object.defineProperty(process.stdout, 'isTTY', { value: origStdoutIsTTY, configurable: true }); Object.defineProperty(process.stdin, 'isTTY', { value: origStdinIsTTY, configurable: true }); - vi.unmock('../src/cli/flags-view/index.js'); + vi.doUnmock('../src/cli/flags-view/index.js'); vi.resetModules(); }); @@ -1504,7 +1504,7 @@ describe('flags CLI — createFlagsCommand factory', () => { afterEach(() => { Object.defineProperty(process.stdout, 'isTTY', { value: origStdoutIsTTY, configurable: true }); Object.defineProperty(process.stdin, 'isTTY', { value: origStdinIsTTY, configurable: true }); - vi.unmock('../src/cli/flags-view/index.js'); + vi.doUnmock('../src/cli/flags-view/index.js'); vi.resetModules(); }); From 16480bc1405b8ae85ff15e5f8eb5c91ec2799458 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 02:23:18 +0200 Subject: [PATCH 09/20] docs(knowledge): update installer-shadowing-wizard-flags feature knowledge base --- .devflow/features/index.md | 2 +- .../KNOWLEDGE.md | 142 ++++++++++-------- 2 files changed, 78 insertions(+), 66 deletions(-) diff --git a/.devflow/features/index.md b/.devflow/features/index.md index df9179d57..875dfd394 100644 --- a/.devflow/features/index.md +++ b/.devflow/features/index.md @@ -11,7 +11,7 @@ - **installer-shadowing-backups** — src/targets/claude-code, src/cli/commands, src/core — Use when changing the install backup session, shipped set, retired name lists, folder swaps or the bare legacy skill hash gate. Keywords: install-backups, retired, hash gate, swap. - **installer-shadowing-init-seed** — src/cli/commands, src/core — Use when changing init seeding (resolveInitSeed, resolveSeed*, --reset), manifest self-heal, writeManagedConfig, queue drain, --hud-only, proxy preflight order or migrations. Keywords: init-seed, manifest. - **installer-shadowing-init-artifacts** — src/targets/claude-code, src/assets/scripts/hooks — Use when changing DEVFLOW_GITIGNORE_BLOCK, computeDevflowGitignore, ensure-root-gitignore or init's CLAUDE.md import audit and stamp. Keywords: gitignore carve-out, claudeignore, audit stamp. -- **installer-shadowing-wizard-flags** — src/cli, src/core — Use when changing prompt-io, the compliance, attribution or gate-level wizard step, init --gate-level, the flags CLI/TUI, convergeFlagsIntoSettings or settingHoldsManagedShape. Keywords: wizard, flags, TUI, gate level. +- **installer-shadowing-wizard-flags** — src/cli, src/core — Use when changing a wizard step, init --gate-level, the flags CLI/TUI, convergeFlagsIntoSettings, settingHoldsManagedShape or the code-mode flag. Keywords: wizard, flags, TUI, gate level, Code Mode, proxy. - **installer-shadowing-tracker-wiring** — src/core, src/cli, src/targets — Use when changing the tracker wizard step, devflow tracker (--set/--status), the Tracker agent install, the manifest tracker group or init's tracker convergence. Keywords: tracker, provider, sentinel. - **curation-capture-system** — src/assets/scripts/hooks, src/core, src/cli, src/hud — Use when changing the capture hooks, memory/curation queues, machine feature switches or ledger root, or choosing which curation KB to read. Keywords: capture-prompt, queue-append, manifest.json, DF_LEDGER_ROOT. - **curation-capture-system-store** — hooks/lib, json-helper, core/curation-store — Use when changing curation-store.cjs, a json-helper curation op, the observation or ledger schema, the one lock, or rendered decisions.md, pitfalls.md and index.md. Keywords: put-observation, assign-anchor. diff --git a/.devflow/features/installer-shadowing-wizard-flags/KNOWLEDGE.md b/.devflow/features/installer-shadowing-wizard-flags/KNOWLEDGE.md index 99de22fa5..b4e3b2832 100644 --- a/.devflow/features/installer-shadowing-wizard-flags/KNOWLEDGE.md +++ b/.devflow/features/installer-shadowing-wizard-flags/KNOWLEDGE.md @@ -1,11 +1,11 @@ --- feature: installer-shadowing-wizard-flags name: Wizard Steps, Flags CLI/TUI & Managed-shape Oracle -description: "Use when changing prompt-io, the compliance, attribution or gate-level wizard step, init --gate-level, the flags CLI/TUI, convergeFlagsIntoSettings or settingHoldsManagedShape. Keywords: wizard, flags, TUI, gate level." +description: "Use when changing a wizard step, init --gate-level, the flags CLI/TUI, convergeFlagsIntoSettings, settingHoldsManagedShape or the code-mode flag. Keywords: wizard, flags, TUI, gate level, Code Mode, proxy." category: component-patterns -directories: [src/cli/commands/prompt-io.ts, src/cli/commands/compliance-prompts.ts, src/cli/commands/attribution-prompts.ts, src/cli/commands/gate-level-prompts.ts, src/cli/commands/flags.ts, src/cli/flags-view, src/cli/tui, src/core/flags.ts] +directories: [src/cli/commands/prompt-io.ts, src/cli/commands/compliance-prompts.ts, src/cli/commands/attribution-prompts.ts, src/cli/commands/gate-level-prompts.ts, src/cli/commands/flags.ts, src/cli/flags-view, src/cli/tui, src/core/flags.ts, src/core/code-mode.ts, src/core/read-file-bytes.ts] created: 2026-10-10 -updated: 2026-10-23 +updated: 2026-11-19 --- # Wizard Steps, Flags CLI/TUI & Managed-shape Oracle @@ -25,7 +25,7 @@ updated: 2026-10-23 - **KB-AP-11** `persistFlagConfig` never reports success with an absent manifest, and success is tracked in locals, never read back off the process-wide `process.exitCode`. - **KB-AP-12** `--enable` / `--disable` are boolean-only: non-boolean flags use `--set`. - **KB-AP-13** Do not expect `ENTER_ALT` sequences from the flags TUI: it runs inline (`screen: 'inline'`); only agents-view uses the default alt screen. -- **KB-AP-14** `GATE_LEVEL_HINTS` (gate-level-prompts.ts) are short labels, one idea each, and `GATE_LEVEL_EFFECT` (gates.ts) holds the per-effect detail and the commands that read the level: a hint changes only when what a level checks changes, and a command that starts to read the level with no phase rule changes `GATE_LEVEL_EFFECT` alone. A test pins the exact text of both tables and `GATE_LEVEL_MEANINGS`; change one and check the other. One shared table is #551. +- **KB-AP-14** `GATE_LEVEL_HINTS` (gate-level-prompts.ts) are short one-idea labels; `GATE_LEVEL_EFFECT` (gates.ts) holds the per-effect detail and the commands that read the level. A hint changes only when what a level checks changes; a command that reads the level with no phase rule changes `GATE_LEVEL_EFFECT` alone. A test pins both tables and `GATE_LEVEL_MEANINGS`. - **KB-AP-15** Never default, narrow or heal the stored gate level on a seed or promptless path (no `??` default, no `parseGateLevel` write-back): a stored `null` or malformed value must pass through raw. This holds for a level read from a manifest `readManifest()` refuses, too (KB-INV-13). - **KB-AP-16** init never writes the personal `gateLevel` in a repository's `.devflow/config.json`: it writes only the manifest `features.gateLevel`, and the personal key still wins where it exists. - **KB-INV-1** `settingDeleteGuard` protects deletion, not writes: `suppress-attribution` enabled always writes `{"commit":"","pr":""}`, overwriting a custom attribution; disabled deletes the key only when the value deep-equals the managed shape. Test-pinned. @@ -36,121 +36,133 @@ updated: 2026-10-23 - **KB-INV-6** `persistFlagConfig` evaluates the settings write and the manifest write independently; neither is skipped by the other's outcome. - **KB-INV-7** `buildPayload` returns `structuredClone` for object payloads (`D-PAYLOAD-CLONE`): a `FLAG_REGISTRY` entry is never aliased into the caller's settings tree. - **KB-INV-8** Flag `blurb` and `hint` length caps are enforced by registry-walk tests in `tests/flags.test.ts`, not by TypeScript types. -- **KB-INV-9** A guarded setting flag the manifest has not recorded starts OFF when its settings key already holds a value that is not the managed shape; `respectUserOwnedSettings` (built on `settingHoldsUserValue`) is the one rule, applied by the init seed and by the flags TUI's starting rows, with no flag id special-cased. A flag the manifest records keeps its value, so an explicit enable still wins. +- **KB-INV-9** A guarded flag the manifest has not recorded starts OFF when its settings key already holds a value that is not the managed shape; `respectUserOwnedSettings` is the one rule, applied by the init seed and the flags TUI's starting rows and save, with no flag id special-cased. A recorded flag keeps its value, so an explicit enable still wins. - **KB-INV-10** `settingDeleteGuard` has the type of `onPayload` (`SettingPayload`), so a scalar flag guards its scalar the same way an object flag guards its shape: `subagent-cache-5m` deletes `subagentPromptCacheTtl` only while it is still `"5m"`, so a user's own `"1h"` survives disable and uninstall. -- **KB-INV-11** `--gate-level` is parsed (`resolveGateLevelInitState`, strict) right after the `--reset`/`--plugin` check and before any write: an invalid level exits 1, `--hud-only --gate-level` exits 1, and so does `--gate-level` with no value (a Commander error naming the levels, since the option is declared `--gate-level `). -- **KB-INV-12** The gate-level gate is `shouldRunGateLevelStep`, which delegates to the shared `shouldRunPromptedWizardStep` and keys on `modePromptShown`. It is reached only through `resolveGateLevelForInit`, the only precedence site: `--gate-level`, then the wizard answer, then the carried stored value raw. `runGateLevelStepAt` returns a `GateLevelDecision`, both paths assign it to `gateDecision`, and `applyCliToggles` has no `gateLevel` arm. -- **KB-INV-13** init never writes a gate level the user did not choose. A manifest `readManifest()` refuses (valid JSON with a `features` object and a missing or mistyped required field, or a leading byte-order mark) reads as no manifest, yet still holds a level that `devflow gates` and the settings resolver read. So full init (`carriedGateLevel`) and `--hud-only` carry that raw level (`readStoredGateLevel`) unless a prompt answer or `--gate-level` replaces it or `--reset` removes it, and a manifest that cannot be read is reported with the `devflow gates --set ` hint, never written as the default. +- **KB-INV-11** `--gate-level` is parsed strictly (`resolveGateLevelInitState`) right after the `--reset`/`--plugin` check and before any write: an invalid level, `--hud-only --gate-level` and a missing value all exit 1. +- **KB-INV-12** The gate is `shouldRunGateLevelStep` (shared `shouldRunPromptedWizardStep`, keyed on `modePromptShown`), reached only through `resolveGateLevelForInit`, the only precedence site: `--gate-level`, then the wizard answer, then the carried stored value raw. `applyCliToggles` has no `gateLevel` arm. +- **KB-INV-13** init never writes a gate level the user did not choose. A manifest `readManifest()` refuses (a missing or mistyped required field, or a leading byte-order mark) reads as no manifest yet still holds a level that `devflow gates` reads. Full init (`carriedGateLevel`) and `--hud-only` carry that raw level (`readStoredGateLevel`) unless a prompt answer or `--gate-level` replaces it or `--reset` removes it; an unreadable manifest is reported with the `devflow gates --set ` hint, never written as the default. - **KB-AP-17** clack `note()` never wraps and pads every row to the longest line, so one long line widens the whole box: a gate-level hint stays short with no line break and every note line stays within the note cap (`collectGateLevelPromptLengthDefects`). +- **KB-AP-18** Never decide "Code Mode / proxy / traffic is on" with a local check or word a Code Mode message inline: `src/core/code-mode.ts` owns the predicates and the fixed message constants, and tests pin the text. +- **KB-AP-19** A flags write that can turn `code-mode` on never runs before `checkCodeModeWrite`: every mutating branch (`--enable`, `--set`, `--unset`, the TUI save) preflights first, and the TUI save re-derives an unedited `code-mode` row from fresh settings. +- **KB-AP-20** A read-only flags or Code Mode read never heals or probes: use `readManifest(dir, {heal: false})` or the raw `readGateManifest`, and never contact the relay. +- **KB-AP-21** Raw readers of settings, manifest or proxy-state files use `readFileBytes(path, maxBytes)`, never a bare `fs.readFile`: it refuses special files and oversize input. +- **KB-INV-14** An env flag with `deleteOnlyOwnPayload` owns only its exact on payload (`holdsOwnEnvPayload`): any other present value at its key is the user's (`holdsUserEnvValue`), is never deleted, and reads as off. `code-mode` is the only such flag. +- **KB-INV-15** `convergeFlagsIntoSettings` folds guarded env payloads BEFORE the strip (Step 2c): an unclaimed exact own payload is adopted as on; a record `true` over a user env value folds to `false` unless the write lists the id in `explicitOn`, which only the off-to-on preflight (`turnsOnCodeMode`) fills. Init passes none. +- **KB-INV-16** Code Mode and the Devflow proxy are refused together in both directions: flags CLI and TUI refuse off-to-on while the proxy is on (`CODE_MODE_ENABLE_REFUSAL`); `devflow proxy` enable refuses while Code Mode is on (`PROXY_ENABLE_REFUSAL`). A requested-on write with an unreadable `settings.json` is refused (`CODE_MODE_READ_FAILURE`); turning off is never blocked by a read failure. +- **KB-INV-17** Blockers (`codeModeBlockers`) show only while Code Mode is on and describe the FINAL state: `writeTimeWarnings` ignores the before-state. Init warns from the converged record and post-preflight proxy state (`initCodeModeWarnings`). +- **KB-INV-18** `readCodeModeSignals` reads local files only: an unreadable `proxy.json` counts as proxy on, an absent or corrupt manifest is ignored, a null `devflowDir` limits it to the settings `env`, and an unrelated manifest defect never erases a readable `flags` record or `proxy` switch (`codeModeManifestSignals`). ## Overview -Three CLI-layer concerns share this KB because they converge on the flags record: the wizard step modules (`compliance-prompts.ts`, `attribution-prompts.ts`, `gate-level-prompts.ts` over the shared `prompt-io.ts` seam), the `devflow flags` command and its inline TUI, and the pure registry pipeline in `src/core/flags.ts` that writes the record into `settings.json`. Core stays UI-agnostic: all I/O-free flag logic lives in `src/core/flags.ts`; the CLI modules own prompts, Commander wiring, settings I/O and manifest persistence; for that reason the init-specific prompt modules (and `init-seed.ts`) live in `src/cli/commands/`, not `src/core/`. The tracker wizard step (its own gate and prompt shape) is in the tracker-wiring KB; the init-seed KB covers how the seed is computed. +Three CLI-layer concerns share this KB because they converge on the flags record: the wizard step modules (`compliance-prompts.ts`, `attribution-prompts.ts`, `gate-level-prompts.ts` over the shared `prompt-io.ts` seam), the `devflow flags` command and its inline TUI, and the pure registry pipeline in `src/core/flags.ts` that writes the record into `settings.json`. Core stays UI-agnostic: all I/O-free flag logic lives in `src/core/flags.ts`; the CLI modules own prompts, Commander wiring, settings I/O and manifest persistence; for that reason the init-specific prompt modules (and `init-seed.ts`) live in `src/cli/commands/`, not `src/core/`. The tracker step is in the tracker-wiring KB; the init-seed KB covers the seed. ## Shared Wizard Prompt-IO Seam (`prompt-io.ts`) -A one-definition seam owning the shared DI types and the real clack adapters: +One definition of the shared DI types and the real clack adapters; a new wizard step builds on it rather than redefining them: - `PromptOutcome` — `{ kind: 'value'; value: T } | { kind: 'cancel' }`. - `WizardPromptIO` — the base injectable interface: `note(message, title): void` + `select(opts): Promise>`. - `clackNote` / `clackSelect` — the real adapters; `clackSelect` narrows away the cancel branch with `p.isCancel` as a type guard, no `as T` cast. -- `AttributionPromptIO` is a type alias of `WizardPromptIO` (a named export kept for tests and callers importing it by name); `CompliancePromptIO`, `TrackerPromptIO` and `GateLevelPromptIO` extend it with their own prompt. +- `AttributionPromptIO` is a named alias of `WizardPromptIO`; `CompliancePromptIO`, `TrackerPromptIO` and `GateLevelPromptIO` extend it with their own prompt. - `shouldRunPromptedWizardStep({mode, modePromptShown, isTTY, hasCliOverride})` — the shared gate table for a step that runs on both wizard paths: CLI override → no; non-TTY → no; Advanced → yes; Recommended → only when `modePromptShown`. The gate-level step delegates to it. The compliance and tracker gates keep their own copies of the table until #554 moves them; the attribution gate is Advanced-only by design and never uses it. The rows are pinned in `tests/prompt-io.test.ts`. -A new wizard step builds on this module rather than redefining those types. ## Compliance Wizard Step (`compliance-prompts.ts`) -CLI-layer module owning all compliance wizard UI: -- `frameworkChoices()` (clack multiselect options from `COMPLIANCE_FRAMEWORKS`), `FRAMEWORK_SELECT_MESSAGE`, `formatFrameworkCatalogue()` (padded catalogue for the `p.note` body), `formatComplianceSummary(enabled, frameworks)` (pure; the canonical home for the compliance state label, re-exported by `init.ts` for backward-compatible test imports). -- `CompliancePromptIO` — `WizardPromptIO` plus `multiselect`; `buildClackCompliancePrompts()` builds the real adapter, translating the cancel symbol into the `PromptOutcome` union. -- `runComplianceStep(opts)` — pure orchestrator, all I/O through `opts.prompts`. Flow: note header → labeled enable select → framework multiselect (`required:false`). Disabling preserves frameworks (defensive copy; returned arrays never alias the seed). Returns `{kind:'resolved', state, messages}` or `{kind:'cancelled'}`. +CLI-layer module owning all compliance wizard UI: `frameworkChoices()`, `FRAMEWORK_SELECT_MESSAGE`, `formatFrameworkCatalogue()` and `formatComplianceSummary(enabled, frameworks)` (the canonical home of the state label, re-exported by `init.ts` for test imports). +- `CompliancePromptIO` is `WizardPromptIO` plus `multiselect`. `runComplianceStep(opts)` is a pure orchestrator (note header, enable select, framework multiselect with `required:false`); disabling preserves frameworks and returned arrays never alias the seed. It returns `{kind:'resolved', state, messages}` or `{kind:'cancelled'}`. - `shouldRunComplianceStep({mode, modePromptShown, isTTY, hasCliOverride})` — pure gate: `hasCliOverride` (`--compliance` / `--no-compliance`) → no; non-TTY → no; Advanced → yes; Recommended → only when `modePromptShown`, which is `true` only when the Setup-mode `p.select` actually ran (the `--recommended` flag and the non-TTY fallback never set it). BOTH wizard paths call it. Recommended threads the result via `applyCliToggles(…, { compliance: cliComplianceOverride ?? wizardCompliance })`. ## Attribution Wizard Step (`attribution-prompts.ts`, D27) Parallel structure to the compliance module with a deliberately different gate: -- `shouldRunAttributionStep({mode, isTTY})` → `isTTY && mode === 'advanced'`. Safe without `modePromptShown` because the Advanced branch itself exits non-zero on non-TTY, so `mode === 'advanced'` only occurs interactively. There is no CLI override: post-install toggling is `devflow flags --enable/--disable suppress-attribution`. The question never runs on Recommended, which carries the seeded value unchanged. -- `buildClackAttributionPrompts()` delegates to the shared `clackNote` / `clackSelect`. -- `attributionSeedFrom(flags: FlagsRecord): boolean` → `true` only for `suppress-attribution === true` (not `as boolean`; undefined, null and false map to false), so `init.ts` passes a real boolean to `p.select`. -- `applyAttributionAnswer(flags, outcome): FlagsRecord` — immutable merge (a new record, never a mutation) and the single merge site; `init.ts` must not duplicate the spread. -- `runAttributionStep({seed, prompts})` — pure orchestrator. Its note names the destructive enable branch ("Yes REPLACES any existing `attribution` value in settings.json, including a custom one") and carries an org AI-disclosure-policy clause. -- **Call site in `init.ts`:** `mode: useRecommended ? 'recommended' : 'advanced'` (never a string literal); one call, in the Advanced path only, via `shouldRunAttributionStep`; `attributionSeedFrom(enabledFlags)` derives the seed and `applyAttributionAnswer(enabledFlags, outcome)` updates `enabledFlags`. +- `shouldRunAttributionStep({mode, isTTY})` is `isTTY && mode === 'advanced'`: safe without `modePromptShown` because the Advanced branch exits non-zero on non-TTY. There is no CLI override (post-install: `devflow flags --enable/--disable suppress-attribution`), and Recommended carries the seeded value unchanged. +- `attributionSeedFrom(flags)` is `true` only for `suppress-attribution === true`, so `init.ts` passes a real boolean to `p.select`. `applyAttributionAnswer(flags, outcome)` is the single immutable merge site; `init.ts` must not duplicate the spread. +- `runAttributionStep({seed, prompts})` is a pure orchestrator; its note names the destructive enable branch ("Yes REPLACES any existing `attribution` value in settings.json, including a custom one") and an org AI-disclosure-policy clause. +- **Call site in `init.ts`:** `mode: useRecommended ? 'recommended' : 'advanced'` (never a string literal); one call, Advanced path only, via `shouldRunAttributionStep`, seeded by `attributionSeedFrom(enabledFlags)` and merged by `applyAttributionAnswer`. ## Gate-Level Wizard Step (`gate-level-prompts.ts`) Asks for the MACHINE gate level, manifest `features.gateLevel`, the field `devflow gates --set` also writes (`src/cli/commands/gates.ts`). The closed set and parser stay in `src/core/gate-level.ts` (`GATE_LEVELS`, `DEFAULT_GATE_LEVEL`, `parseGateLevel`); this module only imports them. - **Gate:** `shouldRunGateLevelStep({mode, modePromptShown, isTTY, hasCliOverride})` delegates to the shared `shouldRunPromptedWizardStep` (prompt-io section): `--gate-level` → no; non-TTY → no; Advanced → yes; Recommended → only when `modePromptShown`. Rows: `tests/gate-level-prompts.test.ts` and `tests/prompt-io.test.ts`. - **Prompt content:** `GATE_LEVEL_HINTS` (a short label per level), `gateLevelChoices()` (`GATE_LEVELS` order), `formatGateLevelCatalogue()`, `GATE_LEVEL_SELECT_MESSAGE`. The step uses `p.select`, never `p.confirm`, so Enter is an informed keep of a named level. -- **Reading a stored level:** `classifyGateLevel(stored, origin)` is the one classification (`default` | `level` | `malformed` | `unreadable`) behind `describeGateLevel`, `gateLevelPromptSeed`, `formatGateLevelRow` and `formatGateLevelSummary`; a private `appliedLevel` folds it to the level that applies. The prompt starts on the stored level on re-init, on `standard` for `undefined` (first install, no key, `--reset`) or an unreadable level, and on `MALFORMED_GATE_LEVEL_READS_AS` (`full`, in `src/core/gate-level.ts`, held to the settings resolver's fold by a parity test) for a malformed value. `describeGateLevel` adds `(default)` only when nothing is recorded, and shows a malformed value as `invalid (manifest.json; reads as full)`, the words of the `Machine:` line of `devflow gates` (a parity test holds the two); accepting the prompt there records `full`, no `(was X)`. -- **Where the stored level was found:** `StoredGateLevelOrigin` is `manifest` | `rejected` | `unreadable`. `readStoredGateLevel(devflowDir, manifest, reset)` returns `{origin, value}`, the level the run replaces; with a `readManifest()` manifest it is `manifest`. Otherwise the pure `storedGateLevelFromRaw` classifies the raw `readGateManifest` read: `absent`, no key, or `object` (the file changed between reads) → `manifest`, the raw value if any; `rejected` with a level → `rejected`, the value untouched; `corrupt` (no `features` object included) or a value that fails `JSON.stringify` → `unreadable`. Under `--reset` the raw level is read for the summary's prior reading only (`unreadable` becomes `manifest`, no value). `carriedGateLevel({manifest, reset, stored, seedLevel})` is what a full init starts from: the seed's level with a `readManifest()` manifest or under `--reset`, else `stored`. `GateManifestState` in `gates.ts` splits `rejected` (init keeps the level) from `unreadable` (init keeps it only if it can read the file; `readManifest()` has no size bound, so a valid file over 1 MiB, `MAX_MANIFEST_BYTES` in `src/core/gate-level.ts`, is unreadable to gates and readable to init). +- **Reading a stored level:** `classifyGateLevel(stored, origin)` is the one classification (`default` | `level` | `malformed` | `unreadable`) behind `describeGateLevel`, `gateLevelPromptSeed`, `formatGateLevelRow` and `formatGateLevelSummary`. The prompt starts on the stored level on re-init, on `standard` for `undefined` (first install, no key, `--reset`) or an unreadable level, and on `MALFORMED_GATE_LEVEL_READS_AS` (`full`, `src/core/gate-level.ts`, held to the settings resolver's fold by a parity test) for a malformed value. A malformed value shows as `invalid (manifest.json; reads as full)`, the words of the `Machine:` line of `devflow gates` (parity test); accepting the prompt records `full`, no `(was X)`. +- **Where the stored level was found:** `StoredGateLevelOrigin` is `manifest` | `rejected` | `unreadable`. `readStoredGateLevel(devflowDir, manifest, reset)` returns `{origin, value}`, the level the run replaces: `manifest` with a `readManifest()` manifest, else the pure `storedGateLevelFromRaw` classifies the raw `readGateManifest` read (`absent`, no key or `object` → `manifest`; `rejected` with a level → `rejected`, value untouched; `corrupt` or a value that fails `JSON.stringify` → `unreadable`). Under `--reset` the raw level feeds the summary's prior reading only. `carriedGateLevel({manifest, reset, stored, seedLevel})` is a full init's start: the seed's level with a `readManifest()` manifest or under `--reset`, else `stored`. `GateManifestState` in `gates.ts` splits `rejected` (init keeps the level) from `unreadable` (kept only if init can read the file; `readManifest()` has no size bound, so a valid file over `MAX_MANIFEST_BYTES` in `src/core/gate-level.ts` is unreadable to gates and readable to init). - **DI seam:** `GateLevelPromptIO extends WizardPromptIO` with a sibling `selectLevel` (the shared `select` is boolean-typed; widening it would change every wizard). `buildClackGateLevelPrompts()` delegates to `clackNote` / `clackSelect`. -- **Orchestrators:** `runGateLevelStep({stored, storedOrigin?, prompts})` is pure and returns `{kind:'resolved', level}` or `{kind:'cancelled'}`; its note names every command `GATE_LEVEL_EFFECT` lists (`/resolve` included; a test checks it) and shows the origin (`rejected`: init keeps the level unless another is chosen; `unreadable`: `Current setting: unknown`). `resolveGateLevelForInit({cliLevel, stored, storedOrigin, mode, modePromptShown, isTTY, prompts})` wraps the gate and the step (`storedOrigin` required, so the prompt cannot lose it) and returns `{kind:'resolved', level, carried}`: with no prompt it resolves `cliLevel ?? stored`, `carried` true only for `stored`, so an absent, malformed or `null` value, or a level carried from a rejected manifest, passes through untouched. -- **Boundary:** `resolveGateLevelInitState(option, hudOnly)` returns `undefined` when the flag was absent, else `{ok:true, value}` or `{ok:false, error}`: strict (`Lean` or an empty value is rejected with `parseGateLevel`'s own error text and no `--gate-level:` prefix), reports a bad value before the `--hud-only` conflict, and refuses `--hud-only` because that path writes no level. -- **Summary:** `formatGateLevelSummary({level, priorLevel, priorOrigin?, kept, manifestWritten})` returns `SummaryLine[]` from the state the run acted on. The recorded level reads "the machine default; change it with devflow gates --set" and appends ` (was X)` when the applied level changed; a malformed value written back as stored, or accepted at the prompt as the `full` it reads as, is no change. If the manifest did not reach disk, a warning names the prior level and says "the gate level did not change". With a `rejected` prior, a warning says init kept the level only when `kept` is true, so a chosen level never warns, even an equal one. With an `unreadable` prior, a run that recorded none warns that `standard` applies, with the `devflow gates --set ` hint. -- **Call sites in `init.ts`:** `storedGate = readStoredGateLevel(devflowDir, existingManifest, !!options.reset)` follows the manifest read, `carriedGate = carriedGateLevel({...})` follows the seed, and `gateDecision: GateLevelDecision` starts as `{level: carriedGate.value, carried: true}`. The `runGateLevelStepAt(mode)` closure passes `stored: gateDecision.level` and `storedOrigin: carriedGate.origin` and owns the cancel idiom (`p.cancel` + `process.exit(0)`); each path assigns it once, right after the tracker step. It emits no step messages; the summary after the tracker asset summary is the only surface (`kept: gateDecision.carried && carriedGate.origin === 'rejected'`, `priorLevel` and `priorOrigin` from `storedGate`), and the Recommended note adds a `Gate level:` row between `Tracker:` and `View mode:`. The manifest write spreads `gateDecision.level` in only when it is not `undefined`, so a first install, an unreadable manifest without `--gate-level`, and `--reset` record none. -- **`--hud-only`:** it reads `readStoredGateLevel(devflowDir, existingHudManifest, false)`, passes the value to `buildHudOnlyManifest(existing, version, now, refusedGateLevel?)` and, only for a `rejected` or `unreadable` origin, prints the summary lines with `kept: true`; otherwise it says nothing about the gate level. -- **Seed plumbing (`init-seed.ts`):** `FeatureSeed.gateLevel: unknown` is required so the compiler forces every seed site to name it; `resolveSeedFeatures` reads `manifest?.features.gateLevel` with no default operator (`FEATURE_DEFAULTS.gateLevel` is `undefined`), and `applyCliToggles` takes `Partial>`, passing the raw value through. The seed never reads a rejected manifest's file: that is the init-side override (`carriedGateLevel`). +- **Orchestrators:** `runGateLevelStep({stored, storedOrigin?, prompts})` is pure and returns `{kind:'resolved', level}` or `{kind:'cancelled'}`; its note names every command `GATE_LEVEL_EFFECT` lists (a test checks it) and shows the origin. `resolveGateLevelForInit({cliLevel, stored, storedOrigin, mode, modePromptShown, isTTY, prompts})` wraps the gate and the step (`storedOrigin` required, so the prompt cannot lose it) and returns `{kind:'resolved', level, carried}`: with no prompt it resolves `cliLevel ?? stored`, `carried` true only for `stored`, so an absent, malformed or `null` value, or one from a rejected manifest, passes through untouched. +- **Boundary:** `resolveGateLevelInitState(option, hudOnly)` returns `undefined` when the flag was absent, else `{ok:true, value}` or `{ok:false, error}`: strict (`Lean` or an empty value is rejected with `parseGateLevel`'s own error text), reports a bad value before the `--hud-only` conflict, and refuses `--hud-only` because that path writes no level. +- **Summary:** `formatGateLevelSummary({level, priorLevel, priorOrigin?, kept, manifestWritten})` returns `SummaryLine[]` from the state the run acted on. The recorded level reads "the machine default; change it with devflow gates --set" and appends ` (was X)` when the applied level changed (a malformed value written back as stored, or accepted as the `full` it reads as, is no change). A manifest that did not reach disk warns that the gate level did not change. A `rejected` prior warns that init kept the level only when `kept` is true (a chosen level never warns); an `unreadable` prior with no level recorded warns that `standard` applies, with the `devflow gates --set ` hint. +- **Call sites in `init.ts`:** `storedGate = readStoredGateLevel(...)` follows the manifest read, `carriedGate = carriedGateLevel({...})` follows the seed, and `gateDecision: GateLevelDecision` starts as `{level: carriedGate.value, carried: true}`. The `runGateLevelStepAt(mode)` closure passes `stored: gateDecision.level` and `storedOrigin: carriedGate.origin` and owns the cancel idiom (`p.cancel` + `process.exit(0)`); each path assigns it once, right after the tracker step. The summary after the tracker asset summary is the only surface (`kept: gateDecision.carried && carriedGate.origin === 'rejected'`), and the Recommended note adds a `Gate level:` row between `Tracker:` and `View mode:`. The manifest write spreads `gateDecision.level` in only when it is not `undefined`, so a first install, an unreadable manifest without `--gate-level`, and `--reset` record none. +- **`--hud-only`:** it reads `readStoredGateLevel(devflowDir, existingHudManifest, false)`, passes the value to `buildHudOnlyManifest(existing, version, now, refusedGateLevel?)` and prints the summary lines with `kept: true` only for a `rejected` or `unreadable` origin. +- **Seed plumbing (`init-seed.ts`):** `FeatureSeed.gateLevel: unknown` is required so every seed site names it; `resolveSeedFeatures` reads `manifest?.features.gateLevel` with no default operator, and `applyCliToggles` takes `Partial>`. The seed never reads a rejected manifest's file: that is the init-side override (`carriedGateLevel`). ## Flags Pipeline and the Managed-shape Oracle (`src/core/flags.ts`) -- **Registry types:** `FLAG_REGISTRY` (a `ClaudeCodeFlag` per flag; `auto-compact-window` is an opt-in number flag, unset by default); `FlagDefCommon` carries `blurb` (short trailing-column phrase) and `hint`. `BooleanFlagDef = EnvBooleanFlagDef | SettingBooleanFlagDef` is a discriminated union that provides declaration-site guarantees only: `EnvBooleanFlagDef` compile-constrains `onPayload: string` and `settingDeleteGuard?: never`; `SettingBooleanFlagDef` allows a `SettingPayload` (`string | boolean | Record`) `onPayload` and an optional `settingDeleteGuard` of the same `SettingPayload` type (`D-GUARD-SCALAR`, so a scalar can be guarded; the oracle's deep-equal handles any JSON value with no second code path). A nested `target.type` check does NOT narrow `onPayload` for consumers, so `isEnvBooleanFlag(f): f is EnvBooleanFlagDef` (exported) is the narrowing predicate. `suppress-attribution` is a `SettingBooleanFlagDef` (target key `attribution`, `onPayload` and `settingDeleteGuard` both `{commit:'',pr:''}`); `subagent-cache-5m` is the scalar one (target key `subagentPromptCacheTtl`, `onPayload` and `settingDeleteGuard` both `"5m"`, default ON, placed right after `prompt-caching-1h`, which it leaves untouched) (`D-SUBAGENT-CACHE-5M`: subagents write 5-minute cache entries while the main session keeps the 1-hour TTL; the registry comment records the vendor-precedence probe, and a Claude Code that predates the setting ignores the key). The registry's size is pinned by the `FLAG_REGISTRY` `toHaveLength` assertion in `tests/flags.test.ts`. -- **Single equality oracle:** `settingValueHoldsManagedShape(flag, value)` is true iff the flag has a `settingDeleteGuard` and the value deep-equals it (`node:util.isDeepStrictEqual`); `settingHoldsManagedShape(settingsJson, flagId)` reads `settings.json` and delegates; its mirror `settingHoldsUserValue(settingsJson, flagId)` is true when a guarded setting flag's key is present (`hasOwnProperty`, so an explicit `null` counts) with a value that is not the managed shape, and false for malformed JSON, a non-object root, an unknown or unguarded flag or an absent key. `respectUserOwnedSettings(flags, manifestFlags, settingsSnapshot)` (`D-ADOPT-RESPECTS-USER`, pure) sets such a flag `false` when the manifest does not record it, so the converge pipeline neither writes nor deletes the user's value. `canDeleteSettingKey` (module-private, `D-ATTR-GUARD`) is shared by `applyFlags`' neutral branch and `stripFlags` and delegates to the oracle. `resolveExistingAttributionSuppression` (init-seed KB) and the Step 2b adoption fold delegate too. -- **`convergeFlagsIntoSettings(settingsJson, record, {viewModeExplicit, ownedRecord?})`** is the fold-before-strip pipeline; both `init.ts` and `persistFlagConfig` MUST call it instead of `stripFlags` + `applyFlags` directly, so the invariant lives in the pipeline. Steps: (1) fold view-mode via `resolveFinalViewMode`, so an externally set `/focus` survives unless `viewModeExplicit`; (2) fold existing settings values into the record for unclaimed valued (enum/number/string) flags — "claimed" is decided by `ownedRecord` (omitted → the record itself, the `persistFlagConfig` path; `null` → nothing owned, fresh install; the pre-seed manifest flags on the init path), and boolean flags are never folded at this step; (2b, `D-ATTR-ADOPT`) adopt guarded boolean settings whose pre-strip on-disk value matches the managed shape, only when the record does not already claim the flag (a claimed `false` or `null` still deletes the block), so a template-written attribution block is not stripped unconditionally on first init; (3) `stripFlags` then `applyFlags` over the folded record; (4) `orderKeysLike` restores the pre-strip key order, top-level and inside `env` (`D-KEY-ORDER`: strip-then-apply re-adds every managed key at the end, and the security deny list merged AFTER the flags appends `permissions`, so without the restore the second init reorders and re-init is no longer byte-for-byte stable). Uninstall calls `stripFlags` directly with no record, preserving its full-sweep semantics. +- **Registry types:** `FLAG_REGISTRY` holds a `ClaudeCodeFlag` per flag (`auto-compact-window` is an opt-in number flag, unset by default); `FlagDefCommon` carries `blurb` and `hint`. `BooleanFlagDef = EnvBooleanFlagDef | SettingBooleanFlagDef` gives declaration-site guarantees only: the env variant constrains `onPayload: string` and `settingDeleteGuard?: never`; the setting variant allows a `SettingPayload` `onPayload` and a `settingDeleteGuard` of the same type, so a scalar can be guarded and the deep-equal oracle handles any JSON value. A nested `target.type` check does NOT narrow `onPayload` for consumers: `isEnvBooleanFlag(f)` is the narrowing predicate. `suppress-attribution` guards the object `{commit:'',pr:''}` at key `attribution`; `subagent-cache-5m` is the scalar one (key `subagentPromptCacheTtl`, `"5m"`, default ON, right after `prompt-caching-1h`, which it leaves untouched): subagents write 5-minute cache entries while the main session keeps the 1-hour TTL, and a Claude Code that predates the setting ignores the key. Every registry default must be safe to ship unseen, because init sets flags without asking: `code-mode` is off and not recommended. The registry size is pinned by the `toHaveLength` assertion in `tests/flags.test.ts`. +- **Single equality oracle:** `settingValueHoldsManagedShape(flag, value)` is true iff the flag has a `settingDeleteGuard` and the value deep-equals it (`isDeepStrictEqual`); `settingHoldsManagedShape(settingsJson, flagId)` reads `settings.json` and delegates. Its mirror `settingHoldsUserValue` is true when a guarded setting flag's key is present (an explicit `null` counts) with a value that is not the managed shape, and false for malformed JSON, a non-object root, an unknown or unguarded flag or an absent key. `respectUserOwnedSettings(flags, manifestFlags, settingsSnapshot)` (pure) sets such a flag `false` when the manifest does not record it, so the converge pipeline neither writes nor deletes the user's value. `canDeleteSettingKey` (private) is shared by `applyFlags`' neutral branch and `stripFlags`; `resolveExistingAttributionSuppression` (init-seed KB) and the Step 2b fold delegate too. +- **`convergeFlagsIntoSettings(settingsJson, record, {viewModeExplicit, ownedRecord?, explicitOn?})`** is the fold-before-strip pipeline; both `init.ts` and `persistFlagConfig` MUST call it instead of `stripFlags` + `applyFlags`. Steps: (1) fold view-mode via `resolveFinalViewMode`, so an externally set `/focus` survives unless `viewModeExplicit`; (2) fold existing settings values into the record for unclaimed valued (enum/number/string) flags: "claimed" is decided by `ownedRecord` (omitted → the record itself, the `persistFlagConfig` path; `null` → nothing owned, fresh install; the pre-seed manifest flags on the init path); booleans are never folded here; (2b) adopt guarded boolean settings whose pre-strip on-disk value matches the managed shape, only when the record does not already claim the flag (a claimed `false` or `null` still deletes the block), so a template-written attribution block survives first init; (2c, KB-INV-15) `foldOwnEnvPayloads` over guarded env flags; (3) `stripFlags` then `applyFlags` over the folded record; (4) `orderKeysLike` restores the pre-strip key order, top-level and inside `env`: strip-then-apply re-adds every managed key at the end and the deny list merged AFTER the flags appends `permissions`, so without the restore re-init is no longer byte-for-byte stable. Uninstall calls `stripFlags` directly with no record, keeping its full-sweep semantics. +- **Env own-payload guard:** `EnvBooleanFlagDef.deleteOnlyOwnPayload` marks a flag that deletes its env key only when the value is exactly `onPayload` (`canDeleteEnvKey`, the env twin of the settings oracle); the `code-mode` entry (`CLAUDE_CODE_EXPERIMENTAL_CODE_MODE`, `onPayload` `'1'`) is the only user. It is the same prove-you-wrote-it rule as `settingDeleteGuard`, applied to a string env value. - **Registry adoption of an on-disk key:** the day a settings key that already ships on disk becomes registry-managed, it must be adopted before the strip pass; the presence of `settingDeleteGuard` is the signal and Step 2b the mechanism. - **Ownership contract:** the guarded deletion is the prove-you-wrote-it contract (only remove a key whose value is the devflow-managed shape). Its corollary — a guard protects deletion, not overwrite — is why enable overwrites a custom attribution while disable preserves one. ## Flags CLI (`src/cli/commands/flags.ts`) -- **`createFlagsCommand()`** is the root Commander for `devflow flags` (a fresh instance per call; `flagsCommand` is the singleton `src/cli.ts` imports). Options: `--list`, `--status`, `--enable `, `--disable `, `--set ` (repeatable), `--unset `; bare invocation on a TTY launches the TUI, on non-TTY it prints the status table and exits 1. Flags resolve through `findFlag(id)` from core (unknown IDs error). -- **`readSettingsSafe`** returns `{ok, content}` / `{ok:false, reason}` and never silently falls back to `{}` on malformed JSON (that would clobber the user's settings); a root that is not a JSON object is rejected. ENOENT yields `{}`. `loadFlagContext` is the one shared load path for the mutating branches. -- **`persistFlagConfig(claudeDir, devflowDir, settingsContent, newRecord, manifest, {viewModeExplicit})`** runs `convergeFlagsIntoSettings`, writes `settings.json` (atomically) and `manifest.json` (`features.flags` = the FOLDED record, so adopted values persist and the two stay in sync) independently, and returns a discriminated `PersistResult`: `{ok:true}`, `{ok:false, failed:['settings'|'manifest'...]}`, or `{ok:false, reason:'no-manifest'}` — an absent manifest is a failure, not a no-op, because "Flags saved." with an unrecorded selection is reverted by the next init. Callers print success only on `ok === true`. `applyTuiResult(result, freshSettingsContent, manifest, claudeDir, devflowDir)` (exported) derives `viewModeExplicit` from whether the view-mode row changed and returns `'saved' | 'unchanged' | PersistResult failure`. -- **`handleBare` builds the TUI's starting rows** with `buildFlagRows(respectUserOwnedSettings(record, record, settingsContent))` (`D-ADOPT-RESPECTS-USER`): passing the record as its own manifest view means only flags it does not yet record can flip, so an upgrade that has not run init yet shows an unrecorded `subagent-cache-5m` as OFF when `settings.json` holds the user's own `"1h"`, and a Save does not write `"5m"` over it. The settings snapshot is read in `handleBare`, so the reducer and renderer stay pure; `tests/flags-cli.test.ts` drives it with a mocked `runFlagsTui` that captures the rows. -- **Display vocabulary (`D-EFFDV`, one definition, every surface via `effectiveDisplay`):** `--enable` / `--disable` confirmations call `formatFlagValue` (`true` → `on`, `false` → `off`); `--set` confirmations route active values through `formatFlagValue` and echo literal `unset` for a `null` input at the call site (the user typed that word); `formatStatusRows` (the non-TTY status table, sanitised with `sanitizeCell`) renders not-adopted rows as `not adopted — default: applies on next devflow init` using `effectiveDisplay(flag, neutralValueOf(flag)).text`; `--list` prints `upstream default: N` for number flags with `upstreamDefault`, else the `defaultValue` string or `none` (never `unset`). +- **`createFlagsCommand()`** is the root Commander for `devflow flags` (a fresh instance per call; `flagsCommand` is the singleton `src/cli.ts` imports). Options: `--list`, `--status`, `--enable `, `--disable `, `--set ` (repeatable), `--unset `; bare on a TTY launches the TUI, on non-TTY it prints the status table and exits 1. IDs resolve through `findFlag` (unknown IDs error). +- **`readSettingsSafe`** returns `{ok, content}` / `{ok:false, reason}` and never falls back to `{}` on malformed JSON (that would clobber the user's settings); a non-object root is rejected, ENOENT yields `{}`. `loadFlagContext` is the one shared load path for the mutating branches. +- **`persistFlagConfig(claudeDir, devflowDir, settingsContent, newRecord, manifest, {viewModeExplicit, before?, explicitOn?})`** runs `convergeFlagsIntoSettings`, writes `settings.json` (atomically) and `manifest.json` (`features.flags` = the FOLDED record, so adopted values persist) independently, then prints `writeTimeWarnings` for the final state. It returns a discriminated `PersistResult`: `{ok:true}`, `{ok:false, failed:['settings'|'manifest'...]}` or `{ok:false, reason:'no-manifest'}` (an absent manifest is a failure: "Flags saved." with an unrecorded selection is reverted by the next init). Callers print success only on `ok === true`. `applyTuiResult(...)` (exported) derives `viewModeExplicit` from whether the view-mode row changed and returns `'saved' | 'unchanged' | 'refused' | PersistResult` failure. +- **`handleBare` builds the TUI's starting rows** with `buildFlagRows(respectUserOwnedSettings(record, record, settingsContent))`: only flags the record does not yet record can flip, so an unrecorded `subagent-cache-5m` shows OFF when `settings.json` holds the user's own `"1h"` and a Save does not write `"5m"` over it. The settings snapshot is read in `handleBare`, so the reducer and renderer stay pure; `tests/flags-cli.test.ts` drives it with a mocked `runFlagsTui` that captures the rows. +- **Display vocabulary (one definition, every surface via `effectiveDisplay`):** `--enable` / `--disable` confirmations call `formatFlagValue` (`true` → `on`, `false` → `off`); `--set` confirmations do the same for active values and echo literal `unset` for a `null` input at the call site (the user typed that word); `formatStatusRows` (sanitised with `sanitizeCell`) renders not-adopted rows as `not adopted — default: applies on next devflow init`; `--list` prints `upstream default: N` for number flags with `upstreamDefault`, else the `defaultValue` string or `none` (never `unset`). + +## Code Mode Flag (`src/core/code-mode.ts`) + +Code Mode (experimental) lets one step make several tool calls from code; it does not start while the Devflow proxy, `disable-nonessential-traffic`, a custom base URL and similar settings are active, and the flag registry (never the proxy) owns the env key. +- **Predicates:** `isCodeModeOn(record, env)`: an exact own payload in `env` is on, any other value at the key is off (the user's), else the record's `code-mode === true`. `isTrafficOn` is true for a record `true` or any `env` value other than `0` / `false`. `isProxyOn` is true for `proxy.json` enabled, the manifest `proxy` switch, or an `ANTHROPIC_BASE_URL` classified `ours` / `ours-other-port`. +- **Preflight (`checkCodeModeWrite` in `flags.ts`):** reads the signals before any write, computes `turnsOnCodeMode(before, requestedOn)`, and refuses (exit 1, nothing written) on proxy on or a read failure. `--set` takes the LAST assignment of `code-mode` as `requestedOn`; `--unset` and `--disable` pass false. After a successful persist the CLI reads the signals again for warnings; the success line for `code-mode` adds `CODE_MODE_NEW_SESSIONS_SUFFIX`. +- **Status:** `--status` and the non-TTY table add `codeModeBlockers` plus `codeModeStatusNotes` (a user env value: off because settings override; record off over an own payload: the next write removes the setting). `--list` reads with a null `devflowDir`; `devflow proxy` status reads the manifest through `readGateManifest` + `codeModeManifestSignals`. +- **TUI save (`applyTuiResult`):** a row is "edited" when `configuredValue !== originalValue`. An unedited `code-mode` row is recomputed with `respectUserOwnedSettings` over the fresh settings, so a settings edit made while the editor was open is not overwritten; a refused preflight returns `'refused'`. +- **Shared reader (`read-file-bytes.ts`):** `readFileBytes(path, maxBytes)` stats, opens with `O_NONBLOCK` (a pipe swapped in after the stat cannot block), re-stats the handle and reads at most size + 1 bytes. It returns the Buffer or `'absent'` / `'not-directory'` / `'unreadable'` (special file, oversize, grown while reading). The settings `env` reader, `readProxyState` and `readGateManifest` all use it; the settings reader treats invalid UTF-8 and a BOM as unreadable. +- **`heal: false`:** `readManifest(devflowDir, {heal: false})` normalizes in memory and skips the heal write; `loadFlagContext`, `handleStatus` and the non-TTY bare status use it, so a read cannot write the manifest. ## Flags TUI (`src/cli/flags-view/`, `src/cli/tui/`) An interactive editor launched exclusively by `devflow flags` bare on a TTY (D40: init applies flags non-interactively in every path). It runs in **inline mode**, rendering in place in the scroll buffer. -- **`flags-view/state.ts`** — the pure state machine. Exported: `buildFlagRows(record)` (rows from the live `FlagsRecord`; each `FlagRow` holds `id`, the `tui` value, `hint`, and `blurb` sourced from `flag.blurb` at build time, so there is no registry reach-back at render time), `collectFlagRecord(rows)` (the inverse, via `tuiToRecord` per row), `reduce(state, key) → {state, done, saved}`, `resizeViewport`, `BUFFER_MAX_LEN`. Private helpers: `buildStops`, `cycleForward` / `cycleBackward`, `enterEdit` / `commitEdit` / `insertChar` / `reduceEditMode` (inline text edit for enum and string flags), `adjustViewport`. `recordToTui` / `tuiToRecord` live in `core/flags.ts`: the TUI uses `null` as the "devflow default" stop and `tuiToRecord` maps it back to `neutralValueOf`. -- **`flags-view/render.ts`** — frame renderer. Column layout at the 80-col reference: PREFIX 2 (cursor mark), LABEL 27, DIRTY 2 (`● `), VALUE 16, BLURB 30 (dim trailing column, header `HINT`, omitted when `blurbW === 0`); VALUE + BLURB preserve the prior single-VALUE-column total, and all widths scale with terminal width (`Math.min(1, cols/80)`). `formatValue` delegates to `effectiveDisplay` for null/neutral values (`dim(...text)`, with ` (default)` appended for number flags); `true` → green `on`, `false` → yellow `off`; a non-boolean active value is `bold` when it deviates from the devflow default, else plain (`D-BLURB`). +- **`flags-view/state.ts`** — the pure state machine: `buildFlagRows(record)` (each `FlagRow` embeds its registry `def`, `hint` and `blurb`, so there is no registry reach-back at render time; a row is edited when `configuredValue !== originalValue`), `collectFlagRecord(rows)` (the inverse, via `tuiToRecord`), `reduce(state, key) → {state, done, saved}`, `resizeViewport`, `BUFFER_MAX_LEN`; inline text edit serves enum and string flags. The TUI uses `null` as the "devflow default" stop and `tuiToRecord` maps it back to `neutralValueOf` (`recordToTui` / `tuiToRecord` live in `core/flags.ts`). +- **`flags-view/render.ts`** — frame renderer. Columns at the 80-col reference: PREFIX 2, LABEL 27, DIRTY 2, VALUE 16, BLURB 30 (dim trailing column, omitted when `blurbW === 0`); widths scale with terminal width (`Math.min(1, cols/80)`). `formatValue` delegates to `effectiveDisplay` for null/neutral values (` (default)` appended for number flags); `true` → green `on`, `false` → yellow `off`; a non-boolean active value is `bold` when it deviates from the devflow default. - **`tui/cells.ts`** — shared ANSI-aware cell helpers: `sanitizeCell` (strips control characters; prevents terminal injection), `padToVisible`, `truncateVisible`. - **`flags-view/terminal.ts`** — `runFlagsTui` passes `screen: 'inline'` to `runTui` (`D-INLINE`); the intent type is closed so a new `FlagsIntent` member is a compile error. -- **`tui/terminal.ts`** — the generic `runTui` driver. `RunTuiSpec.screen?: 'alt' | 'inline'` defaults to `'alt'` (agents-view); inline mechanics: the first frame writes lines directly, later frames use `cursorUp(prevLineCount - 1) + \r`, rewrite and `ERASE_BELOW`; on exit it cursor-ups to the frame top and uses `ERASE_BELOW` + `SHOW_CURSOR`, erasing the widget so the caller's clack flow continues uninterrupted. `INLINE_MARGIN = 2` lines stay free below the widget so the shell prompt is never clobbered (height clamped to `stdout.rows - INLINE_MARGIN`). `cursorUp(n)` returns `ESC[nA` for `n > 0` and an empty string otherwise, so callers need no guard. +- **`tui/terminal.ts`** — the generic `runTui` driver. `RunTuiSpec.screen?: 'alt' | 'inline'` defaults to `'alt'` (agents-view). Inline: the first frame writes lines directly, later frames use `cursorUp(prevLineCount - 1) + \r`, rewrite and `ERASE_BELOW`; on exit it erases the widget so the caller's clack flow continues. `INLINE_MARGIN` lines stay free below the widget (height clamped to `stdout.rows - INLINE_MARGIN`); `cursorUp(n)` returns an empty string for `n <= 0`, so callers need no guard. ## Anti-Patterns -- **KB-AP-1** Four render sites (TUI `formatValue`, the `--enable` / `--disable` confirmation, the `--status` not-adopted message, `--list`'s `defaultLabel`) all route through `effectiveDisplay`; a fifth that hand-codes on/off or shows `unset` creates vocabulary drift. -- **KB-AP-2** The compliance gate runs on interactive Recommended (`modePromptShown: true`); the attribution gate never does. The divergence is design intent, documented in `attribution-prompts.ts`. -- **KB-AP-4** The template merge runs BEFORE the flags pipeline, so a template-written value would be immediately overwritten, or on the off path leave a stale block. Single ownership is enforced by omission from the template and the merge function and by a registry-driven test in `tests/post-install-merge.test.ts`. -- **KB-AP-5** `resolveExistingAttributionSuppression` and the Step 2b fold both use the oracle; a hand-rolled copy drifts. +- **KB-AP-1, KB-AP-2** The render sites (TUI `formatValue`, the `--enable` / `--disable` confirmation, the `--status` not-adopted message, `--list`'s `defaultLabel`) all route through `effectiveDisplay`. The compliance gate runs on interactive Recommended; the attribution gate never does, by design (documented in `attribution-prompts.ts`). +- **KB-AP-4** The template merge runs BEFORE the flags pipeline, so a template-written value would be overwritten, or on the off path leave a stale block. A registry-driven test in `tests/post-install-merge.test.ts` enforces the omission. - **KB-AP-7** Skipping the restore reintroduces the re-init non-idempotency (#388 AC-3). -- **KB-AP-14** The tables differ in shape (`GATE_LEVEL_HINTS` a per-level `Record` of short labels, `GATE_LEVEL_EFFECT` one sentence naming the commands that read the level), so TypeScript cannot flag drift. The `the init prompt and devflow gates describe the same levels` describe in `tests/gate-level-prompts.test.ts` pins the exact text of `GATE_LEVEL_HINTS`, `GATE_LEVEL_EFFECT` and `GATE_LEVEL_MEANINGS`. The hints state no level effect in full, so they are not doc sites of `tests/guards/implement-resolve-level-docs.test.ts`; the full effects live in `GATE_LEVEL_EFFECT`, `devflow gates` and the docs. Further rows check the shared clauses only (level sets, malformed fold, lint-pack level, fewer review focuses, Polish skips); a one-sided edit to another clause is caught by the pin alone. -- **KB-AP-15** `manifest?.features.gateLevel ?? DEFAULT` turns a stored `null` into `standard`, and init would then write that over a value every reader folds to `full`, silently lowering the level. So `FeatureSeed.gateLevel` is raw, the promptless path is `cliLevel ?? stored` (the only `??`, and `cliLevel` is a parsed level or `undefined`), and an absent key stays out of the manifest write. The same holds for a level read from a rejected manifest (`StoredGateLevel.value` stays raw) and for `buildHudOnlyManifest`'s `refusedGateLevel`. -- **KB-AP-16** The machine level and the personal level are different keys: the wizard text and the summary line say "the machine default", and `tests/init-gate-level-e2e.test.ts` pins that init leaves a repository config without `gateLevel` alone and keeps an existing personal key. +- **KB-AP-14** The two tables differ in shape, so TypeScript cannot flag drift. The `the init prompt and devflow gates describe the same levels` describe in `tests/gate-level-prompts.test.ts` pins the exact text of `GATE_LEVEL_HINTS`, `GATE_LEVEL_EFFECT` and `GATE_LEVEL_MEANINGS`. The hints are not doc sites of `tests/guards/implement-resolve-level-docs.test.ts`; full effects live in `GATE_LEVEL_EFFECT`, `devflow gates` and the docs. +- **KB-AP-15** `manifest?.features.gateLevel ?? DEFAULT` turns a stored `null` into `standard`, and init would write that over a value every reader folds to `full`, silently lowering the level. So `FeatureSeed.gateLevel` is raw, the promptless path is `cliLevel ?? stored` (the only `??`), and an absent key stays out of the manifest write. The same holds for a rejected manifest's level and `buildHudOnlyManifest`'s `refusedGateLevel`. +- **KB-AP-16** The machine level and the personal level are different keys: the wizard text says "the machine default", and `tests/init-gate-level-e2e.test.ts` pins that init leaves a repository config without `gateLevel` alone and keeps an existing personal key. ## Gotchas -- **KB-INV-1** `settingDeleteGuard` is test-pinned asymmetric: with a custom attribution block (for example an org name) a flag-disable preserves it and a flag-enable overwrites it. The wizard note says so. -- **KB-AP-9** After `if (f.target.type === 'env')`, `f` is still `BooleanFlagDef` and `f.onPayload` remains `string | boolean | Record`. -- **`--set flag=unset`** is parsed to `null` by `parseFlagValueInput`; the `handleSet` confirmation special-cases `null → 'unset'` so the user sees their own word. It is the only place `unset` still reaches user-facing output. +- **`--set flag=unset`** parses to `null` via `parseFlagValueInput`; the `handleSet` confirmation special-cases `null → 'unset'`, the only place `unset` reaches user-facing output. - **KB-AP-13** A flags TUI test expecting `ENTER_ALT` fails for `runFlagsTui` but passes for agents-view tests; use `screen: 'alt'` when testing alt-screen behaviour. - **Selective uninstall never strips flags** (`runCleanupPhase` only; uninstall KB), so flag state persists when plugins are removed. -- **KB-INV-4 fold timing:** a record that already has `suppress-attribution: false` or `null` still deletes the block; the fold only claims unclaimed flags. -- **KB-INV-12 wiring test is source text:** the `init.ts wiring` describe in `tests/gate-level-prompts.test.ts` regex-matches `init.ts`: one `resolveGateLevelForInit({` call, one `gateDecision = await runGateLevelStepAt(...)` per path and no other assignment beside the `let`, no `Promise` closure type, and these lines verbatim: `mode,`, `modePromptShown,`, `stored: gateDecision.level,`, `storedOrigin: carriedGate.origin,`, the `carriedGateLevel` inputs and the `kept:` line. Reformatting fails it by design. -- **Rejected and unreadable manifests (KB-INV-13):** a promptless init over a rejected manifest keeps the raw level and warns; a prompt answer or `--gate-level` replaces it, and `--reset` removes it (named as `(was full)`), with no warning. Over an unreadable one a promptless init writes no level and warns with the hint. Pinned in `tests/init-gate-level-e2e.test.ts`. +- **KB-INV-12 wiring test is source text:** the `init.ts wiring` describe in `tests/gate-level-prompts.test.ts` regex-matches `init.ts`: one `resolveGateLevelForInit({` call, one `gateDecision = await runGateLevelStepAt(...)` per path and no other assignment beside the `let`, and the `mode,`, `modePromptShown,`, `stored: gateDecision.level,`, `storedOrigin: carriedGate.origin,`, `carriedGateLevel` input and `kept:` lines verbatim. Reformatting fails it by design. +- **Rejected and unreadable manifests (KB-INV-13):** a promptless init over a rejected manifest keeps the raw level and warns; a prompt answer or `--gate-level` replaces it and `--reset` removes it (as `(was full)`), with no warning. Over an unreadable one a promptless init writes no level and warns with the hint (`tests/init-gate-level-e2e.test.ts`). - **KB-INV-11 `--hud-only` writes early:** it writes before the wizard, so the `--gate-level` parse sits above every write; an invalid value leaves an existing install byte-for-byte unchanged (`tests/init-gate-level-e2e.test.ts`). -- **KB-AP-17 note width:** `@clack/prompts` `note()` pads each row to the longest line, and neither it nor the select hint wraps. `collectGateLevelPromptLengthDefects` (`tests/gate-level-prompts.test.ts`) holds `GATE_LEVEL_HINT_MAX` and `GATE_LEVEL_NOTE_LINE_MAX` (a line plus the border fits 80 columns): a hint with no line break, and every note line for every origin in `STORED_GATE_LEVEL_ORIGINS`; a known-bad probe proves it. Shorten a failing line, never raise a cap. -- **Test fixtures match runtime shapes:** `tests/init-e2e-flags.test.ts` drives subprocess tests over the real init settings pass. +- **KB-AP-17 note width:** `@clack/prompts` `note()` pads each row to the longest line, and neither it nor the select hint wraps. `collectGateLevelPromptLengthDefects` (`tests/gate-level-prompts.test.ts`) holds `GATE_LEVEL_HINT_MAX` and `GATE_LEVEL_NOTE_LINE_MAX` for the hint and every note line for every origin in `STORED_GATE_LEVEL_ORIGINS`. Shorten a failing line, never raise a cap. +- **KB-INV-15 silent fold-down:** a record `true` over a user env value (for example an own `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE` of another string) is folded to `false` on any write that does not list the id in `explicitOn`, and is persisted as `false`; only an off-to-on request overwrites the user's value. `tests/write-set-fence.test.ts` pins that a refused `--enable code-mode` writes nothing. ## Key Files -- `src/core/flags.ts` — `FLAG_REGISTRY`, `FlagDefCommon` (`blurb`, `hint`), `BooleanFlagDef` / `EnvBooleanFlagDef` / `SettingBooleanFlagDef`, `SettingPayload`, `isEnvBooleanFlag`, `settingValueHoldsManagedShape`, `settingHoldsManagedShape`, `settingHoldsUserValue`, `respectUserOwnedSettings`, `canDeleteSettingKey` (private), `buildPayload` (`structuredClone`), `convergeFlagsIntoSettings` + `orderKeysLike`, `applyFlags`, `stripFlags`, `FlagsRecord` / `FlagsRecordValue`, `effectiveDisplay`, `formatFlagValue`, `getDefaultFlagsRecord`, `sanitizeFlagsRecord`, `migrateLegacyFlagsToRecord`, `coerceFlagValue`, `parseFlagValueInput`, `neutralValueOf`, `isNeutral`, `countActiveFlags`, `findFlag`, `recordToTui` / `tuiToRecord`, `readViewMode`, `resolveExistingViewMode`, `resolveFinalViewMode` -- `src/cli/commands/flags.ts` — `createFlagsCommand`, `flagsCommand`, `applyTuiResult`, `PersistResult`; private `readSettingsSafe`, `loadFlagContext`, `persistFlagConfig`, `formatStatusRows`, `handleList` / `handleStatus` / `handleSetBooleans` / `handleSet` / `handleUnset` / `handleBare` +- `src/core/flags.ts` — `FLAG_REGISTRY`, the `BooleanFlagDef` family and `isEnvBooleanFlag`, the managed-shape oracle (`settingValueHoldsManagedShape`, `settingHoldsManagedShape`, `settingHoldsUserValue`, `respectUserOwnedSettings`), `holdsOwnEnvPayload` / `holdsUserEnvValue`, `buildPayload`, `convergeFlagsIntoSettings` + `orderKeysLike`, `applyFlags`, `stripFlags`, `FlagsRecord`, `effectiveDisplay`, `formatFlagValue`, `neutralValueOf`, `findFlag`, `recordToTui` / `tuiToRecord`, the view-mode resolvers +- `src/core/code-mode.ts` — `isCodeModeOn`, `isTrafficOn`, `isProxyOn`, `turnsOnCodeMode`, `codeModeRefusal`, `codeModeBlockers`, `writeTimeWarnings`, `codeModeStatusNotes`, `initCodeModeWarnings`, `readCodeModeSignals`, `codeModeManifestSignals`, the fixed message constants +- `src/core/read-file-bytes.ts` — `readFileBytes`, the bounded regular-file reader +- `src/cli/commands/flags.ts` — `createFlagsCommand`, `flagsCommand`, `applyTuiResult`, `PersistResult`; private `readSettingsSafe`, `loadFlagContext`, `checkCodeModeWrite`, `persistFlagConfig`, `formatStatusRows`, the `handle*` branches +- `src/cli/commands/proxy.ts` — the proxy enable refusal while Code Mode is on and the status read of the same signals; `src/cli/commands/init.ts` prints `initCodeModeWarnings` in the settings pass - `src/cli/commands/prompt-io.ts` — `PromptOutcome`, `WizardPromptIO`, `clackNote`, `clackSelect`, `shouldRunPromptedWizardStep` -- `src/cli/commands/compliance-prompts.ts` — `shouldRunComplianceStep`, `runComplianceStep`, `CompliancePromptIO`, `buildClackCompliancePrompts`, `formatComplianceSummary`, `frameworkChoices`, `FRAMEWORK_SELECT_MESSAGE`, `formatFrameworkCatalogue` -- `src/cli/commands/attribution-prompts.ts` — `shouldRunAttributionStep`, `AttributionPromptIO`, `buildClackAttributionPrompts`, `attributionSeedFrom`, `applyAttributionAnswer`, `runAttributionStep` -- `src/cli/commands/gate-level-prompts.ts` — `shouldRunGateLevelStep`, `runGateLevelStep`, `resolveGateLevelForInit`, `resolveGateLevelInitState`, `readStoredGateLevel`, `storedGateLevelFromRaw`, `carriedGateLevel`, `GateLevelDecision`, `StoredGateLevel` / `StoredGateLevelOrigin`, `classifyGateLevel`, `GateLevelPromptIO`, `buildClackGateLevelPrompts`, `gateLevelChoices`, `GATE_LEVEL_HINTS`, `gateLevelPromptSeed`, `describeGateLevel`, `formatGateLevelCatalogue`, `formatGateLevelRow`, `formatGateLevelSummary` -- `src/cli/flags-view/{state,render,terminal,index}.ts` (`FlagsViewState`, `FlagRow`, `FlagsIntent`, `FlagsTuiResult`, `runFlagsTui`) and `src/cli/tui/{terminal,cells}.ts` (`runTui`, `RunTuiSpec`, `INLINE_MARGIN`, `cursorUp`, `sanitizeCell`, `padToVisible`, `truncateVisible`) — the TUI as above -- `tests/flags.test.ts` (blurb ≤ 30 and hint ≤ 76 registry walks; the registry-size assertion; the `subagent-cache-5m` scalar-guard describes), `tests/flags-cli.test.ts` (bare TUI rows), `tests/post-install-merge.test.ts` (single ownership), `tests/init-e2e-flags.test.ts` (subprocess init settings pass), `tests/flags-view-render.test.ts` (render), `tests/gate-level-prompts.test.ts` (gate table, stored-level origin, `carriedGateLevel`, orchestrators, summary, exact-text pins, prompt-length collector, `init.ts` wiring), `tests/prompt-io.test.ts` (the shared gate table), `tests/init-gate-level-e2e.test.ts` (subprocess `--gate-level`, promptless paths, rejected and unreadable manifests, `--hud-only`, the Recommended note row, personal-key coexistence), `tests/init-machine-switch.test.ts` (`buildHudOnlyManifest` and `refusedGateLevel`) +- `src/cli/commands/compliance-prompts.ts`, `attribution-prompts.ts` — the compliance and attribution gate, orchestrator and clack adapter, as above +- `src/cli/commands/gate-level-prompts.ts` — the gate, orchestrators (`runGateLevelStep`, `resolveGateLevelForInit`), the stored-level readers (`readStoredGateLevel`, `storedGateLevelFromRaw`, `carriedGateLevel`, `classifyGateLevel`), `resolveGateLevelInitState`, `GATE_LEVEL_HINTS` and the describe / summary formatters +- `src/cli/flags-view/{state,render,terminal,index}.ts` and `src/cli/tui/{terminal,cells}.ts` — the TUI as above +- `tests/flags.test.ts` (registry walks, registry size, scalar-guard describes, own-payload fold), `tests/code-mode.test.ts` (predicates, signals reader, messages), `tests/flags-cli.test.ts` (bare TUI rows, refusals), `tests/write-set-fence.test.ts` (each CLI toggle's write allowlist, `code-mode` rows included), `tests/init-e2e-flags.test.ts` (subprocess init settings pass), `tests/post-install-merge.test.ts` (single ownership), `tests/flags-view-render.test.ts`, `tests/gate-level-prompts.test.ts` (gate table, stored-level origin, exact-text pins, prompt-length collector, `init.ts` wiring), `tests/prompt-io.test.ts` (shared gate table), `tests/init-gate-level-e2e.test.ts` (subprocess `--gate-level`, rejected and unreadable manifests, `--hud-only`), `tests/init-machine-switch.test.ts` (`refusedGateLevel`) ## Related @@ -159,6 +171,6 @@ An interactive editor launched exclusively by `devflow flags` bare on a TTY (D40 - `.devflow/features/installer-shadowing-tracker-wiring/KNOWLEDGE.md` — the tracker wizard gate, copying the compliance table - `.devflow/features/installer-shadowing-uninstall/KNOWLEDGE.md` — `stripFlags` with shape-guarded deletion on full uninstall - `.devflow/features/compliance-feature/KNOWLEDGE.md` — what the compliance step selects and installs -- `src/core/gate-level.ts` and `src/cli/commands/gates.ts` — the level set, parser, `MALFORMED_GATE_LEVEL_READS_AS`, raw manifest reader (`readGateManifest`) and writer the step reuses, and `GATE_LEVEL_EFFECT`, the text that names the commands which read the level +- `src/core/gate-level.ts` and `src/cli/commands/gates.ts` — the level set, parser, `MALFORMED_GATE_LEVEL_READS_AS`, `readGateManifest` and `GATE_LEVEL_EFFECT` the step reuses - `docs/reference/init.md` — the user-facing gate level paragraph and `--gate-level` -- `.devflow/features/external-model-routing/KNOWLEDGE.md` — agents-view TUI (alt screen) and proxy +- `.devflow/features/external-model-routing/KNOWLEDGE.md` — agents-view TUI (alt screen) and the proxy that Code Mode refuses beside From 6eb1f4a65ee7e2e7e097ef3351453633db445d9f Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 02:24:52 +0200 Subject: [PATCH 10/20] docs(knowledge): update external-model-routing feature knowledge base --- .../external-model-routing/KNOWLEDGE.md | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/.devflow/features/external-model-routing/KNOWLEDGE.md b/.devflow/features/external-model-routing/KNOWLEDGE.md index f68a9b605..ac2cd3026 100644 --- a/.devflow/features/external-model-routing/KNOWLEDGE.md +++ b/.devflow/features/external-model-routing/KNOWLEDGE.md @@ -3,9 +3,9 @@ feature: external-model-routing name: External Model Routing & Per-Agent Model Config description: "Use when working on the proxy lifecycle (enable, disable, status, preflight), relay teardown, proxy.json or routing config. Keywords: devflow proxy, relay, ANTHROPIC_BASE_URL, dormancy." category: architecture -directories: [src/core/proxy-state.ts, src/core/codex-auth-inspect.ts, src/cli/commands/proxy.ts] +directories: [src/core/proxy-state.ts, src/core/code-mode.ts, src/core/read-file-bytes.ts, src/core/codex-auth-inspect.ts, src/cli/commands/proxy.ts] created: 2026-07-24 -updated: 2026-10-13 +updated: 2026-11-19 --- # External Model Routing & Per-Agent Model Config @@ -22,6 +22,8 @@ updated: 2026-10-13 - **KB-AP-8** Never spawn `binPath` directly: npm does not guarantee executable bits, so always `node `. - **KB-AP-9** Never leave stub relays that tests spawn unreaped on the failure path: orphans stretched the full run from seconds to tens of minutes and caused spurious failures in unrelated files. - **KB-AP-10** Never treat `proxy.json` ENOENT as an error: `readProxyState()` returns the default disabled state, and an error there is a false negative on fresh installs. +- **KB-AP-11** Never duplicate the `ANTHROPIC_BASE_URL` classifier, read `proxy.json` outside `readProxyState`, or put a path, errno or parser message in its error: `classifyProxyBaseUrl` and `readProxyEnvState` live in `proxy-state.ts` (`proxy.ts` only re-exports the latter), and `readProxyState` reads through the bounded reader and returns fixed text. +- **KB-AP-12** Never let `--enable` reach `mkdir`, the spinner, the routing-config write, preflight or hook registration before the Code Mode check: the refusal precedes every side effect, drift repair included. - **KB-INV-1** `isProxyEnabled()` reads only `proxy.json` and is the sole dormancy authority; every path that forces the proxy off writes `proxy.json enabled:false` alongside manifest, hooks and env, or a later reapply writes GPT ids with no relay. - **KB-INV-2** `reapplyAgentMapping` runs only after init preflight has resolved the final `proxyEnabled`. - **KB-INV-3** Teardown always removes the hooks; it strips env only when `applyProxyTeardownToSettings` receives a managed port derived from an existing `proxy.json` (D-STRIP-1). @@ -32,6 +34,9 @@ updated: 2026-10-13 - **KB-INV-8** Init never spawns the relay or runs doctor; a preflight failure warns and forces `proxyEnabled=false`, never aborting init. The first session's hook starts the relay. - **KB-INV-9** `--port` has no commander default: omission means the remembered port in `proxy.json` wins. - **KB-INV-10** The Codex JWT is decoded for display only: never signature-verified, no token material returned, the account id truncated. +- **KB-INV-11** `proxy --enable` refuses (exit 1, nothing written) while Code Mode is on, and also when the Code Mode signals cannot be read (settings unparseable or unreadable); disable and every turn-off path are never blocked by Code Mode. +- **KB-INV-12** `proxy --status` prints Code Mode blocker lines only while Code Mode is on, as warnings after the `ANTHROPIC_BASE_URL` line, from the shared predicates in `code-mode.ts`; it never prints settings values. +- **KB-INV-13** `readProxyState` returns the default disabled state only for an absent file; an unreadable, oversize, non-regular, non-directory-parent or unparseable file is an `Err` with fixed text, and the Code Mode signal reader counts that `Err` as the proxy being on. ## Overview @@ -52,7 +57,7 @@ The routing runtime is an internal package (`subswitch`, exact-pinned in `packag | File | Role | |------|------| -| `~/.devflow/proxy.json` | Runtime authority, tolerant-parsed by `readProxyState()`. ENOENT yields the default disabled state (KB-AP-10). Fields: `enabled`, `port`, `binPath`, `configPath`, `resolvedAt`, `devflowVersion`. | +| `~/.devflow/proxy.json` | Runtime authority, read by `readProxyState()` through the bounded `readFileBytes` (regular file only, size-capped by `MAX_PROXY_STATE_BYTES`; read failures return fixed error text, KB-AP-11), then field-tolerant parsed. Only an absent file yields the default disabled state (KB-AP-10, KB-INV-13). Fields: `enabled`, `port`, `binPath`, `configPath`, `resolvedAt`, `devflowVersion`. | | `~/.devflow/proxy-routing.json` | Routing config from `buildRoutingConfigJson(port, existingContent?)`, written before preflight on enable (contract below). | | `manifest.features.proxy` | Init/uninstall authority. `resolveSeedFeatures` seeds it from `manifest?.features.proxy ?? FEATURE_DEFAULTS.proxy`; `--reset` seeds `false`. | | `proxy.pid`, `logs/proxy.log`, `.proxy-spawn.lock` | Relay pid record (best-effort), relay log, spawn lock. Handled in the hook knowledge base. | @@ -64,6 +69,7 @@ The routing runtime is an internal package (`subswitch`, exact-pinned in `packag ### Enable path (crash-safe) 1. `resolvePort(portOption, priorPort)`: the remembered port from `proxy.json` unless `--port` is given (KB-INV-9). +1b. **Code Mode gate** (KB-INV-11, KB-AP-12): right after the port resolves and before the spinner, `readCodeModeSignals(claudeDir, devflowDir)` reads local files only (settings env, `proxy.json`, the manifest, never the relay). A failed read or an unparseable `settings.json` prints `CODE_MODE_READ_FAILURE`; `isCodeModeOn(record, env)` true prints `PROXY_ENABLE_REFUSAL`. Both set exit 1 and return. The gate sits in `runEnable`, so it also stops drift repair (`proxy.json` on and manifest off, or the reverse) and a hand-set Code Mode with no or a corrupt manifest. The message constants live in `code-mode.ts`; do not reword them inline. The flags side of the pair is in the wizard-flags knowledge base. 2. Create `~/.devflow` and `logs/` (0700), run `rotateProxyLogIfLarge` (pre-spawn only; see the hook knowledge base), then write `proxy-routing.json` through `buildRoutingConfigJson(port, existingContent)`. 3. `runProxyPreflight()`: four ordered checks (see Preflight). Doctor is deliberately excluded (KB-AP-3). 4. Write `proxy.json enabled:true` with the freshly resolved `binPath`. @@ -88,6 +94,10 @@ Hard failures at any step set `process.exitCode = 1` and return (KB-INV-7). Enab `devflow uninstall` only reports a still-running relay (PID and a manual `kill` hint); it never signals. `--status` always probes the relay, even when disabled, so it surfaces the case of a disabled feature with a relay still listening. +### Status Code Mode lines + +`runStatus` reads the manifest with the raw `readGateManifest` and takes the flag record and manifest proxy switch from `codeModeManifestSignals` (an unrelated manifest defect does not erase a readable switch). After the `ANTHROPIC_BASE_URL` line it prints `codeModeBlockers(...)` as warnings, fed by `isCodeModeOn`, `isTrafficOn` and `isProxyOn`. The proxy signal there is `proxy.json` enabled or unreadable, the manifest switch, or a relay URL on any port (`ours` or `ours-other-port`, from `classifyProxyBaseUrl`). With Code Mode off, a proxy that is on prints nothing extra. Status reads `settings.json` itself, so a missing or broken file leaves `env` undefined and the blockers fall back to the record. + ### Settings teardown `applyProxyTeardownToSettings(settings, managedPort | undefined)` is the single teardown decision point for disable and uninstall. With `managedPort === undefined` it returns `removeProxyHooks(settings)` only; otherwise it delegates to `applyDisableToSettings`. The caller derives `managedPort` from an existing `proxy.json`, which is evidence that Devflow wrote the vars; with no file, passing `undefined` skips the env strip rather than clobber a foreign gateway (KB-INV-3). @@ -114,7 +124,7 @@ Hard failures at any step set `process.exitCode = 1` and return (KB-INV-7). Enab ### Init and uninstall -**Init never runs doctor and never spawns** (KB-INV-8). With routing wanted, it recovers the remembered port (init has no `--port`), writes the routing config through `buildRoutingConfigJson` (a write failure forces `proxyEnabled=false`), runs `runProxyPreflight` with `buildRealPreflightDeps({ swallowSettingsReadError: true })`, and on success writes `proxy.json enabled:true` with the freshly resolved `binPath` (the heal path for upgrades). On failure it warns, forces `proxyEnabled=false` and writes `proxy.json enabled:false` when the prior state was enabled; with the proxy off at entry, a prior enabled `proxy.json` is marked disabled the same way. Deeper diagnostics (doctor, spawn) live in `devflow proxy --enable` and `--status`. +**Init never runs doctor and never spawns** (KB-INV-8). With routing wanted, it recovers the remembered port (init has no `--port`), writes the routing config through `buildRoutingConfigJson` (a write failure forces `proxyEnabled=false`), runs `runProxyPreflight` with `buildRealPreflightDeps({ swallowSettingsReadError: true })`, and on success writes `proxy.json enabled:true` with the freshly resolved `binPath` (the heal path for upgrades). On failure it warns, forces `proxyEnabled=false` and writes `proxy.json enabled:false` when the prior state was enabled; with the proxy off at entry, a prior enabled `proxy.json` is marked disabled the same way. Deeper diagnostics (doctor, spawn) live in `devflow proxy --enable` and `--status`. Init does not refuse on Code Mode: it only warns (`initCodeModeWarnings`) from the converged flag record and the post-preflight `proxyEnabled`, so the warning describes the final state; the refusal belongs to `proxy --enable` and the flags writes. `init.ts` gates the env strip on `proxyJsonExists()` (explicit `D-STRIP-1` comment): with no file on a machine that never had the proxy, no stripping runs; with the file, its port is passed to `_stripProxyEnvFromObject` as `managedPort`. The `reapplyAgentMapping` call comes after the preflight block (KB-INV-2) and is skipped only when the mapping has no agent entries and the proxy is off (see the agent-config knowledge base). @@ -132,7 +142,7 @@ Hard failures at any step set `process.exitCode = 1` and return (KB-INV-7). Enab | `applyProxyEnv`, `stripProxyEnv` | Pure settings-JSON-string transforms, no mutation | | `applyDisableToSettings`, `applyProxyTeardownToSettings` | Both-operations invariant; unified teardown (D-STRIP-1) | | `addProxyHooks`, `removeProxyHooks`, `hasProxyHooks` | Hook mutation helpers | -| `readProxyEnvState` | One of `ours`, `ours-other-port`, `foreign`, `absent`, for `--status` | +| `readProxyEnvState` | Re-exported from `proxy-state.ts` (where it and `classifyProxyBaseUrl` are defined, so `code-mode.ts` can use them without importing the CLI); one of `ours`, `ours-other-port`, `foreign`, `absent`. Invalid settings JSON still raises, so callers parse first and report malformed settings themselves, as check ④ does | | `formatCodexAuthLine(state, path, now)` | `{ level, msg }`: `warn` when the state is `unreadable`, `info` otherwise; expiry is informational only because the relay refreshes tokens proactively; `AUTH_MODE_MAX_LEN` bounds the rendered auth mode (hostile `~/.codex/auth.json`) | | `formatExternalModelsLine(catalog, logPath)` | Selectable model names, or `unavailable` with the log path | | `realHttpGet(url, timeoutMs)` | Bounded HTTP GET | @@ -187,11 +197,15 @@ There is no override-confirm prompt: the merge is purely additive (Devflow entri - **KB-AP-8** — `resolveProxyBin()` uses `createRequire(import.meta.url)`, the ESM-safe way to resolve CommonJS package paths; `require.resolve('subswitch/package.json')` finds the package relative to devflow's own `node_modules`, not the user's project. - **KB-AP-9** — Reap stub relays with `afterEach`/`onTestFinished`, SIGTERM then SIGKILL, and confirm death with `process.kill(pid, 0)`. The incident: orphaned stub relays accumulated over weeks and produced spurious failures in memory-pipeline and capture-hook tests that were repeatedly misdiagnosed as product defects. +- **KB-AP-11** — `readProxyState` returns `Err` with fixed text (`Cannot read the Devflow proxy state file.` or `Cannot parse the Devflow proxy state file.`), so callers can print it without leaking a path or errno. The fixed texts are pinned only loosely in `tests/proxy-state.test.ts` (ENOENT is Ok, a malformed file does not throw), so keep them stable by hand. A caller that needs "unreadable means on" (the Code Mode reader) checks `!proxy.ok`; one that wants defaults must not treat `Err` as absent. A malformed file is an `Err`, not a silent default, so a hand-damaged `proxy.json` shows up as proxy-on in the Code Mode checks. +- **KB-AP-12** — The gate order in `runEnable` is port, Code Mode signals, spinner, mkdir. `tests/proxy-code-mode.test.ts` pins refusal before writes or the spinner, drift repair, hand-set enable with an absent or corrupt manifest, and signal-reader failure. `tests/write-set-fence.test.ts` has a `proxy --enable` row (`proxy.json` disabled, the manifest flag record with `code-mode` true) expecting exit 1 and no writes; the successful `--enable` stays exempt because the relay it starts writes outside the fence. - Non-fatal everywhere: artifact removal in uninstall and disable, `writeFileAtomicExclusive`'s chmod, and the hook's binPath re-resolution never abort their command. ## Key Files -- `src/core/proxy-state.ts` — `ProxyState` schema and read/write, `isProxyEnabled()`, `proxyJsonExists()`, `resolveProxyBin()` and `RUNTIME_VERSION_RE`, `buildRoutingConfigJson()`, `ROUTING_CONFIG_REJECTED_SUBKEYS` +- `src/core/proxy-state.ts` — `ProxyState` schema and read/write, `isProxyEnabled()`, `proxyJsonExists()`, `classifyProxyBaseUrl()`, `readProxyEnvState()`, `resolveProxyBin()` and `RUNTIME_VERSION_RE`, `buildRoutingConfigJson()`, `ROUTING_CONFIG_REJECTED_SUBKEYS` +- `src/core/code-mode.ts` — the Code Mode predicates, signal reader, blockers and fixed message constants that `runEnable` and `runStatus` call +- `src/core/read-file-bytes.ts` — `readFileBytes`, the bounded regular-file reader behind `readProxyState` - `src/core/codex-auth-inspect.ts` — `inspectCodexAuth()`, `classifyCodexAuthReadError()` - `src/core/fs-atomic.ts` — `writeFileAtomicExclusive()` (mode-preserving), `writeSettingsFileAtomic()` (symlink-following) - `src/cli/commands/proxy.ts` — `proxyCommand`, `runEnable`, `runDisable`, `runStatus` and the seams in the table above @@ -205,6 +219,7 @@ There is no override-confirm prompt: the merge is purely additive (Devflow entri - `.devflow/features/external-model-routing-hook/KNOWLEDGE.md` — the hook that starts the relay on SessionStart, the relay `env -i` allowlist and `scrubChildEnv()` it must stay in sync with - `.devflow/features/external-model-routing-agent-config/KNOWLEDGE.md` — mapping engine, dormancy, agent state, TUI, discovery and cache; the proxy off-switch rules above feed its dormancy semantics +- `.devflow/features/installer-shadowing-wizard-flags/KNOWLEDGE.md` — the Code Mode flag, its predicates and the flags-side refusal that pairs with the proxy enable refusal - `.devflow/features/installer-shadowing/KNOWLEDGE.md` — `resolveSeedFeatures`, manifest-group feature seeding and uninstall artifact cleanup patterns that the proxy extends - `.devflow/features/curation-capture-system-memory-worker/KNOWLEDGE.md` — the memory worker's side of `agents.memory` - `src/core/` and `src/cli/` — all state I/O and pure logic in core, CLI orchestration in cli; the proxy feature is the canonical multi-module example of the split From 15c8fbf8d978978c201e06bce99351e71a8a8692 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 03:12:53 +0200 Subject: [PATCH 11/20] test: cover Code Mode flag guard paths Check that CLI and TUI enables leave both files unchanged when Devflow cannot read the settings env. Check that CLI re-enable succeeds with a warning when Code Mode and the proxy are both on. Task: resolve-batch-a --- tests/flags-cli.test.ts | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/tests/flags-cli.test.ts b/tests/flags-cli.test.ts index 44d80876b..c79fb45a3 100644 --- a/tests/flags-cli.test.ts +++ b/tests/flags-cli.test.ts @@ -269,6 +269,37 @@ describe('flags CLI — createFlagsCommand factory', () => { await expectUnchanged(files); }); + describe.each(['CLI enable', 'TUI save'])('%s', entry => { + it.each([ + { + name: 'a file over the read limit', + bytes: () => Buffer.from(JSON.stringify({ + env: { ANTHROPIC_BASE_URL: relayUrl }, + pad: 'x'.repeat(1024 * 1024), + })), + }, + { + name: 'a file with invalid UTF-8', + bytes: () => Buffer.concat([ + Buffer.from(`{"env":{"ANTHROPIC_BASE_URL":"${relayUrl}"},"pad":"`), + Buffer.from([0xff]), + Buffer.from('"}'), + ]), + }, + ])('refuses $name without changes to either file', async ({ bytes }) => { + const files = await seed({}, {}); + const settingsBytes = bytes(); + await fs.writeFile(files.settingsPath, settingsBytes); + + if (entry === 'CLI enable') await flagsCmd.parseAsync(['--enable', 'code-mode'], { from: 'user' }); + else await runTui({ 'code-mode': true }); + + expectRefusal('Cannot make this change because Devflow could not check the Code Mode and proxy state.'); + expect(await fs.readFile(files.settingsPath)).toEqual(settingsBytes); + expect(await fs.readFile(files.manifestPath)).toEqual(Buffer.from(files.manifestBytes)); + }); + }); + it.each([ { args: ['--disable', 'code-mode'] }, { args: ['--unset', 'code-mode'] }, @@ -334,6 +365,20 @@ describe('flags CLI — createFlagsCommand factory', () => { await expectSaved(true, '1'); }); + it('allows CLI re-enable when Code Mode and the proxy are already on', async () => { + await seed({ 'code-mode': true }, { [codeKey]: '1' }); + await seedProxy(); + + await flagsCmd.parseAsync(['--enable', 'code-mode'], { from: 'user' }); + + await expectSaved(true, '1'); + expect(p.log.error).not.toHaveBeenCalled(); + expect(p.log.success).toHaveBeenCalledOnce(); + expect(vi.mocked(p.log.warn).mock.calls).toEqual([[ + 'Code Mode does not start while the Devflow proxy is on. Run `devflow flags --disable code-mode` or `devflow proxy --disable`.', + ]]); + }); + it('allows an unrelated TUI save when Code Mode and the proxy are already on', async () => { await seed({ 'code-mode': true }, { [codeKey]: '1' }); await seedProxy(); From b4b9e816008adac6bf9c9de508880a1280dacdcc Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 03:13:03 +0200 Subject: [PATCH 12/20] fix(proxy): bound status reads of settings Use the same settings limit for status and enable. Task: resolve-batch-c --- src/cli/commands/proxy.ts | 13 ++----------- src/core/code-mode.ts | 2 +- tests/proxy-code-mode.test.ts | 13 +++++++++++++ 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/cli/commands/proxy.ts b/src/cli/commands/proxy.ts index d19be5c83..dd89e6969 100644 --- a/src/cli/commands/proxy.ts +++ b/src/cli/commands/proxy.ts @@ -44,6 +44,7 @@ import { isProxyOn, isTrafficOn, readCodeModeSignals, + readSettingsEnv, } from '../../core/code-mode.js'; import { syncManifestFeature } from '../../core/manifest.js'; import { readGateManifest } from '../../core/gate-level.js'; @@ -1392,10 +1393,6 @@ export const proxyCommand = new Command('proxy') // ─── Status ─────────────────────────────────────────────────────────────────── -function isSettingsRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - async function runStatus(): Promise { const devflowDir = getDevFlowDirectory(); const claudeDir = getClaudeDirectory(); @@ -1460,13 +1457,7 @@ async function runStatus(): Promise { } // Env state - let env: Record | undefined; - try { - const settingsJson = await fs.readFile(settingsPath, 'utf-8'); - const settings: unknown = JSON.parse(settingsJson); - if (isSettingsRecord(settings) && isSettingsRecord(settings.env)) env = settings.env; - } catch { /* settings unavailable */ } - + const env = await readSettingsEnv(settingsPath); const envState = classifyProxyBaseUrl(env?.ANTHROPIC_BASE_URL, port); const envStateLabels: Record = { 'ours': color.green('set (our relay)'), diff --git a/src/core/code-mode.ts b/src/core/code-mode.ts index 891d9a532..67b65dbfd 100644 --- a/src/core/code-mode.ts +++ b/src/core/code-mode.ts @@ -102,7 +102,7 @@ function isPlainObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } -async function readSettingsEnv(settingsPath: string): Promise { +export async function readSettingsEnv(settingsPath: string): Promise { const bytes = await readFileBytes(settingsPath, MAX_SETTINGS_BYTES); if (bytes === 'absent') return {}; if (typeof bytes === 'string') return undefined; diff --git a/tests/proxy-code-mode.test.ts b/tests/proxy-code-mode.test.ts index 76d7a7834..c7c5db161 100644 --- a/tests/proxy-code-mode.test.ts +++ b/tests/proxy-code-mode.test.ts @@ -178,6 +178,19 @@ describe('proxy --status Code Mode warnings', () => { expect(vi.mocked(p.log.warn).mock.calls).toEqual([[CODE_MODE_PROXY_BLOCKER]]); }); + it('completes status without Code Mode warnings from settings over 1 MiB', async () => { + const settings = JSON.stringify({ + env: { [codeKey]: '1', [trafficKey]: '1', ANTHROPIC_BASE_URL: 'http://127.0.0.1:4142' }, + }); + seedFile('.claude/settings.json', settings.padEnd(1024 * 1024 + 1)); + + await run('--status'); + + expect(p.log.warn).not.toHaveBeenCalled(); + expect(p.log.info).toHaveBeenCalledWith(expect.stringMatching(/^ANTHROPIC_BASE_URL: .*not set/u)); + expect(process.exitCode).toBe(0); + }); + it('uses readable switches even if another manifest field is absent', async () => { seedFile('.devflow/manifest.json', JSON.stringify({ features: { flags: codeOn, proxy: true } })); const before = snapshot(); From eb65b84676507912e4d93042e2324a662c7f36a8 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 03:13:04 +0200 Subject: [PATCH 13/20] docs: state the result of a file close error Explain why a file close error gives an unreadable result. Task: resolve-batch-c --- src/core/read-file-bytes.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/core/read-file-bytes.ts b/src/core/read-file-bytes.ts index 5c4ec4ba0..5197dc385 100644 --- a/src/core/read-file-bytes.ts +++ b/src/core/read-file-bytes.ts @@ -30,6 +30,7 @@ export async function readFileBytes( } return total > opened.size ? 'unreadable' : bytes.subarray(0, total); } finally { + // A close failure returns 'unreadable', the conservative result. await file.close(); } } catch { From e8027c6ad40758b7e0a9675f4100bd92cf18fe4f Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 03:13:04 +0200 Subject: [PATCH 14/20] docs: clarify Code Mode tool call rules State which rules and hooks apply to each tool call. Task: resolve-batch-c --- docs/cli-reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 0669bf34b..5c0575f06 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -509,7 +509,7 @@ All 33 flags by kind and Devflow default: ⁵ `subagent-cache-5m` writes `"5m"`, so subagents write 5-minute prompt-cache entries while the main session keeps the 1-hour TTL of `prompt-caching-1h`. Disabling or uninstalling deletes the key only when it holds `"5m"`. When the key already holds another value (say `"1h"`), `devflow init` and the flags TUI record the flag off and keep your value; `init --reset` writes `"5m"`. -⁶ `code-mode` is experimental and off by default. This change applies to new sessions only. Code Mode does not work with `claude -p`. +⁶ `code-mode` is experimental and off by default. This change applies to new sessions only. Code Mode does not work with `claude -p`. Deny rules, ask rules, and `PreToolUse` hooks still apply to each tool call. - **Blockers.** Code Mode does not start with the Devflow proxy or `disable-nonessential-traffic` on. A custom `ANTHROPIC_BASE_URL`, `apiKeyHelper`, `ANTHROPIC_AUTH_TOKEN`, or OpenTelemetry export also blocks Code Mode. Code Mode with `agent-teams` needs Claude Code v2.1.326 or later. - **User settings only.** Claude Code reads the enable value only from `env` in user settings. A `0` in the shell or in any settings file takes priority. A project setting cannot turn Code Mode on. Devflow checks only local state and the user settings `env`, not shell exports or project settings. From 9beb458e55a85a7d4cb45666963167cdba1d271b Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 03:13:12 +0200 Subject: [PATCH 15/20] test: pin Code Mode and proxy read errors Check that a file at a directory path does not count as absent. Check the fixed proxy errors and the Code Mode message text. Task: resolve-batch-b --- tests/code-mode.test.ts | 20 ++++++++++++++++++++ tests/proxy-state.test.ts | 36 ++++++++++++++++-------------------- 2 files changed, 36 insertions(+), 20 deletions(-) diff --git a/tests/code-mode.test.ts b/tests/code-mode.test.ts index 11624b3c6..78e4ef114 100644 --- a/tests/code-mode.test.ts +++ b/tests/code-mode.test.ts @@ -122,6 +122,14 @@ describe('Code Mode refusals and warnings', () => { expect(codeMode.PROXY_ENABLE_REFUSAL).toContain('devflow flags --disable code-mode'); }); + it.each([ + ['CODE_MODE_USER_VALUE_NOTE', 'your settings override the flag'], + ['CODE_MODE_RECORD_FALSE_NOTE', 'the flag record is off'], + ['CODE_MODE_READ_FAILURE', 'could not check the Code Mode and proxy state'], + ] as const)('includes the reason in %s', (name, reason) => { + expect(codeMode[name]).toContain(reason); + }); + it('does not name the routing runtime in any exported message', () => { for (const value of Object.values(codeMode)) { if (typeof value === 'string') expect(value).not.toMatch(/subswitch/i); @@ -184,6 +192,12 @@ describe('readCodeModeSignals', () => { await expectRefusal(true); }); + it('refuses when the Devflow directory path is a file', async () => { + await fs.rmdir(devflowDir); + await fs.writeFile(devflowDir, 'x'); + await expectRefusal(true); + }); + it.each([ ['http://127.0.0.1:4141', true], ['http://127.0.0.1:4123', true], @@ -215,6 +229,12 @@ describe('readCodeModeSignals', () => { expect(await read()).toMatchObject({ ok: true, value: { env: undefined } }); }); + it('reports unavailable settings when the Claude directory path is a file', async () => { + await fs.rmdir(claudeDir); + await fs.writeFile(claudeDir, 'x'); + expect(await read()).toMatchObject({ ok: true, value: { env: undefined, proxyOn: false } }); + }); + it.skipIf(process.getuid?.() === 0 || process.platform === 'win32')('reports unavailable settings for permission errors', async () => { await writeSettings({ [CODE_ENV]: '1' }); await fs.chmod(settingsPath, 0o000); diff --git a/tests/proxy-state.test.ts b/tests/proxy-state.test.ts index be1c17102..5d1306808 100644 --- a/tests/proxy-state.test.ts +++ b/tests/proxy-state.test.ts @@ -7,7 +7,7 @@ * * Coverage: * - readProxyState: ENOENT → default disabled state (TEST-2) - * - readProxyState: malformed JSON → tolerant default, no throw (TEST-2) + * - readProxyState: unreadable state or invalid JSON → fixed error (TEST-2) * - writeProxyState → readProxyState round-trip (TEST-2) * - Tolerant field parsing: wrong-typed fields self-heal to defaults (TEST-2) * - buildRoutingConfigJson: port-only shape — no injected anthropic block (AC-C4) @@ -91,27 +91,23 @@ describe('readProxyState — missing file', () => { }); // --------------------------------------------------------------------------- -// readProxyState — malformed JSON (TEST-2) +// readProxyState — read and parse errors (TEST-2) // --------------------------------------------------------------------------- -describe('readProxyState — malformed JSON', () => { - it('returns ok with default state for malformed JSON input', async () => { - await fs.writeFile(path.join(tmpDir, 'proxy.json'), 'not-json{{{', 'utf-8'); - // Should not throw; should return a Result - let result: Awaited>; - expect(async () => { - result = await readProxyState(tmpDir); - }).not.toThrow(); - result = await readProxyState(tmpDir); - // Must return an Err (parse error is surfaced as Err, not a throw) - // The implementation returns Err for JSON.parse failures that are not ENOENT - expect(typeof result.ok).toBe('boolean'); - }); - - it('does not throw for malformed JSON — Result returned instead', async () => { - await fs.writeFile(path.join(tmpDir, 'proxy.json'), '{ "enabled": true, >>>bad<<<', 'utf-8'); - // The key requirement: no exception escapes readProxyState - await expect(readProxyState(tmpDir)).resolves.toBeDefined(); +describe('readProxyState — read and parse errors', () => { + const readError = 'Cannot read the Devflow proxy state file.'; + const proxyJson = (dir: string) => path.join(dir, 'proxy.json'); + + it.each([ + ['invalid JSON', '.', (dir: string) => fs.writeFile(proxyJson(dir), '{'), + 'Cannot parse the Devflow proxy state file.'], + ['a directory at proxy.json', '.', (dir: string) => fs.mkdir(proxyJson(dir)), readError], + ['a file over the read limit', '.', (dir: string) => fs.writeFile(proxyJson(dir), '{}'.padEnd(1024 * 1024 + 1)), readError], + ['a file at the Devflow directory path', 'not-a-dir', (dir: string) => fs.writeFile(dir, 'x'), readError], + ] as const)('returns a fixed error for %s', async (_input, subpath, arrange, error) => { + const devflowDir = path.join(tmpDir, subpath); + await arrange(devflowDir); + expect(await readProxyState(devflowDir)).toStrictEqual({ ok: false, error }); }); }); From 6feb6b7d62c0ace78e291a28c8dd22399a163d65 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Thu, 19 Nov 2026 03:49:30 +0200 Subject: [PATCH 16/20] docs(knowledge): update external-model-routing feature knowledge base --- .devflow/features/external-model-routing/KNOWLEDGE.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.devflow/features/external-model-routing/KNOWLEDGE.md b/.devflow/features/external-model-routing/KNOWLEDGE.md index ac2cd3026..ea9578743 100644 --- a/.devflow/features/external-model-routing/KNOWLEDGE.md +++ b/.devflow/features/external-model-routing/KNOWLEDGE.md @@ -35,7 +35,7 @@ updated: 2026-11-19 - **KB-INV-9** `--port` has no commander default: omission means the remembered port in `proxy.json` wins. - **KB-INV-10** The Codex JWT is decoded for display only: never signature-verified, no token material returned, the account id truncated. - **KB-INV-11** `proxy --enable` refuses (exit 1, nothing written) while Code Mode is on, and also when the Code Mode signals cannot be read (settings unparseable or unreadable); disable and every turn-off path are never blocked by Code Mode. -- **KB-INV-12** `proxy --status` prints Code Mode blocker lines only while Code Mode is on, as warnings after the `ANTHROPIC_BASE_URL` line, from the shared predicates in `code-mode.ts`; it never prints settings values. +- **KB-INV-12** `proxy --status` prints Code Mode blocker lines only while Code Mode is on, as warnings after the `ANTHROPIC_BASE_URL` line, from the shared predicates in `code-mode.ts`; it never prints settings values. It reads `settings.json` only through `readSettingsEnv` (bounded reader, never a bare `fs.readFile`): an unreadable or oversize file gives no env, so the URL shows as not set and no blocker line comes from that file. - **KB-INV-13** `readProxyState` returns the default disabled state only for an absent file; an unreadable, oversize, non-regular, non-directory-parent or unparseable file is an `Err` with fixed text, and the Code Mode signal reader counts that `Err` as the proxy being on. ## Overview @@ -96,7 +96,7 @@ Hard failures at any step set `process.exitCode = 1` and return (KB-INV-7). Enab ### Status Code Mode lines -`runStatus` reads the manifest with the raw `readGateManifest` and takes the flag record and manifest proxy switch from `codeModeManifestSignals` (an unrelated manifest defect does not erase a readable switch). After the `ANTHROPIC_BASE_URL` line it prints `codeModeBlockers(...)` as warnings, fed by `isCodeModeOn`, `isTrafficOn` and `isProxyOn`. The proxy signal there is `proxy.json` enabled or unreadable, the manifest switch, or a relay URL on any port (`ours` or `ours-other-port`, from `classifyProxyBaseUrl`). With Code Mode off, a proxy that is on prints nothing extra. Status reads `settings.json` itself, so a missing or broken file leaves `env` undefined and the blockers fall back to the record. +`runStatus` reads the manifest with the raw `readGateManifest` and takes the flag record and manifest proxy switch from `codeModeManifestSignals` (an unrelated manifest defect does not erase a readable switch). After the `ANTHROPIC_BASE_URL` line it prints `codeModeBlockers(...)` as warnings, fed by `isCodeModeOn`, `isTrafficOn` and `isProxyOn`. The proxy signal there is `proxy.json` enabled or unreadable, the manifest switch, or a relay URL on any port (`ours` or `ours-other-port`, from `classifyProxyBaseUrl`). With Code Mode off, a proxy that is on prints nothing extra. Status reads `settings.json` through `readSettingsEnv`, the same bounded reader (`MAX_SETTINGS_BYTES` cap) that `readCodeModeSignals` uses: an absent file gives an empty env, and an unreadable, oversize, non-object or unparseable file leaves `env` undefined. The URL then shows as not set, and the blockers fall back to the manifest record and the proxy signals. `tests/proxy-code-mode.test.ts` pins an oversize settings file: status ends with exit 0, no warnings and a not-set URL line. ### Settings teardown @@ -197,15 +197,15 @@ There is no override-confirm prompt: the merge is purely additive (Devflow entri - **KB-AP-8** — `resolveProxyBin()` uses `createRequire(import.meta.url)`, the ESM-safe way to resolve CommonJS package paths; `require.resolve('subswitch/package.json')` finds the package relative to devflow's own `node_modules`, not the user's project. - **KB-AP-9** — Reap stub relays with `afterEach`/`onTestFinished`, SIGTERM then SIGKILL, and confirm death with `process.kill(pid, 0)`. The incident: orphaned stub relays accumulated over weeks and produced spurious failures in memory-pipeline and capture-hook tests that were repeatedly misdiagnosed as product defects. -- **KB-AP-11** — `readProxyState` returns `Err` with fixed text (`Cannot read the Devflow proxy state file.` or `Cannot parse the Devflow proxy state file.`), so callers can print it without leaking a path or errno. The fixed texts are pinned only loosely in `tests/proxy-state.test.ts` (ENOENT is Ok, a malformed file does not throw), so keep them stable by hand. A caller that needs "unreadable means on" (the Code Mode reader) checks `!proxy.ok`; one that wants defaults must not treat `Err` as absent. A malformed file is an `Err`, not a silent default, so a hand-damaged `proxy.json` shows up as proxy-on in the Code Mode checks. +- **KB-AP-11** — `readProxyState` returns `Err` with fixed text (`Cannot read the Devflow proxy state file.` or `Cannot parse the Devflow proxy state file.`), so callers can print it without leaking a path or errno. `tests/proxy-state.test.ts` pins the fixed texts with literals: the parse text for invalid JSON, and the read text for a directory at `proxy.json`, an oversize file and a file at the Devflow directory path. Change a text only with that test. A caller that needs "unreadable means on" (the Code Mode reader) checks `!proxy.ok`; one that wants defaults must not treat `Err` as absent. A malformed file is an `Err`, not a silent default, so a hand-damaged `proxy.json` shows up as proxy-on in the Code Mode checks. - **KB-AP-12** — The gate order in `runEnable` is port, Code Mode signals, spinner, mkdir. `tests/proxy-code-mode.test.ts` pins refusal before writes or the spinner, drift repair, hand-set enable with an absent or corrupt manifest, and signal-reader failure. `tests/write-set-fence.test.ts` has a `proxy --enable` row (`proxy.json` disabled, the manifest flag record with `code-mode` true) expecting exit 1 and no writes; the successful `--enable` stays exempt because the relay it starts writes outside the fence. - Non-fatal everywhere: artifact removal in uninstall and disable, `writeFileAtomicExclusive`'s chmod, and the hook's binPath re-resolution never abort their command. ## Key Files - `src/core/proxy-state.ts` — `ProxyState` schema and read/write, `isProxyEnabled()`, `proxyJsonExists()`, `classifyProxyBaseUrl()`, `readProxyEnvState()`, `resolveProxyBin()` and `RUNTIME_VERSION_RE`, `buildRoutingConfigJson()`, `ROUTING_CONFIG_REJECTED_SUBKEYS` -- `src/core/code-mode.ts` — the Code Mode predicates, signal reader, blockers and fixed message constants that `runEnable` and `runStatus` call -- `src/core/read-file-bytes.ts` — `readFileBytes`, the bounded regular-file reader behind `readProxyState` +- `src/core/code-mode.ts` — the Code Mode predicates, `readSettingsEnv` (bounded settings env reader), signal reader, blockers and fixed message constants that `runEnable` and `runStatus` call +- `src/core/read-file-bytes.ts` — `readFileBytes`, the bounded regular-file reader behind `readProxyState` and `readSettingsEnv`; any failure, a failed close included, gives `unreadable` (the conservative result) - `src/core/codex-auth-inspect.ts` — `inspectCodexAuth()`, `classifyCodexAuthReadError()` - `src/core/fs-atomic.ts` — `writeFileAtomicExclusive()` (mode-preserving), `writeSettingsFileAtomic()` (symlink-following) - `src/cli/commands/proxy.ts` — `proxyCommand`, `runEnable`, `runDisable`, `runStatus` and the seams in the table above From 3070d8bf4fbd03b0736b1d6440b1add3819eae37 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Sun, 22 Nov 2026 20:40:40 +0200 Subject: [PATCH 17/20] test(reader): check file handle failures Test that the reader skips the read and closes the handle if it exceeds the limit. Test that a failed close discards the bytes. Task: resolve-b --- tests/read-file-bytes.test.ts | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 tests/read-file-bytes.test.ts diff --git a/tests/read-file-bytes.test.ts b/tests/read-file-bytes.test.ts new file mode 100644 index 000000000..2cb482e4f --- /dev/null +++ b/tests/read-file-bytes.test.ts @@ -0,0 +1,43 @@ +import { promises as fs } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it, vi, type TestContext } from 'vitest'; +import { readFileBytes } from '../src/core/read-file-bytes.js'; + +const MAX_BYTES = 5; + +async function openFixture(onTestFinished: TestContext['onTestFinished']) { + const dir = await fs.mkdtemp(join(tmpdir(), 'read-file-bytes-')); + onTestFinished(() => fs.rm(dir, { recursive: true })); + const filePath = join(dir, 'file'); + await fs.writeFile(filePath, 'abc'); + const handle = await fs.open(filePath, 'r'); + onTestFinished(handle.close.bind(handle)); + vi.spyOn(fs, 'open').mockResolvedValueOnce(handle); + return { dir, filePath, handle }; +} + +describe('readFileBytes', () => { + it('closes without a read if the open handle exceeds the byte limit', async ({ onTestFinished }) => { + const { dir, filePath, handle } = await openFixture(onTestFinished); + const largerFile = join(dir, 'larger'); + await fs.writeFile(largerFile, 'abcdef'); + vi.spyOn(handle, 'stat').mockResolvedValueOnce(await fs.stat(largerFile)); + const read = vi.spyOn(handle, 'read'); + const close = vi.spyOn(handle, 'close'); + + expect(await readFileBytes(filePath, MAX_BYTES)).toBe('unreadable'); + expect(read).not.toHaveBeenCalled(); + expect(close).toHaveBeenCalledTimes(1); + }); + + it('returns unreadable if close fails after a successful read', async ({ onTestFinished }) => { + const { filePath, handle } = await openFixture(onTestFinished); + const read = vi.spyOn(handle, 'read'); + const close = vi.spyOn(handle, 'close').mockRejectedValueOnce(new Error('close failed')); + + expect(await readFileBytes(filePath, MAX_BYTES)).toBe('unreadable'); + expect(read).toHaveResolvedWith(expect.objectContaining({ bytesRead: 3 })); + expect(close).toHaveBeenCalledTimes(1); + }); +}); From 6097b5c920daa043c4cedb7080f91c1ca9726564 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Sun, 22 Nov 2026 20:41:11 +0200 Subject: [PATCH 18/20] fix(proxy): reject non-object state roots Use the fixed parse error for non-object proxy state. Keep default values for missing or invalid object fields. Task: resolve-c --- .../features/external-model-routing/KNOWLEDGE.md | 4 ++-- src/core/proxy-state.ts | 16 ++++++++++++---- tests/proxy-state.test.ts | 8 ++++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/.devflow/features/external-model-routing/KNOWLEDGE.md b/.devflow/features/external-model-routing/KNOWLEDGE.md index ea9578743..062cced62 100644 --- a/.devflow/features/external-model-routing/KNOWLEDGE.md +++ b/.devflow/features/external-model-routing/KNOWLEDGE.md @@ -36,7 +36,7 @@ updated: 2026-11-19 - **KB-INV-10** The Codex JWT is decoded for display only: never signature-verified, no token material returned, the account id truncated. - **KB-INV-11** `proxy --enable` refuses (exit 1, nothing written) while Code Mode is on, and also when the Code Mode signals cannot be read (settings unparseable or unreadable); disable and every turn-off path are never blocked by Code Mode. - **KB-INV-12** `proxy --status` prints Code Mode blocker lines only while Code Mode is on, as warnings after the `ANTHROPIC_BASE_URL` line, from the shared predicates in `code-mode.ts`; it never prints settings values. It reads `settings.json` only through `readSettingsEnv` (bounded reader, never a bare `fs.readFile`): an unreadable or oversize file gives no env, so the URL shows as not set and no blocker line comes from that file. -- **KB-INV-13** `readProxyState` returns the default disabled state only for an absent file; an unreadable, oversize, non-regular, non-directory-parent or unparseable file is an `Err` with fixed text, and the Code Mode signal reader counts that `Err` as the proxy being on. +- **KB-INV-13** `readProxyState` accepts an absent file as disabled. A present file must pass the read limits and contain a JSON object. Missing or invalid fields in an object use defaults. The Code Mode signal reader counts an `Err` from `readProxyState` as proxy-on. ## Overview @@ -57,7 +57,7 @@ The routing runtime is an internal package (`subswitch`, exact-pinned in `packag | File | Role | |------|------| -| `~/.devflow/proxy.json` | Runtime authority, read by `readProxyState()` through the bounded `readFileBytes` (regular file only, size-capped by `MAX_PROXY_STATE_BYTES`; read failures return fixed error text, KB-AP-11), then field-tolerant parsed. Only an absent file yields the default disabled state (KB-AP-10, KB-INV-13). Fields: `enabled`, `port`, `binPath`, `configPath`, `resolvedAt`, `devflowVersion`. | +| `~/.devflow/proxy.json` | Runtime authority. `readProxyState()` uses `readFileBytes` with `MAX_PROXY_STATE_BYTES`. A file that fails the read limits or does not contain a JSON object returns fixed error text (KB-AP-11, KB-INV-13). An absent file returns a default disabled state (KB-AP-10). Fields: `enabled`, `port`, `binPath`, `configPath`, `resolvedAt`, `devflowVersion`. | | `~/.devflow/proxy-routing.json` | Routing config from `buildRoutingConfigJson(port, existingContent?)`, written before preflight on enable (contract below). | | `manifest.features.proxy` | Init/uninstall authority. `resolveSeedFeatures` seeds it from `manifest?.features.proxy ?? FEATURE_DEFAULTS.proxy`; `--reset` seeds `false`. | | `proxy.pid`, `logs/proxy.log`, `.proxy-spawn.lock` | Relay pid record (best-effort), relay log, spawn lock. Handled in the hook knowledge base. | diff --git a/src/core/proxy-state.ts b/src/core/proxy-state.ts index ad9f557f8..776d7c370 100644 --- a/src/core/proxy-state.ts +++ b/src/core/proxy-state.ts @@ -66,9 +66,16 @@ export interface ProxyState { // Read / write // --------------------------------------------------------------------------- +const PROXY_STATE_PARSE_ERROR = 'Cannot parse the Devflow proxy state file.'; + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + /** - * Read proxy state from ~/.devflow/proxy.json with tolerant parsing. - * Returns a default disabled state when the file is missing. + * Read proxy state from ~/.devflow/proxy.json. + * Require a JSON object and use defaults for missing or invalid fields. + * Return a default disabled state when the file is missing. */ export async function readProxyState(devflowDir: string): Promise> { const statePath = join(devflowDir, 'proxy.json'); @@ -80,7 +87,8 @@ export async function readProxyState(devflowDir: string): Promise; + const data: unknown = JSON.parse(content); + if (!isPlainObject(data)) return Err(PROXY_STATE_PARSE_ERROR); // Tolerant parse: provide safe defaults for missing/invalid fields. const state: ProxyState = { @@ -94,7 +102,7 @@ export async function readProxyState(devflowDir: string): Promise { await arrange(devflowDir); expect(await readProxyState(devflowDir)).toStrictEqual({ ok: false, error }); }); + + it.each(['[]', '5'])('returns a fixed parse error for JSON root %s', async (content) => { + await fs.writeFile(proxyJson(tmpDir), content); + expect(await readProxyState(tmpDir)).toStrictEqual({ + ok: false, + error: 'Cannot parse the Devflow proxy state file.', + }); + }); }); // --------------------------------------------------------------------------- From d2943fb5da8fa262c608c1ce0dd4167d8b390cab Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Sun, 22 Nov 2026 20:43:07 +0200 Subject: [PATCH 19/20] fix(flags): refuse unreadable settings Leave both files unchanged if the flags command cannot read user settings. Keep flag writes that do not turn Code Mode on independent of its signal check. Point users to their Claude Code user settings when the check fails. Task: resolve-a --- src/cli/commands/flags.ts | 27 ++++++------ src/core/code-mode.ts | 4 +- tests/code-mode.test.ts | 2 +- tests/flags-cli.test.ts | 90 ++++++++++++++++++++++++++++++++++++--- 4 files changed, 98 insertions(+), 25 deletions(-) diff --git a/src/cli/commands/flags.ts b/src/cli/commands/flags.ts index 1a7569e08..1d56a9084 100644 --- a/src/cli/commands/flags.ts +++ b/src/cli/commands/flags.ts @@ -17,7 +17,6 @@ */ import { Command } from 'commander'; -import { promises as fs } from 'fs'; import * as path from 'path'; import * as p from '@clack/prompts'; import color from 'picocolors'; @@ -43,6 +42,7 @@ import { import { CODE_MODE_NEW_SESSIONS_SUFFIX, CODE_MODE_READ_FAILURE, + MAX_SETTINGS_BYTES, codeModeBlockers, codeModeRefusal, codeModeStatusNotes, @@ -55,6 +55,7 @@ import { import type { CodeModeBlockerState, CodeModeSignals } from '../../core/code-mode.js'; import { readManifest, writeManifest } from '../../core/manifest.js'; import { writeSettingsFileAtomic } from '../../core/fs-atomic.js'; +import { readFileBytes } from '../../core/read-file-bytes.js'; import { sanitizeCell } from '../tui/cells.js'; // Static imports for pure view-state helpers — no TTY machinery. // runFlagsTui stays lazily imported in handleBare to keep TTY module out of @@ -97,25 +98,21 @@ function logFlagSuccess(id: string, line: string): void { p.log.success(id === 'code-mode' ? `${line}. ${CODE_MODE_NEW_SESSIONS_SUFFIX}` : line); } -/** - * Read and parse settings.json. - * ENOENT → returns `{ content: '{}', ok: true }`. - * Malformed JSON → returns `{ ok: false, reason: string }`. - * - * NEVER silently falls back to '{}' on malformed JSON — that would clobber the - * user's settings. The caller must abort with exit code 1 on !ok. - */ +/** Initialize only when settings.json is absent. Refuse input the writer cannot preserve. */ async function readSettingsSafe( settingsPath: string, ): Promise<{ ok: true; content: string } | { ok: false; reason: string }> { + const bytes = await readFileBytes(settingsPath, MAX_SETTINGS_BYTES); + if (bytes === 'absent') return { ok: true, content: '{}' }; + if (typeof bytes === 'string') { + return { ok: false, reason: 'Cannot read settings.json. Check access, file type, and size (1 MiB limit).' }; + } + let raw: string; try { - raw = await fs.readFile(settingsPath, 'utf-8'); - } catch (err) { - if ((err as NodeJS.ErrnoException).code === 'ENOENT') { - return { ok: true, content: '{}' }; - } - return { ok: false, reason: `Cannot read settings.json: ${(err as Error).message}` }; + raw = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); + } catch { + return { ok: false, reason: 'settings.json is not valid UTF-8. Fix the file before you change flags.' }; } // REL-M2 + PERF-L4: single parse — validate root shape and return raw string. diff --git a/src/core/code-mode.ts b/src/core/code-mode.ts index 67b65dbfd..2f5303bed 100644 --- a/src/core/code-mode.ts +++ b/src/core/code-mode.ts @@ -7,7 +7,7 @@ import type { ProxyEnvState, Result } from './proxy-state.js'; export const CODE_MODE_ENABLE_REFUSAL = 'Cannot enable Code Mode while the Devflow proxy is on. Run `devflow proxy --disable` first.'; export const PROXY_ENABLE_REFUSAL = 'Cannot enable the Devflow proxy while Code Mode is on. Run `devflow flags --disable code-mode` first.'; -export const CODE_MODE_READ_FAILURE = 'Cannot make this change because Devflow could not check the Code Mode and proxy state.'; +export const CODE_MODE_READ_FAILURE = 'Cannot make this change because Devflow could not check the Code Mode and proxy state. Check your Claude Code user settings.json.'; export const CODE_MODE_PROXY_BLOCKER = 'Code Mode does not start while the Devflow proxy is on. Run `devflow flags --disable code-mode` or `devflow proxy --disable`.'; export const CODE_MODE_TRAFFIC_BLOCKER = 'Code Mode does not start while disable-nonessential-traffic is on. Run `devflow flags --disable code-mode`.'; export const CODE_MODE_USER_VALUE_NOTE = 'Code Mode is off because your settings override the flag.'; @@ -16,7 +16,7 @@ export const CODE_MODE_NEW_SESSIONS_SUFFIX = 'This change applies to new session const codeModeFlag = findFlag('code-mode'); const trafficFlag = findFlag('disable-nonessential-traffic'); -const MAX_SETTINGS_BYTES = 1024 * 1024; +export const MAX_SETTINGS_BYTES = 1024 * 1024; type RawRecord = Readonly>; diff --git a/tests/code-mode.test.ts b/tests/code-mode.test.ts index 78e4ef114..9ee4d3171 100644 --- a/tests/code-mode.test.ts +++ b/tests/code-mode.test.ts @@ -125,7 +125,7 @@ describe('Code Mode refusals and warnings', () => { it.each([ ['CODE_MODE_USER_VALUE_NOTE', 'your settings override the flag'], ['CODE_MODE_RECORD_FALSE_NOTE', 'the flag record is off'], - ['CODE_MODE_READ_FAILURE', 'could not check the Code Mode and proxy state'], + ['CODE_MODE_READ_FAILURE', 'could not check the Code Mode and proxy state. Check your Claude Code user settings.json.'], ] as const)('includes the reason in %s', (name, reason) => { expect(codeMode[name]).toContain(reason); }); diff --git a/tests/flags-cli.test.ts b/tests/flags-cli.test.ts index c79fb45a3..81447c72e 100644 --- a/tests/flags-cli.test.ts +++ b/tests/flags-cli.test.ts @@ -51,7 +51,7 @@ import * as os from 'os'; import { PassThrough } from 'stream'; import { createFlagsCommand, applyTuiResult } from '../src/cli/commands/flags.js'; import { makeManifest } from './helpers.js'; -import type { FlagsRecord } from '../src/core/flags.js'; +import { FLAG_REGISTRY, neutralValueOf, type FlagsRecord } from '../src/core/flags.js'; import { readManifest } from '../src/core/manifest.js'; import * as codeMode from '../src/core/code-mode.js'; // Direct import from terminal.js (not index.js) so the REL-M3 mock of index.js @@ -269,7 +269,70 @@ describe('flags CLI — createFlagsCommand factory', () => { await expectUnchanged(files); }); - describe.each(['CLI enable', 'TUI save'])('%s', entry => { + it.each([ + { name: '--disable code-mode', args: ['--disable', 'code-mode'], codeOn: false, lspOn: false }, + { name: '--enable lsp', args: ['--enable', 'lsp'], codeOn: true, lspOn: true }, + { name: 'an unrelated TUI save', args: [], codeOn: true, lspOn: true }, + ])('persists $name when the Code Mode check cannot read its signals', async ({ args, codeOn, lspOn }) => { + const neutralFlags: FlagsRecord = Object.fromEntries(FLAG_REGISTRY.map(flag => [flag.id, neutralValueOf(flag)] as const)); + const files = await seed({ ...neutralFlags, 'code-mode': true }, { [codeKey]: '1' }); + const readSignals = vi.fn().mockResolvedValue({ + ok: true, value: { env: undefined, record: null, proxyOn: false }, + }); + vi.doMock('../src/core/code-mode.js', async importOriginal => ({ + ...await importOriginal(), + readCodeModeSignals: readSignals, + })); + vi.resetModules(); + try { + if (args.length === 0) await runTui({ lsp: true }); + else { + const { createFlagsCommand } = await import('../src/cli/commands/flags.js'); + await createFlagsCommand().parseAsync(args, { from: 'user' }); + } + } finally { + vi.doUnmock('../src/core/code-mode.js'); + vi.resetModules(); + } + + expect(readSignals).toHaveBeenCalled(); + expect(process.exitCode).toBe(0); + expect(p.log.error).not.toHaveBeenCalled(); + expect(parseFlagsRecord(await fs.readFile(files.manifestPath, 'utf-8'))).toEqual({ + ...neutralFlags, 'code-mode': codeOn, lsp: lspOn, + }); + expect(parseSettings(await fs.readFile(files.settingsPath, 'utf-8'))).toEqual({ + env: { + ANTHROPIC_AUTH_TOKEN: fixtureAuth, + ...(codeOn ? { [codeKey]: '1' } : {}), + ...(lspOn ? { ENABLE_LSP_TOOL: 'true' } : {}), + }, + apiKeyHelper: fixtureHelper, + }); + }); + + describe.each([ + { name: 'CLI Code Mode enable', args: ['--enable', 'code-mode'], afterLaunch: false, + message: 'Cannot make this change because Devflow could not check the Code Mode and proxy state. Check your Claude Code user settings.json.' }, + { name: 'CLI unrelated enable', args: ['--enable', 'lsp'], afterLaunch: false }, + { name: 'TUI launch', args: [], afterLaunch: false }, + { name: 'TUI save', args: [], afterLaunch: true }, + ])('$name', ({ args, afterLaunch, message }) => { + const readError = 'Cannot read settings.json. Check access, file type, and size (1 MiB limit).'; + + async function tryWrite(replaceSettings: () => Promise) { + if (!afterLaunch) await replaceSettings(); + if (args.length > 0) { + await flagsCmd.parseAsync(args, { from: 'user' }); + } else { + const beforeSave = vi.fn(async () => { + if (afterLaunch) await replaceSettings(); + }); + await runTui({ lsp: true }, beforeSave); + expect(beforeSave).toHaveBeenCalledTimes(afterLaunch ? 1 : 0); + } + } + it.each([ { name: 'a file over the read limit', @@ -277,6 +340,7 @@ describe('flags CLI — createFlagsCommand factory', () => { env: { ANTHROPIC_BASE_URL: relayUrl }, pad: 'x'.repeat(1024 * 1024), })), + error: readError, }, { name: 'a file with invalid UTF-8', @@ -285,19 +349,31 @@ describe('flags CLI — createFlagsCommand factory', () => { Buffer.from([0xff]), Buffer.from('"}'), ]), + error: 'settings.json is not valid UTF-8. Fix the file before you change flags.', }, - ])('refuses $name without changes to either file', async ({ bytes }) => { + ])('refuses $name without changes to either file', async ({ bytes, error }) => { const files = await seed({}, {}); const settingsBytes = bytes(); - await fs.writeFile(files.settingsPath, settingsBytes); - if (entry === 'CLI enable') await flagsCmd.parseAsync(['--enable', 'code-mode'], { from: 'user' }); - else await runTui({ 'code-mode': true }); + await tryWrite(() => fs.writeFile(files.settingsPath, settingsBytes)); - expectRefusal('Cannot make this change because Devflow could not check the Code Mode and proxy state.'); + expectRefusal(message ?? error); expect(await fs.readFile(files.settingsPath)).toEqual(settingsBytes); expect(await fs.readFile(files.manifestPath)).toEqual(Buffer.from(files.manifestBytes)); }); + + it('refuses a directory in place of settings.json without changes to either path', async () => { + const files = await seed({}, {}); + + await tryWrite(async () => { + await fs.unlink(files.settingsPath); + await fs.mkdir(files.settingsPath); + }); + + expectRefusal(message ?? readError); + expect(await fs.readdir(files.settingsPath)).toEqual([]); + expect(await fs.readFile(files.manifestPath)).toEqual(Buffer.from(files.manifestBytes)); + }); }); it.each([ From d508c9ce2ec9328e82a15676d56b64b201a119f0 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Sun, 22 Nov 2026 20:44:02 +0200 Subject: [PATCH 20/20] docs(changelog): note the flags settings-file limit --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8cbf9184..63d6dffbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **Experimental Code Mode flag.** Use `devflow flags --enable code-mode` for direct Claude Code sessions. The flag is off by default. This change applies to new sessions only. Code Mode does not start while the Devflow proxy or `disable-nonessential-traffic` is on. +- **Experimental Code Mode flag.** Use `devflow flags --enable code-mode` for direct Claude Code sessions. The flag is off by default. This change applies to new sessions only. Code Mode does not start while the Devflow proxy or `disable-nonessential-traffic` is on. `devflow flags` does not change a user `settings.json` that is over 1 MiB or is not valid UTF-8, and leaves the file as it is. - A local test plan can specify ` [expect-exit: ]` (1 to 125) for a planned failure. A local PASS needs the expected exit, which defaults to 0. A file claim applies only if its saved expected exit matches the test plan. Old claim lines without `expect-exit:` parse with expected exit 0 and apply only to TPs without clauses; with clauses, they give UNVERIFIED, not FAILED. ---