harness-reflex 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +103 -23
- package/USER_GUIDE.md +121 -43
- package/dist/adapters/agy.js +1 -1
- package/dist/adapters/agy.js.map +1 -1
- package/dist/adapters/codex.d.ts +133 -4
- package/dist/adapters/codex.js +325 -2
- package/dist/adapters/codex.js.map +1 -1
- package/dist/backend/defaults.d.ts +31 -0
- package/dist/backend/defaults.js +32 -0
- package/dist/backend/defaults.js.map +1 -0
- package/dist/backend/jev.js +6 -5
- package/dist/backend/jev.js.map +1 -1
- package/dist/backend/mock.d.ts +12 -1
- package/dist/backend/mock.js +34 -0
- package/dist/backend/mock.js.map +1 -1
- package/dist/backend/simple-jev.js +5 -4
- package/dist/backend/simple-jev.js.map +1 -1
- package/dist/backend/types.d.ts +34 -0
- package/dist/backend/types.js.map +1 -1
- package/dist/cli/index.js +5 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/core/closing.d.ts +90 -0
- package/dist/core/closing.js +111 -0
- package/dist/core/closing.js.map +1 -0
- package/dist/core/evidence.d.ts +119 -0
- package/dist/core/evidence.js +209 -0
- package/dist/core/evidence.js.map +1 -0
- package/dist/core/judge.d.ts +221 -0
- package/dist/core/judge.js +251 -0
- package/dist/core/judge.js.map +1 -0
- package/dist/core/orchestrate-closing.d.ts +237 -0
- package/dist/core/orchestrate-closing.js +250 -0
- package/dist/core/orchestrate-closing.js.map +1 -0
- package/dist/core/orchestrate-correction.d.ts +209 -0
- package/dist/core/orchestrate-correction.js +141 -0
- package/dist/core/orchestrate-correction.js.map +1 -0
- package/dist/core/orchestrate-host.d.ts +225 -0
- package/dist/core/orchestrate-host.js +80 -0
- package/dist/core/orchestrate-host.js.map +1 -0
- package/dist/core/orchestrate-stagnation.d.ts +259 -0
- package/dist/core/orchestrate-stagnation.js +270 -0
- package/dist/core/orchestrate-stagnation.js.map +1 -0
- package/dist/core/orchestrate.d.ts +357 -0
- package/dist/core/orchestrate.js +418 -0
- package/dist/core/orchestrate.js.map +1 -0
- package/dist/core/policy.d.ts +122 -0
- package/dist/core/policy.js +102 -0
- package/dist/core/policy.js.map +1 -0
- package/dist/core/prune-plan.d.ts +141 -0
- package/dist/core/prune-plan.js +390 -0
- package/dist/core/prune-plan.js.map +1 -0
- package/dist/core/score.d.ts +2 -2
- package/dist/core/score.js.map +1 -1
- package/dist/core/text.d.ts +36 -0
- package/dist/core/text.js +66 -0
- package/dist/core/text.js.map +1 -0
- package/dist/hook/cli.d.ts +9 -0
- package/dist/hook/cli.js +52 -0
- package/dist/hook/cli.js.map +1 -0
- package/dist/hook/contract.d.ts +125 -0
- package/dist/hook/contract.js +159 -0
- package/dist/hook/contract.js.map +1 -0
- package/dist/hook/decision.d.ts +97 -0
- package/dist/hook/decision.js +955 -0
- package/dist/hook/decision.js.map +1 -0
- package/dist/hook/memory-store.d.ts +81 -0
- package/dist/hook/memory-store.js +157 -0
- package/dist/hook/memory-store.js.map +1 -0
- package/dist/hook/payload.d.ts +55 -0
- package/dist/hook/payload.js +129 -0
- package/dist/hook/payload.js.map +1 -0
- package/dist/hook/run.d.ts +48 -0
- package/dist/hook/run.js +218 -0
- package/dist/hook/run.js.map +1 -0
- package/dist/hook/store-port.d.ts +72 -0
- package/dist/hook/store-port.js +2 -0
- package/dist/hook/store-port.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/ports/audit.d.ts +18 -0
- package/dist/ports/audit.js +11 -0
- package/dist/ports/audit.js.map +1 -0
- package/dist/ports/clock.d.ts +14 -0
- package/dist/ports/clock.js +11 -0
- package/dist/ports/clock.js.map +1 -0
- package/dist/ports/decision.d.ts +75 -0
- package/dist/ports/decision.js +2 -0
- package/dist/ports/decision.js.map +1 -0
- package/dist/ports/index.d.ts +14 -0
- package/dist/ports/index.js +2 -0
- package/dist/ports/index.js.map +1 -0
- package/dist/ports/log.d.ts +22 -0
- package/dist/ports/log.js +12 -0
- package/dist/ports/log.js.map +1 -0
- package/dist/ports/state.d.ts +46 -0
- package/dist/ports/state.js +13 -0
- package/dist/ports/state.js.map +1 -0
- package/dist/state/clock.d.ts +40 -0
- package/dist/state/clock.js +43 -0
- package/dist/state/clock.js.map +1 -0
- package/dist/state/file-store.d.ts +340 -0
- package/dist/state/file-store.js +849 -0
- package/dist/state/file-store.js.map +1 -0
- package/dist/state/paths.d.ts +41 -0
- package/dist/state/paths.js +73 -0
- package/dist/state/paths.js.map +1 -0
- package/docs/USER_GUIDE.en.md +79 -36
- package/docs/claude-code.md +281 -0
- package/docs/design/v0.2.0-harness-plugins.md +381 -0
- package/docs/design/v0.3.0-orchestration-unification.md +580 -0
- package/docs/dsh-plugin.md +54 -54
- package/docs/release-checklist-v0.1.0.md +32 -21
- package/docs/release-handbook-porting-notes.md +11 -11
- package/docs/release-handbook.md +55 -30
- package/docs/release-notes-v0.1.0.md +27 -14
- package/docs/release-notes-v0.3.0.md +152 -0
- package/docs/research/claude-code-harness.md +607 -0
- package/docs/research/pi-harness.md +621 -0
- package/package.json +16 -7
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file-store.js","sourceRoot":"","sources":["../../src/state/file-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE5F,yEAAyE;AACzE,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GAAG,IAAI,CAAC;AAC7C,2EAA2E;AAC3E,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAC;AAC/B,2DA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IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC;QAC3C,IAAI,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,oBAAoB;YAAE,OAAO,MAAM,CAAC;QAC3E,MAAM,OAAO,GAAqB;YAChC,GAAG,MAAM;YACT,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE;YAC5B,UAAU,EAAE,CAAC,MAAM,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC;SACpD,CAAC;QACF,IAAI,MAAM,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,oBAAoB;YAAE,OAAO,OAAO,CAAC;QACtG,OAAO,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;IAC5C,CAAC;CACF","sourcesContent":["/**\n * The file-backed session state of the command-hook process.\n *\n * The contract this module implements is design §3: append-only JSONL is the\n * authority, `state.json` is a discardable cache, the lock is an atomic `mkdir`\n * with a five-second staleness rule, and nothing here may block a tool call.\n * When a lock cannot be taken the caller is told so; when a cache file is\n * corrupt it is deleted and rebuilt; when one JSONL line is unreadable it is\n * isolated and the rest of the file is still read.\n *\n * Concurrency assumptions, stated explicitly because they are the whole point:\n * - `events.jsonl` / `ledger.jsonl` lines are each appended with a single write\n * syscall to an `O_APPEND` file descriptor, so interleaving is impossible and\n * a reader never triggers a second write per line.\n * - `state.json` and decision caches are written to a temporary file, fsynced,\n * and renamed into place, so a reader sees the old file or the new one.\n * - A directory (not a file) is the lock: `mkdir` is atomic on every POSIX\n * filesystem the design targets.\n *\n * @module state/file-store\n */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { HookClock } from './clock.js';\nimport { SystemClock } from './clock.js';\nimport { DEFAULT_HARNESS, resolveStateRoot, sessionDirName, sessionHash } from './paths.js';\n\n/** Longest JSONL line this store will append, in bytes (design §3.3). */\nexport const MAX_JSONL_LINE_BYTES = 4 * 1024;\n/** Bad lines read from one file before the file is treated as unusable. */\nexport const MAX_BAD_LINES = 5;\n/** Default lifetime of a session directory, seven days. */\nexport const SESSION_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;\n/** Default cap on one session's retained originals: 32 MiB. */\nexport const MAX_ORIGINAL_BYTES = 32 * 1024 * 1024;\n/** Default staleness of a `lock/` directory before it may be taken over. */\nexport const LOCK_STALE_MS = 5 * 1000;\n/** Version recorded in `meta.json`; kept in step with package.json by hand. */\nexport const HARNESS_STATE_VERSION = '0.1.0-alpha.2';\n/** Tail window for reads, so a large log is never loaded whole. */\nexport const READ_TAIL_BYTES = 256 * 1024;\n\n/** One session's identity, as stored in `meta.json`. */\nexport interface SessionMeta {\n harness: string;\n /** Plaintext session id; the directory name only carries its hash. */\n sessionId: string;\n createdAt: string;\n harnessVersion: string;\n mode: string;\n}\n\n/** The per-turn counters a decision turn spends from. */\nexport interface SessionBudget {\n interventions: number;\n judgmentsTurn: number;\n judgmentsSession: number;\n}\n\n/** The derived cache in `state.json`; never authoritative. */\nexport interface SessionState {\n version: 1;\n turnNo: number;\n appliedSignatures: string[];\n budgets: SessionBudget;\n continues: Record<string, number>;\n updatedAt: string;\n}\n\n/** One line of `events.jsonl`: a tool observation, append-only. */\nexport interface SessionEvent {\n v: 1;\n kind: 'pre' | 'post' | 'failure' | 'stop' | 'session';\n at: number;\n atIso: string;\n turnNo: number;\n tool?: string;\n toolUseId?: string;\n signature?: string;\n failed?: boolean;\n /** Bounded model-facing text of the result, for later evidence assembly. */\n output?: string;\n source?: string;\n /** Present when the observation is also the idempotency commit of a decision. */\n dedupeKey?: string;\n}\n\n/** The ledger vocabulary of the hook surface. */\nexport type HookLedgerType = 'stagnation' | 'prune' | 'gate' | 'closing' | 'noop' | 'error';\n\n/** One line of `ledger.jsonl`: an auditable decision or skip. */\nexport interface HookLedgerRecord {\n id: string;\n timestamp: string;\n type: HookLedgerType;\n harness: string;\n event: string;\n backend: string;\n latencyMs: number;\n dedupeKey: string;\n turnNo: number;\n shadow?: boolean;\n applied?: boolean;\n judged?: boolean;\n tokensSaved?: number;\n originalTokens?: number;\n prunedTokens?: number;\n passed?: boolean;\n isStuck?: boolean;\n skipReason?: string;\n retention?: 'retained' | 'evicted' | 'none';\n details?: Record<string, unknown>;\n}\n\n/** The paths of one ensured session. */\nexport interface SessionPaths {\n dir: string;\n meta: string;\n state: string;\n events: string;\n ledger: string;\n originals: string;\n decisions: string;\n lock: string;\n}\n\n/** What one retention attempt produced. */\nexport interface RetentionResult {\n retained: boolean;\n /** Digest names of older originals evicted to make room. */\n evicted: string[];\n /** Why the new payload was not retained, when it was not. */\n reason?: string;\n}\n\n/** Options of {@link FileStateStore}. */\nexport interface FileStateStoreOptions {\n /** State root; defaults to {@link resolveStateRoot}. */\n root?: string;\n /** Harness tag; defaults to `cc`. */\n harness?: string;\n /** Clock used for timestamps and staleness. */\n clock?: HookClock;\n /** Lock takeover age, default five seconds. */\n lockStaleMs?: number;\n /** Session directory lifetime, default seven days. */\n sessionRetentionMs?: number;\n /** Retained-original cap, default 32 MiB. */\n maxOriginalBytes?: number;\n}\n\n/** The value returned by a lock attempt. */\nexport interface LockAttempt<T> {\n acquired: boolean;\n value?: T;\n reason?: string;\n}\n\n/** A record with the fields the store validates before appending. */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Whether a pid still exists (EPERM means it exists but is not ours). */\nfunction isProcessAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/** Random suffix for temporary and tombstone names. */\nfunction randomSuffix(): string {\n return `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\n/**\n * The file-backed implementation of the hook's external state.\n *\n * Every mutating operation is either an append (safe for concurrent writers) or\n * guarded by the directory lock. Readers never throw on corrupt data: they\n * isolate, rebuild, or return an empty view, because a hook that throws is a\n * hook that might be misread as a decision.\n */\nexport class FileStateStore {\n readonly root: string;\n readonly harness: string;\n readonly clock: HookClock;\n readonly lockStaleMs: number;\n readonly sessionRetentionMs: number;\n readonly maxOriginalBytes: number;\n\n /**\n * @param options - root, harness, clock, and the retention/lock knobs.\n */\n constructor(options: FileStateStoreOptions = {}) {\n this.root = options.root ?? resolveStateRoot();\n this.harness = options.harness ?? DEFAULT_HARNESS;\n this.clock = options.clock ?? new SystemClock();\n this.lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS;\n this.sessionRetentionMs = options.sessionRetentionMs ?? SESSION_RETENTION_MS;\n this.maxOriginalBytes = options.maxOriginalBytes ?? MAX_ORIGINAL_BYTES;\n }\n\n /** The directory all session directories live in. */\n sessionsRoot(): string {\n return path.join(this.root, 'sessions');\n }\n\n /** The directory quarantined sessions are moved into. */\n orphansRoot(): string {\n return path.join(this.root, 'orphans');\n }\n\n /** The directory of one session (`<root>/sessions/cc-<sha16>`). */\n sessionDir(sessionId: string): string {\n return path.join(this.sessionsRoot(), sessionDirName(this.harness, sessionId));\n }\n\n /** The paths of one session without creating anything. */\n sessionPaths(sessionId: string): SessionPaths {\n const dir = this.sessionDir(sessionId);\n return {\n dir,\n meta: path.join(dir, 'meta.json'),\n state: path.join(dir, 'state.json'),\n events: path.join(dir, 'events.jsonl'),\n ledger: path.join(dir, 'ledger.jsonl'),\n originals: path.join(dir, 'originals'),\n decisions: path.join(dir, 'decisions'),\n lock: path.join(dir, 'lock')\n };\n }\n\n /**\n * Create the session directory and its metadata if they are missing.\n *\n * A directory whose `meta.json` does not hash back to its own name is\n * quarantined under `orphans/` rather than trusted (design §3.2/§3.4).\n * @param sessionId - the host's session id.\n * @param mode - the effective three-state mode, for `meta.json`.\n * @returns the ensured session paths.\n */\n ensureSession(sessionId: string, mode: string): SessionPaths {\n const paths = this.sessionPaths(sessionId);\n this.ensureDir(this.root);\n this.ensureDir(this.sessionsRoot());\n const expectedHash = sessionHash(this.harness, sessionId);\n let exists = false;\n try {\n exists = fs.statSync(paths.dir).isDirectory();\n } catch {\n exists = false;\n }\n if (exists) {\n const meta = this.readMeta(paths.meta);\n if (meta !== undefined && sessionHash(this.harness, meta.sessionId) !== expectedHash) {\n // A directory that hashes somewhere else is genuinely not this session.\n this.quarantine(paths.dir);\n exists = false;\n }\n // A missing or unreadable meta is the ordinary creation race: several\n // processes can see a new directory before the first one has renamed its\n // meta into place, and an interrupted writer can leave a bad one. The\n // directory's name already carries the session hash, so the safe repair is\n // to adopt it and rewrite the meta atomically — never to quarantine a\n // directory another process is actively appending to.\n }\n if (!exists) this.ensureDir(paths.dir);\n const meta: SessionMeta = {\n harness: this.harness,\n sessionId,\n createdAt: this.clock.iso(),\n harnessVersion: HARNESS_STATE_VERSION,\n mode\n };\n if (this.readMeta(paths.meta) === undefined) {\n // Temp + rename, never a half-written meta for another process to read.\n this.writeAtomic(paths.meta, `${JSON.stringify(meta)}\\n`);\n }\n this.ensureDir(paths.originals);\n this.ensureDir(paths.decisions);\n for (const file of [paths.events, paths.ledger]) this.ensureFile(file);\n return paths;\n }\n\n /**\n * Append one observation to `events.jsonl`.\n * @param sessionId - the session.\n * @param record - the event line.\n */\n appendEvent(sessionId: string, record: SessionEvent): void {\n this.appendLine(this.sessionPaths(sessionId).events, record);\n }\n\n /**\n * Append one decision or skip to `ledger.jsonl`.\n *\n * A record is bounded before it is written: an oversized details object is\n * dropped rather than split, so a line is always one atomic write.\n * @param sessionId - the session.\n * @param record - the ledger line.\n */\n appendLedger(sessionId: string, record: HookLedgerRecord): void {\n this.appendLine(this.sessionPaths(sessionId).ledger, this.bounded(record));\n }\n\n /**\n * Read the newest events of one session, oldest first.\n * @param sessionId - the session.\n * @param limit - maximum events to return.\n * @returns parseable events, newest tail only.\n */\n readEvents(sessionId: string, limit = 60): SessionEvent[] {\n const paths = this.sessionPaths(sessionId);\n const records = this.readTail(paths, paths.events, limit);\n return records.filter((record): record is SessionEvent => isObject(record) && typeof record.kind === 'string');\n }\n\n /**\n * Read the newest ledger lines of one session, oldest first.\n * @param sessionId - the session.\n * @param limit - maximum lines to return.\n * @returns parseable ledger records.\n */\n readLedger(sessionId: string, limit = 60): HookLedgerRecord[] {\n const paths = this.sessionPaths(sessionId);\n const records = this.readTail(paths, paths.ledger, limit);\n return records.filter((record): record is HookLedgerRecord => isObject(record) && typeof record.type === 'string');\n }\n\n /**\n * Read the cached state, rebuilding it from the logs when it is missing or\n * corrupt. Never throws.\n * @param sessionId - the session.\n * @returns the derived state (a fresh one when nothing could be read).\n */\n readState(sessionId: string): SessionState {\n const paths = this.sessionPaths(sessionId);\n try {\n const parsed = JSON.parse(fs.readFileSync(paths.state, 'utf8')) as unknown;\n const state = this.normalizeState(parsed);\n if (state) return state;\n } catch {\n // missing or truncated: fall through to a rebuild\n }\n this.safeUnlink(paths.state);\n const rebuilt = this.rebuildState(sessionId);\n this.writeState(paths, rebuilt);\n return rebuilt;\n }\n\n /**\n * Run one read-modify-write of `state.json` under the directory lock.\n *\n * A caller that does not get the lock must skip its turn, not queue: a tool\n * call is never worth blocking (design §3.3).\n * @param sessionId - the session.\n * @param mutate - pure update of the state in place.\n * @returns whether the lock was acquired, plus the callback's value.\n */\n updateState<T>(sessionId: string, mutate: (state: SessionState) => T): LockAttempt<T> {\n const paths = this.sessionPaths(sessionId);\n const lock = this.acquireLock(paths);\n if (!lock.acquired) return { acquired: false, reason: lock.reason };\n try {\n const state = this.readState(sessionId);\n const value = mutate(state);\n state.updatedAt = this.clock.iso();\n this.writeState(paths, state);\n return { acquired: true, value };\n } finally {\n lock.release?.();\n }\n }\n\n /**\n * Whether a dedupe key was already accounted for in the ledger.\n *\n * Only the tail is scanned: a hook is never asked about an ancient call, and\n * an unbounded scan would turn a fast command into a slow one. Error records\n * do not count — a duplicate delivery after a transient failure is allowed to\n * decide again.\n * @param sessionId - the session.\n * @param key - the dedupe key.\n * @param limit - how many trailing ledger lines to inspect.\n * @returns whether a non-error record already carries this key.\n */\n ledgerHasKey(sessionId: string, key: string, limit = 512): boolean {\n return this.readLedger(sessionId, limit).some((record) => record.dedupeKey === key && record.type !== 'error');\n }\n\n /**\n * Whether a dedupe key was already written to the event log.\n *\n * This is the crash window after the observation was appended and before the\n * ledger line was: the retry must not append the observation twice.\n * @param sessionId - the session.\n * @param key - the dedupe key.\n * @param limit - how many trailing events to inspect.\n * @returns whether the event log already carries this key.\n */\n eventsHaveKey(sessionId: string, key: string, limit = 512): boolean {\n return this.readEvents(sessionId, limit).some((record) => record.dedupeKey === key);\n }\n\n /**\n * Read one cached decision output.\n * @param sessionId - the session.\n * @param key - the dedupe key.\n * @returns the cached output, or `undefined` when absent/corrupt.\n */\n readDecision(sessionId: string, key: string): Record<string, unknown> | undefined {\n const file = path.join(this.sessionPaths(sessionId).decisions, `${key}.json`);\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;\n return isObject(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Commit one decision output atomically.\n *\n * The decision cache doubles as the idempotency marker: a duplicate delivery\n * of the same dedupe key replays this object instead of deciding again.\n * @param sessionId - the session.\n * @param key - the dedupe key.\n * @param output - the exact stdout object of the command.\n */\n writeDecision(sessionId: string, key: string, output: Record<string, unknown>): void {\n const paths = this.sessionPaths(sessionId);\n this.ensureDir(paths.decisions);\n this.writeAtomic(path.join(paths.decisions, `${key}.json`), JSON.stringify(output));\n }\n\n /**\n * Claim the right to decide one dedupe key before the expensive path runs.\n *\n * The decision cache is the commit, but it can only be written after the\n * judgment. Two processes delivering the same `tool_use_id` concurrently would\n * both decide in that window; this exclusive-create claim makes the loser an\n * explicit no-op (or a replay, when the winner has already committed). A claim\n * older than `staleMs` is taken over, so a crashed process cannot wedge a key\n * forever.\n * @param sessionId - the session.\n * @param key - the dedupe key.\n * @param staleMs - age after which a claim is considered abandoned.\n * @returns whether this process may decide the key.\n */\n claimDecision(sessionId: string, key: string, staleMs = 10_000): { acquired: boolean } {\n const paths = this.sessionPaths(sessionId);\n this.ensureDir(paths.decisions);\n const file = path.join(paths.decisions, `${key}.claim`);\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n fs.writeFileSync(file, JSON.stringify({ pid: process.pid, startedMs: this.clock.now() }), {\n flag: 'wx',\n mode: 0o600\n });\n return { acquired: true };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') return { acquired: false };\n let startedMs = this.clock.now();\n let ownerAlive = true;\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;\n if (isObject(parsed)) {\n if (typeof parsed.startedMs === 'number') startedMs = parsed.startedMs;\n if (typeof parsed.pid === 'number') ownerAlive = isProcessAlive(parsed.pid);\n }\n } catch {\n // unreadable claim: its mtime is the best age estimate\n try {\n startedMs = fs.statSync(file).mtimeMs;\n } catch {\n continue;\n }\n }\n // A dead owner's claim is recoverable at once: that is what makes a\n // `kill -9` followed by an immediate replay decide rather than no-op.\n if (ownerAlive && this.clock.now() - startedMs <= staleMs) return { acquired: false };\n const tombstone = `${file}.stale-${randomSuffix()}`;\n try {\n fs.renameSync(file, tombstone);\n fs.rmSync(tombstone, { force: true });\n } catch {\n return { acquired: false };\n }\n }\n }\n return { acquired: false };\n }\n\n /** Release a claim; never throws. */\n releaseDecisionClaim(sessionId: string, key: string): void {\n this.safeUnlink(path.join(this.sessionPaths(sessionId).decisions, `${key}.claim`));\n }\n\n /**\n * Retain one pre-prune payload, evicting the oldest copies when the cap is\n * exceeded.\n *\n * The cap applies to the whole `originals/` directory of one session. Evicted\n * names are returned so the caller can record the downgrade; when the new\n * payload itself cannot fit the result is `retained: false` and the caller must\n * install the reduction without a locator and without counting a saving.\n * @param sessionId - the session.\n * @param digest - content digest (the file stem).\n * @param text - the payload, verbatim.\n * @returns what happened.\n */\n retainOriginal(sessionId: string, digest: string, text: string): RetentionResult {\n const paths = this.sessionPaths(sessionId);\n this.ensureDir(paths.originals);\n const target = path.join(paths.originals, `${digest}.txt`);\n if (fs.existsSync(target)) return { retained: true, evicted: [] };\n const size = Buffer.byteLength(text, 'utf8');\n // A payload larger than the whole allowance can never fit; evicting older\n // copies for it would only destroy data, so it is refused before any eviction.\n if (size > this.maxOriginalBytes) return { retained: false, evicted: [], reason: 'retention-cap' };\n const entries = this.originalEntries(paths.originals);\n let total = entries.reduce((sum, entry) => sum + entry.size, 0);\n const evicted: string[] = [];\n if (total + size > this.maxOriginalBytes) {\n for (const entry of entries) {\n if (total + size <= this.maxOriginalBytes) break;\n try {\n fs.unlinkSync(path.join(paths.originals, entry.name));\n total -= entry.size;\n evicted.push(entry.name.replace(/\\.txt$/, ''));\n } catch {\n // A concurrent eviction took it first; the accounting stays honest.\n }\n }\n }\n if (total + size > this.maxOriginalBytes) {\n return { retained: false, evicted, reason: 'retention-cap' };\n }\n try {\n fs.writeFileSync(target, text, { flag: 'wx', mode: 0o600 });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n return { retained: false, evicted, reason: 'retention-failed' };\n }\n }\n return { retained: true, evicted };\n }\n\n /**\n * Read one retained payload back.\n *\n * The locator a pruned result carries names this record; reading it is what\n * makes the reduction reversible, so a missing or unreadable file answers\n * `undefined` instead of throwing into a decision path.\n * @param sessionId - the session.\n * @param digest - content digest (the file stem).\n * @returns the verbatim payload, or `undefined`.\n */\n readOriginal(sessionId: string, digest: string): string | undefined {\n try {\n const paths = this.sessionPaths(sessionId);\n if (!/^[0-9a-f]{8,64}$/.test(digest)) return undefined;\n return fs.readFileSync(path.join(paths.originals, `${digest}.txt`), 'utf8');\n } catch {\n return undefined;\n }\n }\n\n /** Enforce one session's original cap without retaining anything new. */\n gcOriginals(sessionId: string): string[] {\n const paths = this.sessionPaths(sessionId);\n let entries: Array<{ name: string; size: number; mtimeMs: number }>;\n try {\n entries = this.originalEntries(paths.originals);\n } catch {\n return [];\n }\n let total = entries.reduce((sum, entry) => sum + entry.size, 0);\n const evicted: string[] = [];\n for (const entry of entries) {\n if (total <= this.maxOriginalBytes) break;\n try {\n fs.unlinkSync(path.join(paths.originals, entry.name));\n total -= entry.size;\n evicted.push(entry.name.replace(/\\.txt$/, ''));\n } catch {\n // best effort\n }\n }\n return evicted;\n }\n\n /**\n * Remove session directories older than the retention window.\n * @param nowMs - clock reading to compare against (defaults to the store clock).\n * @param keepSessionId - a session that must survive even if its mtime looks\n * old (a pinned test clock must never garbage-collect the turn being served).\n * @returns the removed directory names.\n */\n gcSessions(nowMs?: number, keepSessionId?: string): string[] {\n const now = nowMs ?? this.clock.now();\n const keep = keepSessionId === undefined ? undefined : path.basename(this.sessionDir(keepSessionId));\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(this.sessionsRoot(), { withFileTypes: true });\n } catch {\n return [];\n }\n const removed: string[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name === keep) continue;\n const dir = path.join(this.sessionsRoot(), entry.name);\n const mtime = this.latestMtime(dir);\n if (now - mtime <= this.sessionRetentionMs) continue;\n try {\n fs.rmSync(dir, { recursive: true, force: true });\n removed.push(entry.name);\n } catch {\n // best effort: a concurrently opened session is left for the next gc\n }\n }\n return removed;\n }\n\n /** The quarantine log path for a session, created on demand. */\n corruptLog(sessionId: string): string {\n return path.join(this.sessionPaths(sessionId).dir, `corrupt-${this.clock.now()}.log`);\n }\n\n // ---------------------------------------------------------------- internals\n\n /** Create one directory with user-only permissions, best effort. */\n private ensureDir(dir: string): void {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n try {\n fs.chmodSync(dir, 0o700);\n } catch {\n // Existing ownership/permissions outside our control; keep going.\n }\n }\n\n /** Create an empty file with 0600 if it does not exist yet. */\n private ensureFile(file: string): void {\n if (fs.existsSync(file)) return;\n try {\n fs.writeFileSync(file, '', { flag: 'wx', mode: 0o600 });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n }\n\n /** Single-write append of one JSON line. */\n private appendLine(file: string, record: unknown): void {\n const line = `${JSON.stringify(record)}\\n`;\n if (Buffer.byteLength(line, 'utf8') > MAX_JSONL_LINE_BYTES) {\n throw new Error(`refusing to append a ${Buffer.byteLength(line, 'utf8')}-byte JSONL line (max ${MAX_JSONL_LINE_BYTES})`);\n }\n const fd = fs.openSync(file, 'a', 0o600);\n try {\n fs.writeSync(fd, line);\n } finally {\n fs.closeSync(fd);\n }\n }\n\n /** Read only the tail of a JSONL file, isolating unreadable lines. */\n private readTail(paths: SessionPaths, file: string, limit: number): unknown[] {\n let fd: number;\n try {\n fd = fs.openSync(file, 'r');\n } catch {\n return [];\n }\n try {\n const size = fs.fstatSync(fd).size;\n if (size === 0) return [];\n const start = Math.max(0, size - READ_TAIL_BYTES);\n const buffer = Buffer.alloc(size - start);\n fs.readSync(fd, buffer, 0, buffer.length, start);\n let text = buffer.toString('utf8');\n if (start > 0) {\n const newline = text.indexOf('\\n');\n text = newline >= 0 ? text.slice(newline + 1) : '';\n }\n const lines = text.split('\\n').filter((line) => line.trim().length > 0);\n const window = limit > 0 ? lines.slice(Math.max(0, lines.length - limit)) : lines;\n const good: unknown[] = [];\n const bad: string[] = [];\n for (const line of window) {\n try {\n good.push(JSON.parse(line));\n } catch {\n bad.push(line);\n }\n }\n if (bad.length > 0) this.isolateBadLines(paths, bad);\n if (bad.length > MAX_BAD_LINES) return [];\n return good;\n } catch {\n return [];\n } finally {\n fs.closeSync(fd);\n }\n }\n\n /** Append unreadable lines to `corrupt-<ts>.log`; never grow it unbounded. */\n private isolateBadLines(paths: SessionPaths, bad: readonly string[]): void {\n try {\n const payload = bad.map((line) => line.slice(0, 1000)).join('\\n');\n fs.appendFileSync(this.corruptLogFor(paths.dir), `${payload}\\n`, { encoding: 'utf8', mode: 0o600 });\n } catch {\n // diagnostics are best effort\n }\n }\n\n /** `corrupt-<ts>.log` in a session directory. */\n private corruptLogFor(dir: string): string {\n return path.join(dir, `corrupt-${this.clock.now()}.log`);\n }\n\n /** Validate and normalize a parsed `state.json`. */\n private normalizeState(value: unknown): SessionState | undefined {\n if (!isObject(value)) return undefined;\n if (value.version !== 1) return undefined;\n if (typeof value.turnNo !== 'number' || !Number.isFinite(value.turnNo) || value.turnNo < 0) return undefined;\n if (!isObject(value.budgets)) return undefined;\n const budgets = value.budgets as Record<string, unknown>;\n if (\n typeof budgets.interventions !== 'number' ||\n typeof budgets.judgmentsTurn !== 'number' ||\n typeof budgets.judgmentsSession !== 'number'\n ) {\n return undefined;\n }\n return {\n version: 1,\n turnNo: value.turnNo,\n appliedSignatures: Array.isArray(value.appliedSignatures)\n ? value.appliedSignatures.filter((item): item is string => typeof item === 'string').slice(-50)\n : [],\n budgets: {\n interventions: budgets.interventions,\n judgmentsTurn: budgets.judgmentsTurn,\n judgmentsSession: budgets.judgmentsSession\n },\n continues: isObject(value.continues)\n ? Object.fromEntries(\n Object.entries(value.continues).filter(([, count]) => typeof count === 'number') as Array<[string, number]>\n )\n : {},\n updatedAt: typeof value.updatedAt === 'string' ? value.updatedAt : this.clock.iso()\n };\n }\n\n /** Rebuild the discardable state from the two authoritative logs. */\n private rebuildState(sessionId: string): SessionState {\n const events = this.readEvents(sessionId, 5000);\n const ledger = this.readLedger(sessionId, 5000);\n let turnNo = 0;\n for (const event of events) {\n if (event.kind === 'stop' && typeof event.turnNo === 'number') turnNo = Math.max(turnNo, event.turnNo);\n }\n const judgmentsSession = ledger.filter((record) => record.judged === true).length;\n return {\n version: 1,\n turnNo,\n appliedSignatures: [],\n budgets: { interventions: 0, judgmentsTurn: 0, judgmentsSession },\n continues: {},\n updatedAt: this.clock.iso()\n };\n }\n\n /** Write `state.json` via temp + fsync + rename. */\n private writeState(paths: SessionPaths, state: SessionState): void {\n this.writeAtomic(paths.state, JSON.stringify(state));\n }\n\n /** Atomic replacement of a small file. */\n private writeAtomic(file: string, content: string): void {\n const tmp = `${file}.${randomSuffix()}.tmp`;\n const fd = fs.openSync(tmp, 'w', 0o600);\n try {\n fs.writeSync(fd, content);\n fs.fsyncSync(fd);\n } finally {\n fs.closeSync(fd);\n }\n try {\n fs.renameSync(tmp, file);\n } catch {\n // Windows-style rename-over-existing; POSIX never takes this branch.\n this.safeUnlink(file);\n fs.renameSync(tmp, file);\n }\n }\n\n /** Unlink without throwing. */\n private safeUnlink(file: string): void {\n try {\n fs.unlinkSync(file);\n } catch {\n // already gone\n }\n }\n\n /** Read and validate `meta.json`. */\n private readMeta(file: string): SessionMeta | undefined {\n try {\n const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;\n if (!isObject(parsed)) return undefined;\n if (typeof parsed.sessionId !== 'string' || typeof parsed.harness !== 'string') return undefined;\n return parsed as unknown as SessionMeta;\n } catch {\n return undefined;\n }\n }\n\n /** Move a directory whose meta does not match its name into `orphans/`. */\n private quarantine(dir: string): void {\n try {\n this.ensureDir(this.orphansRoot());\n const target = path.join(this.orphansRoot(), `${path.basename(dir)}-${this.clock.now()}`);\n fs.renameSync(dir, target);\n } catch {\n // If it cannot be moved, leave it; ensureSession recreates the missing path.\n }\n }\n\n /** Newest mtime under one directory, for the seven-day rule. */\n private latestMtime(dir: string): number {\n let latest = 0;\n try {\n latest = fs.statSync(dir).mtimeMs;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n try {\n const stat = fs.statSync(path.join(dir, entry.name));\n if (stat.mtimeMs > latest) latest = stat.mtimeMs;\n } catch {\n // raced with a unlink\n }\n }\n } catch {\n latest = 0;\n }\n return latest;\n }\n\n /** The retained originals, oldest first. */\n private originalEntries(dir: string): Array<{ name: string; size: number; mtimeMs: number }> {\n let names: string[];\n try {\n names = fs.readdirSync(dir);\n } catch {\n return [];\n }\n const entries: Array<{ name: string; size: number; mtimeMs: number }> = [];\n for (const name of names) {\n if (!name.endsWith('.txt')) continue;\n try {\n const stat = fs.statSync(path.join(dir, name));\n entries.push({ name, size: stat.size, mtimeMs: stat.mtimeMs });\n } catch {\n // raced with an eviction\n }\n }\n entries.sort((left, right) => left.mtimeMs - right.mtimeMs);\n return entries;\n }\n\n /** Take the directory lock, taking over one that is older than the stale rule. */\n private acquireLock(paths: SessionPaths): { acquired: boolean; reason?: string; release?: () => void } {\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n fs.mkdirSync(paths.lock, { mode: 0o700 });\n try {\n fs.writeFileSync(\n path.join(paths.lock, 'owner.json'),\n JSON.stringify({ pid: process.pid, startedAt: this.clock.iso(), startedMs: this.clock.now() }),\n { mode: 0o600 }\n );\n } catch {\n // The lock is still held; owner metadata is diagnostics only.\n }\n return { acquired: true, release: () => this.releaseLock(paths.lock) };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') return { acquired: false, reason: 'lock-error' };\n const startedMs = this.lockStartedMs(paths.lock);\n const age = this.clock.now() - startedMs;\n if (!Number.isFinite(age) || age <= this.lockStaleMs) return { acquired: false, reason: 'lock-contention' };\n const tombstone = `${paths.lock}.stale-${randomSuffix()}`;\n try {\n fs.renameSync(paths.lock, tombstone);\n fs.rmSync(tombstone, { recursive: true, force: true });\n } catch {\n return { acquired: false, reason: 'lock-contention' };\n }\n }\n }\n return { acquired: false, reason: 'lock-contention' };\n }\n\n /** Release the lock directory. */\n private releaseLock(lock: string): void {\n try {\n fs.rmSync(lock, { recursive: true, force: true });\n } catch {\n // already gone\n }\n }\n\n /** When the current lock owner started, from its metadata or its mtime. */\n private lockStartedMs(lock: string): number {\n try {\n const owner = JSON.parse(fs.readFileSync(path.join(lock, 'owner.json'), 'utf8')) as unknown;\n if (isObject(owner) && typeof owner.startedMs === 'number' && Number.isFinite(owner.startedMs)) {\n return owner.startedMs;\n }\n } catch {\n // fall through to mtime\n }\n try {\n return fs.statSync(lock).mtimeMs;\n } catch {\n return this.clock.now();\n }\n }\n\n /** Bound one ledger record to the line budget before it can be appended. */\n private bounded(record: HookLedgerRecord): HookLedgerRecord {\n const line = `${JSON.stringify(record)}\\n`;\n if (Buffer.byteLength(line, 'utf8') <= MAX_JSONL_LINE_BYTES) return record;\n const minimal: HookLedgerRecord = {\n ...record,\n details: { truncated: true },\n skipReason: (record.skipReason ?? '').slice(0, 120)\n };\n if (Buffer.byteLength(`${JSON.stringify(minimal)}\\n`, 'utf8') <= MAX_JSONL_LINE_BYTES) return minimal;\n return { ...minimal, details: undefined };\n }\n}\n"]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Harness tag used for the state directory prefix; Claude Code for v0.2.0. */
|
|
2
|
+
export declare const DEFAULT_HARNESS = "cc";
|
|
3
|
+
/** Environment variable that relocates the whole state root (design §3.2). */
|
|
4
|
+
export declare const STATE_DIR_ENV = "HARNESS_REFLEX_STATE_DIR";
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the state root.
|
|
7
|
+
*
|
|
8
|
+
* Explicit `HARNESS_REFLEX_STATE_DIR` wins; otherwise the XDG state home
|
|
9
|
+
* (`$XDG_STATE_HOME`, falling back to `~/.local/state`) plus `harness-reflex`.
|
|
10
|
+
* @param env - environment to read (defaults to `process.env`).
|
|
11
|
+
* @returns an absolute path to the state root.
|
|
12
|
+
*/
|
|
13
|
+
export declare function resolveStateRoot(env?: NodeJS.ProcessEnv): string;
|
|
14
|
+
/**
|
|
15
|
+
* The sixteen-hex-character identity of one session directory.
|
|
16
|
+
*
|
|
17
|
+
* The session id is hashed rather than used verbatim: it must never become a
|
|
18
|
+
* path segment a host controls (design §3.4, "path traversal refused").
|
|
19
|
+
* @param harness - harness tag.
|
|
20
|
+
* @param sessionId - the host's session id.
|
|
21
|
+
* @returns the first sixteen hex characters of `sha256(harness \0 sessionId)`.
|
|
22
|
+
*/
|
|
23
|
+
export declare function sessionHash(harness: string, sessionId: string): string;
|
|
24
|
+
/**
|
|
25
|
+
* The directory name of one session: `cc-<sha16>`.
|
|
26
|
+
* @param harness - harness tag.
|
|
27
|
+
* @param sessionId - the host's session id.
|
|
28
|
+
* @returns the directory name (a single, safe path segment).
|
|
29
|
+
*/
|
|
30
|
+
export declare function sessionDirName(harness: string, sessionId: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* Refuse a platform whose filesystem semantics this store does not implement.
|
|
33
|
+
*
|
|
34
|
+
* The design names Windows explicitly: `mkdir` locks and `rename`-over-existing
|
|
35
|
+
* behave differently there, so a silent degradation would be a correctness bug
|
|
36
|
+
* rather than a portability gap. The hook reports the refusal on stderr and
|
|
37
|
+
* exits non-zero (which every host treats as "abandoned, fail open").
|
|
38
|
+
* @param platform - platform to check (defaults to `process.platform`).
|
|
39
|
+
* @throws when the platform is Windows.
|
|
40
|
+
*/
|
|
41
|
+
export declare function assertSupportedPlatform(platform?: NodeJS.Platform): void;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the hook process keeps its external state, and which platform it may do
|
|
3
|
+
* that on.
|
|
4
|
+
*
|
|
5
|
+
* A Claude Code command hook is a fresh process per event (design §3.1), so the
|
|
6
|
+
* only thing two events share is a directory. The root is user-scoped rather
|
|
7
|
+
* than project-scoped: a `.reflex/` next to the repository would be a git
|
|
8
|
+
* pollutant, while `$XDG_STATE_HOME` is what the user's state directory is for.
|
|
9
|
+
*
|
|
10
|
+
* @module state/paths
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import * as os from 'node:os';
|
|
14
|
+
import * as path from 'node:path';
|
|
15
|
+
/** Harness tag used for the state directory prefix; Claude Code for v0.2.0. */
|
|
16
|
+
export const DEFAULT_HARNESS = 'cc';
|
|
17
|
+
/** Environment variable that relocates the whole state root (design §3.2). */
|
|
18
|
+
export const STATE_DIR_ENV = 'HARNESS_REFLEX_STATE_DIR';
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the state root.
|
|
21
|
+
*
|
|
22
|
+
* Explicit `HARNESS_REFLEX_STATE_DIR` wins; otherwise the XDG state home
|
|
23
|
+
* (`$XDG_STATE_HOME`, falling back to `~/.local/state`) plus `harness-reflex`.
|
|
24
|
+
* @param env - environment to read (defaults to `process.env`).
|
|
25
|
+
* @returns an absolute path to the state root.
|
|
26
|
+
*/
|
|
27
|
+
export function resolveStateRoot(env = process.env) {
|
|
28
|
+
const explicit = env[STATE_DIR_ENV]?.trim();
|
|
29
|
+
if (explicit)
|
|
30
|
+
return path.resolve(explicit);
|
|
31
|
+
const xdg = env.XDG_STATE_HOME?.trim();
|
|
32
|
+
if (xdg)
|
|
33
|
+
return path.join(path.resolve(xdg), 'harness-reflex');
|
|
34
|
+
return path.join(os.homedir(), '.local', 'state', 'harness-reflex');
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The sixteen-hex-character identity of one session directory.
|
|
38
|
+
*
|
|
39
|
+
* The session id is hashed rather than used verbatim: it must never become a
|
|
40
|
+
* path segment a host controls (design §3.4, "path traversal refused").
|
|
41
|
+
* @param harness - harness tag.
|
|
42
|
+
* @param sessionId - the host's session id.
|
|
43
|
+
* @returns the first sixteen hex characters of `sha256(harness \0 sessionId)`.
|
|
44
|
+
*/
|
|
45
|
+
export function sessionHash(harness, sessionId) {
|
|
46
|
+
return createHash('sha256').update(`${harness}\u0000${sessionId}`).digest('hex').slice(0, 16);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The directory name of one session: `cc-<sha16>`.
|
|
50
|
+
* @param harness - harness tag.
|
|
51
|
+
* @param sessionId - the host's session id.
|
|
52
|
+
* @returns the directory name (a single, safe path segment).
|
|
53
|
+
*/
|
|
54
|
+
export function sessionDirName(harness, sessionId) {
|
|
55
|
+
return `${harness}-${sessionHash(harness, sessionId)}`;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Refuse a platform whose filesystem semantics this store does not implement.
|
|
59
|
+
*
|
|
60
|
+
* The design names Windows explicitly: `mkdir` locks and `rename`-over-existing
|
|
61
|
+
* behave differently there, so a silent degradation would be a correctness bug
|
|
62
|
+
* rather than a portability gap. The hook reports the refusal on stderr and
|
|
63
|
+
* exits non-zero (which every host treats as "abandoned, fail open").
|
|
64
|
+
* @param platform - platform to check (defaults to `process.platform`).
|
|
65
|
+
* @throws when the platform is Windows.
|
|
66
|
+
*/
|
|
67
|
+
export function assertSupportedPlatform(platform = process.platform) {
|
|
68
|
+
if (platform === 'win32') {
|
|
69
|
+
throw new Error('harness-reflex hook: Windows is not supported; this state store relies on POSIX mkdir locks, ' +
|
|
70
|
+
'rename-over-existing and single-write O_APPEND semantics. Run Claude Code hooks under WSL2, Linux, or macOS.');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=paths.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.js","sourceRoot":"","sources":["../../src/state/paths.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,+EAA+E;AAC/E,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,CAAC;AAEpC,8EAA8E;AAC9E,MAAM,CAAC,MAAM,aAAa,GAAG,0BAA0B,CAAC;AAExD;;;;;;;GAOG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAyB,OAAO,CAAC,GAAG;IACnE,MAAM,QAAQ,GAAG,GAAG,CAAC,aAAa,CAAC,EAAE,IAAI,EAAE,CAAC;IAC5C,IAAI,QAAQ;QAAE,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC5C,MAAM,GAAG,GAAG,GAAG,CAAC,cAAc,EAAE,IAAI,EAAE,CAAC;IACvC,IAAI,GAAG;QAAE,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,gBAAgB,CAAC,CAAC;IAC/D,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,gBAAgB,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,WAAW,CAAC,OAAe,EAAE,SAAiB;IAC5D,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,OAAO,SAAS,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAChG,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,SAAiB;IAC/D,OAAO,GAAG,OAAO,IAAI,WAAW,CAAC,OAAO,EAAE,SAAS,CAAC,EAAE,CAAC;AACzD,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,uBAAuB,CAAC,WAA4B,OAAO,CAAC,QAAQ;IAClF,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CACb,+FAA+F;YAC7F,8GAA8G,CACjH,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["/**\n * Where the hook process keeps its external state, and which platform it may do\n * that on.\n *\n * A Claude Code command hook is a fresh process per event (design §3.1), so the\n * only thing two events share is a directory. The root is user-scoped rather\n * than project-scoped: a `.reflex/` next to the repository would be a git\n * pollutant, while `$XDG_STATE_HOME` is what the user's state directory is for.\n *\n * @module state/paths\n */\nimport { createHash } from 'node:crypto';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\n/** Harness tag used for the state directory prefix; Claude Code for v0.2.0. */\nexport const DEFAULT_HARNESS = 'cc';\n\n/** Environment variable that relocates the whole state root (design §3.2). */\nexport const STATE_DIR_ENV = 'HARNESS_REFLEX_STATE_DIR';\n\n/**\n * Resolve the state root.\n *\n * Explicit `HARNESS_REFLEX_STATE_DIR` wins; otherwise the XDG state home\n * (`$XDG_STATE_HOME`, falling back to `~/.local/state`) plus `harness-reflex`.\n * @param env - environment to read (defaults to `process.env`).\n * @returns an absolute path to the state root.\n */\nexport function resolveStateRoot(env: NodeJS.ProcessEnv = process.env): string {\n const explicit = env[STATE_DIR_ENV]?.trim();\n if (explicit) return path.resolve(explicit);\n const xdg = env.XDG_STATE_HOME?.trim();\n if (xdg) return path.join(path.resolve(xdg), 'harness-reflex');\n return path.join(os.homedir(), '.local', 'state', 'harness-reflex');\n}\n\n/**\n * The sixteen-hex-character identity of one session directory.\n *\n * The session id is hashed rather than used verbatim: it must never become a\n * path segment a host controls (design §3.4, \"path traversal refused\").\n * @param harness - harness tag.\n * @param sessionId - the host's session id.\n * @returns the first sixteen hex characters of `sha256(harness \\0 sessionId)`.\n */\nexport function sessionHash(harness: string, sessionId: string): string {\n return createHash('sha256').update(`${harness}\\u0000${sessionId}`).digest('hex').slice(0, 16);\n}\n\n/**\n * The directory name of one session: `cc-<sha16>`.\n * @param harness - harness tag.\n * @param sessionId - the host's session id.\n * @returns the directory name (a single, safe path segment).\n */\nexport function sessionDirName(harness: string, sessionId: string): string {\n return `${harness}-${sessionHash(harness, sessionId)}`;\n}\n\n/**\n * Refuse a platform whose filesystem semantics this store does not implement.\n *\n * The design names Windows explicitly: `mkdir` locks and `rename`-over-existing\n * behave differently there, so a silent degradation would be a correctness bug\n * rather than a portability gap. The hook reports the refusal on stderr and\n * exits non-zero (which every host treats as \"abandoned, fail open\").\n * @param platform - platform to check (defaults to `process.platform`).\n * @throws when the platform is Windows.\n */\nexport function assertSupportedPlatform(platform: NodeJS.Platform = process.platform): void {\n if (platform === 'win32') {\n throw new Error(\n 'harness-reflex hook: Windows is not supported; this state store relies on POSIX mkdir locks, ' +\n 'rename-over-existing and single-write O_APPEND semantics. Run Claude Code hooks under WSL2, Linux, or macOS.'\n );\n }\n}\n"]}
|
package/docs/USER_GUIDE.en.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# Harness Reflex User Guide (v0.1.0)
|
|
2
2
|
|
|
3
|
-
> This is the complete manual for the
|
|
3
|
+
> This is the complete manual for the **`dsh-harness-reflex` plugin** and the
|
|
4
4
|
> **`harness-reflex` core package**. The same text is embedded into
|
|
5
|
-
> `packages/dsh-reflex/client.js`, so it can be read directly in the DSH
|
|
5
|
+
> `packages/dsh-harness-reflex/client.js`, so it can be read directly in the DSH
|
|
6
6
|
> settings panel under the **“Guide”** tab (it follows the DSH interface
|
|
7
7
|
> language, Chinese or English).
|
|
8
8
|
> Editing this file therefore requires re-running `npm run build:all`, otherwise
|
|
@@ -24,7 +24,7 @@ It ships in two forms that share one decision engine but expose **different tool
|
|
|
24
24
|
| Form | Package | Harness | Transport |
|
|
25
25
|
| --- | --- | --- | --- |
|
|
26
26
|
| stdio MCP server | `harness-reflex` | Claude Code, Codex CLI, AGY | MCP JSON-RPC child process |
|
|
27
|
-
| DSH Host plugin |
|
|
27
|
+
| DSH Host plugin | `dsh-harness-reflex` | DeepSeek Harness (`dsh`) | In-process `ctx.tools` / Cordis hooks |
|
|
28
28
|
|
|
29
29
|
The MCP surface exposes eight tools; the DSH surface registers five switchable
|
|
30
30
|
tools (four by default), while pruning, stagnation detection and the ledger are
|
|
@@ -42,7 +42,7 @@ and each surface's actual tool definitions for argument and validation boundarie
|
|
|
42
42
|
└───────────────┬──────────────────────────────────┬───────────────────┘
|
|
43
43
|
│ stdio MCP │ in-process DSH Cordis
|
|
44
44
|
┌───────────────▼──────────────────┐ ┌────────────▼───────────────────┐
|
|
45
|
-
│ harness-reflex core (dist/) │ │
|
|
45
|
+
│ harness-reflex core (dist/) │ │ dsh-harness-reflex plugin │
|
|
46
46
|
│ gate · prune · stagnation │◄─┤ src/bridge.ts ReflexRuntime │
|
|
47
47
|
│ route · screen · score │ │ src/tools.ts 5 switchable │
|
|
48
48
|
│ ledger · calibrate │ │ src/router.ts virtual provider│
|
|
@@ -53,7 +53,8 @@ and each surface's actual tool definitions for argument and validation boundarie
|
|
|
53
53
|
└──────────────────────────────────┘ ┌────────────▼───────────────────┐
|
|
54
54
|
│ client.js browser panel (React) │
|
|
55
55
|
│ Overview / Virtual provider / │
|
|
56
|
-
│ Effort / Backend /
|
|
56
|
+
│ Effort / Backend / Interventions│
|
|
57
|
+
│ Tools / Ledger / Guide │
|
|
57
58
|
└────────────────────────────────┘
|
|
58
59
|
```
|
|
59
60
|
|
|
@@ -92,17 +93,17 @@ node dist/cli/index.js setup all # or claude | codex | agy
|
|
|
92
93
|
|
|
93
94
|
# 3) install as a DSH plugin (in-process integration, recommended)
|
|
94
95
|
# release tarball: --force is required to reinstall the same version
|
|
95
|
-
dsh plugin --profile web add --force ./release/
|
|
96
|
+
dsh plugin --profile web add --force ./release/dsh-harness-reflex-0.1.0.tgz
|
|
96
97
|
```
|
|
97
98
|
|
|
98
99
|
Every step of `npm run build:all` is required:
|
|
99
100
|
|
|
100
101
|
1. `tsc`: root `src/` → `dist/`;
|
|
101
102
|
2. `node scripts/link-dsh-deps.mjs`: symlinks this machine's `@deepseek-ai/*`
|
|
102
|
-
packages into `packages/dsh-reflex/node_modules/` (fully offline, no registry);
|
|
103
|
-
3. `tsc -p packages/dsh-reflex/tsconfig.json`: plugin Host half → `packages/dsh-reflex/dist/`;
|
|
103
|
+
packages into `packages/dsh-harness-reflex/node_modules/` (fully offline, no registry);
|
|
104
|
+
3. `tsc -p packages/dsh-harness-reflex/tsconfig.json`: plugin Host half → `packages/dsh-harness-reflex/dist/`;
|
|
104
105
|
4. `node scripts/embed-user-guide.mjs` + `tsc -p tsconfig.client.json` +
|
|
105
|
-
`node packages/dsh-reflex/dist/client-bundle.js packages/dsh-reflex`:
|
|
106
|
+
`node packages/dsh-harness-reflex/dist/client-bundle.js packages/dsh-harness-reflex`:
|
|
106
107
|
embeds this manual into the browser half and emits the single-file `client.js`.
|
|
107
108
|
|
|
108
109
|
> The order is not interchangeable: `client.js` must be built after this
|
|
@@ -123,26 +124,59 @@ plugin options; resolution order is “plugin config > environment > default moc
|
|
|
123
124
|
| Official Jev / System One API | `jev` | `POST {BASE_URL}/v1/...`, requires an API key |
|
|
124
125
|
|
|
125
126
|
```bash
|
|
126
|
-
# Official Jev
|
|
127
|
-
export SYSTEM_ONE_BACKEND=jev
|
|
127
|
+
# Official Jev: only the key is required
|
|
128
128
|
export SYSTEM_ONE_API_KEY="your-api-key"
|
|
129
|
-
export SYSTEM_ONE_BASE_URL="https://api.typesafe.ai/v1/systemone"
|
|
130
129
|
|
|
131
|
-
# Self-hosted vLLM (OpenAI compatible)
|
|
132
|
-
export SYSTEM_ONE_BACKEND=simple-jev
|
|
130
|
+
# Self-hosted vLLM (OpenAI compatible): only the endpoint is required
|
|
133
131
|
export SYSTEM_ONE_BASE_URL="http://localhost:8000"
|
|
134
|
-
export
|
|
132
|
+
export SYSTEM_ONE_BACKEND=simple-jev # optional: VLLM_BASE_URL/OPENAI_BASE_URL alone selects simple-jev
|
|
135
133
|
```
|
|
136
134
|
|
|
137
|
-
|
|
135
|
+
With `SYSTEM_ONE_BACKEND` unset the choice is derived: `SYSTEM_ONE_API_KEY`/`JEV_API_KEY` present → `jev`;
|
|
136
|
+
`VLLM_BASE_URL`/`OPENAI_BASE_URL` present → `simple-jev`; neither → `mock`.
|
|
137
|
+
|
|
138
|
+
The other two variables default per backend, so “default mock” says nothing about them:
|
|
139
|
+
|
|
140
|
+
| Variable | `jev` | `simple-jev` |
|
|
141
|
+
| --- | --- | --- |
|
|
142
|
+
| `SYSTEM_ONE_BASE_URL` | `https://api.typesafe.ai/v1/systemone` | `http://localhost:8000` |
|
|
143
|
+
| `SYSTEM_ONE_MODEL` | `jev-latest` | `Qwen/Qwen2.5-7B-Instruct` |
|
|
144
|
+
| `SYSTEM_ONE_API_KEY` | **none** (empty; the service rejects the request) | `dummy` (local servers usually ignore it) |
|
|
145
|
+
|
|
146
|
+
**A connection comes only from the active connection profile** ("Connections" on the
|
|
147
|
+
System 1 backend page). With none active the plugin is **unconfigured**: the panel says
|
|
148
|
+
so, the plugin makes no external request, and decisions fall back to the local
|
|
149
|
+
deterministic heuristics. A mistyped active name is reported and connects nothing — it is
|
|
150
|
+
never silently swapped for another connection.
|
|
151
|
+
|
|
152
|
+
Each connection profile states its own fields (under `systemOne.profiles.<name>` in the
|
|
153
|
+
DSH plugin config):
|
|
138
154
|
|
|
139
155
|
| Option | Default | Notes |
|
|
140
156
|
| --- | --- | --- |
|
|
141
|
-
| `
|
|
142
|
-
| `
|
|
143
|
-
| `
|
|
144
|
-
| `
|
|
145
|
-
| `
|
|
157
|
+
| `baseUrl` | unset | System 1 endpoint; unset lets the backend use its environment/default |
|
|
158
|
+
| `modelIds` | unset | The **list of model ids** this connection may ask for. `model` is the single-model spelling, identical to a one-entry list |
|
|
159
|
+
| `selectedModel` | first listed id | The **one model in force**: the runtime sends it and the Test button probes it. It must be one of `modelIds`: the save refuses a selection outside the list, and a hand-edited file that still carries one builds **no connection at all** (the panel shows "not configured") instead of asking for a different model |
|
|
160
|
+
| `apiKey` | unset | The secret itself, **write-only**: it is stored on save and never shown again. A **rename does not carry it** — retype it after renaming (see below) |
|
|
161
|
+
| `apiKeyEnv` | unset | Stores the **variable name only**. Unset names nothing and the backend falls back to `SYSTEM_ONE_API_KEY` → `JEV_API_KEY` → `VLLM_API_KEY` → `OPENAI_API_KEY`; naming a variable locks onto it, with no fallback |
|
|
162
|
+
| `timeoutMs` | unset | Per-decision timeout; unset uses the **backend default — 10000 ms for `jev`, 8000 ms for `simple-jev`**, not one shared value |
|
|
163
|
+
| `backend` | unset | Backend implementation for this connection; unset uses the top-level `backend` |
|
|
164
|
+
|
|
165
|
+
The top-level `backend` only decides *which implementation a connection uses when it
|
|
166
|
+
states none* (`auto` derives from the environment; `mock` / `vllm` / `jev` may be pinned).
|
|
167
|
+
It is not a connection by itself. An explicit `backend: mock` still works: that is a
|
|
168
|
+
deliberate choice of the in-process implementation, and needs no profile.
|
|
169
|
+
|
|
170
|
+
**Renames and write-only keys.** A connection's name *is* its settings path, so renaming
|
|
171
|
+
it means writing a different path — and the Host cannot move a stored secret across paths.
|
|
172
|
+
The panel therefore **blocks the save** and names the row, asking you to retype the API
|
|
173
|
+
key (connections whose key comes from an environment variable are unaffected and rename
|
|
174
|
+
normally). Swapping two names, or renaming onto a name another saved profile already
|
|
175
|
+
holds, is refused the same way, with its own explanation.
|
|
176
|
+
|
|
177
|
+
The same-named `baseUrl` / `model` / `apiKeyEnv` / `timeoutMs` keys at the top of
|
|
178
|
+
`systemOne` do not take part in the connection: they are not a connection profile. If a
|
|
179
|
+
document still holds them, the panel neither reads nor rewrites them.
|
|
146
180
|
|
|
147
181
|
Calibration (optional): fit a PAVA/ECE curve with the `calibrate` engine over a
|
|
148
182
|
labelled sample, then point `calibrationPath` at that JSON and the runtime will
|
|
@@ -371,7 +405,7 @@ the documented default and needs no extra configuration.
|
|
|
371
405
|
Retrieval is a read of the session events under that locator:
|
|
372
406
|
|
|
373
407
|
```ts
|
|
374
|
-
import { readPrunedOriginal } from '
|
|
408
|
+
import { readPrunedOriginal } from 'dsh-harness-reflex';
|
|
375
409
|
|
|
376
410
|
const record = readPrunedOriginal(session.ownEvents(), locator);
|
|
377
411
|
record?.text; // the original, byte for byte
|
|
@@ -444,14 +478,14 @@ The plugin declares its browser half through `dsh.client` and registers into the
|
|
|
444
478
|
| Reasoning effort | Policy (never intervene / Reflex adaptive), fallback level, minimum confidence, **adaptive-effort switch** |
|
|
445
479
|
| Interventions | Three-state mode (`off`/`observe`/`active`), the four capability overrides, per-turn intervention budget, per-turn judgment budget, per-session judgment budget, repeat threshold, failure threshold, minimum confidence, judgment window size, prune floor ratio; plus the currently effective mode and capabilities (read-only) |
|
|
446
480
|
| Tools | A per-capability switch for each of the five capabilities (four on, `route` off by default), each one stating **what it does / when the agent should call it / whether it is advised to expose it**, plus an "Apply recommended set" button; the currently registered tool names are listed at the end (read-only, follows `toolPrefix`), with a line pointing the ledger at `/reflex-ledger` |
|
|
447
|
-
| System 1 backend |
|
|
481
|
+
| System 1 backend | Connection profiles (any number: base URL, model list with one selection, write-only API key, key variable name, timeout), the backend implementation; plus the tool-name prefix, prune threshold, ledger JSONL path and calibration-curve path |
|
|
448
482
|
| Decision ledger | Live metrics, recent-decision table, JSONL sink, clear (confirmed twice) |
|
|
449
483
|
| **Guide** | **A read-only view of this manual, following the DSH interface language** |
|
|
450
484
|
|
|
451
|
-
- Saving
|
|
452
|
-
|
|
453
|
-
backend page spans
|
|
454
|
-
|
|
485
|
+
- Saving validates through the Host and writes **only the paths whose value
|
|
486
|
+
changed** (whole-group pages still write their group whole — see below). The
|
|
487
|
+
System 1 backend page spans the connection rows, `systemOne.active`, `backend`
|
|
488
|
+
and the four runtime fields.
|
|
455
489
|
- When the Host settings document is read-only the page becomes read-only and
|
|
456
490
|
every write control is disabled.
|
|
457
491
|
- Panel routes under `/dsh-reflex/api/*` (`panel` / `health` / `ledger/clear`) accept loopback clients only, and
|
|
@@ -479,12 +513,13 @@ much they write:
|
|
|
479
513
|
- **The reasoning-effort switch is always written explicitly.** `effort.enabled`
|
|
480
514
|
is saved with the group's current value, so there is no "the panel shows it
|
|
481
515
|
enabled but the configuration actually omits it" ambiguity.
|
|
482
|
-
- **System 1 backend:
|
|
516
|
+
- **System 1 backend: only the paths that changed.** The Host settings
|
|
483
517
|
document is addressed by **configuration path**, and this page covers
|
|
484
|
-
`backend` (a scalar),
|
|
485
|
-
top-level fields `toolPrefix`, `ledgerPath`,
|
|
486
|
-
`calibrationPath`: saving writes
|
|
487
|
-
|
|
518
|
+
`backend` (a scalar), the connection rows (`systemOne.profiles.<name>.<field>`),
|
|
519
|
+
`systemOne.active`, and the four top-level fields `toolPrefix`, `ledgerPath`,
|
|
520
|
+
`pruneThreshold` and `calibrationPath`: saving writes the paths whose value
|
|
521
|
+
actually changed and leaves untouched rows and fields alone (a renamed or
|
|
522
|
+
removed row retires its whole old subtree). A **page name is never used as a configuration key** —
|
|
488
523
|
`runtime` is not a field of `Config`, so writing under that name is refused by
|
|
489
524
|
the Host outright and the whole save fails with it. A blank `ledgerPath` or
|
|
490
525
|
`calibrationPath` is written as "unset", which keeps the layer below instead of
|
|
@@ -535,17 +570,25 @@ the **eight tools frozen since v0.1.0**, while the DSH plugin side registers
|
|
|
535
570
|
by the automatic intervention layer and by one command instead of occupying the
|
|
536
571
|
model's tool list.
|
|
537
572
|
|
|
538
|
-
| Capability | MCP tool name (`harness-reflex mcp`) | DSH plugin side (
|
|
573
|
+
| Capability | MCP tool name (`harness-reflex mcp`) | DSH plugin side (`dsh-harness-reflex`) | Main arguments | Advice |
|
|
539
574
|
| --- | --- | --- | --- | --- |
|
|
540
575
|
| Multi-option classification | `reflex_choice` | tool `reflex_choice` | `question`, `options[]`, optional `context` | Suggested for the agent |
|
|
541
576
|
| Continuous rating | `reflex_score` | tool `reflex_score` | `statement`, optional `criteria`, `context` | Suggested for the agent |
|
|
542
577
|
| Prompt-injection screen | `reflex_screen` | tool `reflex_screen` | `content`, optional `source`, `strict` | Suggested for the agent |
|
|
543
578
|
| Claim/evidence gate | `reflex_gate` | tool `reflex_gate` | `assertions[{statement}]`, `evidence`, optional `strictness` | Suggested for the agent |
|
|
544
579
|
| Candidate ranking | `reflex_route` | tool `reflex_route` (**not registered by default**) | `goal`, `candidates[]`, optional `topK` | Opt-in |
|
|
580
|
+
| Subagent delegation | `reflex_delegate` | tool `reflex_delegate` (**only registered after you tick Delegation in the settings panel, and the host delegation tool then declares a reasoning level, i.e. `modelSelection` is on**) | `prompt`, `description`, optional `provider`, `model`, `cwd` | Suggested for the agent |
|
|
545
581
|
| Long-output pruning | `reflex_prune` | no tool: result pruning runs automatically from hooks such as `tools/pre-execute`, following the intervention mode | `rawOutput`, optional `intent`, `shadowMode` | — |
|
|
546
582
|
| Stagnation detection | `reflex_detect_stagnation` | no tool: stagnation detection is part of the automatic intervention layer | optional `recentAction`, `goal`, `history[]` | — |
|
|
547
583
|
| Ledger audit | `reflex_status_ledger` | no tool: use the `/reflex-ledger` command (no arguments) | optional `includeEntries` (returns `summary`, optionally `recentEntries`) | For humans |
|
|
548
584
|
|
|
585
|
+
Ticking **Delegation** is an explicit consent with a side effect outside this plugin: it merges
|
|
586
|
+
`tool-subagent: { modelSelection: true }` into your profile patch (`~/.dsh/profiles/<profile>/cordis.patch.yml`),
|
|
587
|
+
preserving every other byte of it and backing it up first. The host reads that switch at start-up, so the
|
|
588
|
+
panel says **"saved — takes effect after you restart DSH"** rather than pretending it is live. If the capability
|
|
589
|
+
disappears at runtime, the plugin warns, withdraws `reflex_delegate`, and shows the reason — it never writes your
|
|
590
|
+
configuration back on its own.
|
|
591
|
+
|
|
549
592
|
Differences:
|
|
550
593
|
|
|
551
594
|
- The tool-name prefix is configurable (`toolPrefix`, default `reflex_`), so
|
|
@@ -630,7 +673,7 @@ Release artifacts (`release/`):
|
|
|
630
673
|
| Artifact | Content |
|
|
631
674
|
| --- | --- |
|
|
632
675
|
| `harness-reflex-<version>.tgz` | Root package: `dist/`, `README.md`, `docs/`, `USER_GUIDE.md`, `experiments/` |
|
|
633
|
-
| `
|
|
676
|
+
| `dsh-harness-reflex-<version>.tgz` | Plugin `dsh-harness-reflex` (npm pack naming): `dist/`, `client.js` (with this manual embedded), `cordis.patch.yml`, `locale/` |
|
|
634
677
|
| `SHA256SUMS` | SHA-256 checksums of the two tarballs |
|
|
635
678
|
| `release-report.json` | The per-check packaging audit (entries, dead links, dependency declarations, install smoke) |
|
|
636
679
|
| `RELEASE-<version>.md` | Release notes: install commands, verification checklist, contents |
|
|
@@ -653,7 +696,7 @@ stdio MCP `tools/list` for real.
|
|
|
653
696
|
| A virtual model errors instead of dispatching | The pool is empty and `routing.fallback` is unset; add candidates or a fallback target |
|
|
654
697
|
| Text is not routed as expected | Check `routing.enabled`, the virtual model id spelling, and whether the agent actually requested that virtual model |
|
|
655
698
|
| Reasoning effort never changes | The policy is unset (no intervention), or the caller chose a concrete `reasoningEffort` explicitly on the request |
|
|
656
|
-
| System 1 decisions always fall back | `timeoutMs` too small, `baseUrl` unreachable, or `minConfidence` too high; check the latest decision and backend state on the Overview page |
|
|
699
|
+
| System 1 decisions always fall back | `timeoutMs` too small, `baseUrl` unreachable, or `minConfidence` too high; check the latest decision and backend state on the Overview page. Note the timeout has **no single default**: unset means 10000 ms for `jev` and 8000 ms for `simple-jev` |
|
|
657
700
|
| The in-panel guide is stale | `USER_GUIDE.md` changed without a rebuild; run `npm run build:all` |
|
|
658
701
|
| A closed tool is still being called | The registry takes effect on the next load; reload the plugin and check that the key is the **suffix** (`gate`, not `reflex_gate`). `prune`/`detect_stagnation`/`status_ledger` are commands now and are refused by the validator |
|
|
659
702
|
| `reflex_route` is missing from the default tool list | Expected: `route` is off by default; switch it on in the Tools page (or set `tools: { enabled: { route: true } }`) |
|
|
@@ -666,7 +709,7 @@ stdio MCP `tools/list` for real.
|
|
|
666
709
|
|
|
667
710
|
## 13. Version and compatibility
|
|
668
711
|
|
|
669
|
-
- Version: `harness-reflex` and
|
|
712
|
+
- Version: `harness-reflex` and `dsh-harness-reflex` ship together at v0.1.0;
|
|
670
713
|
- Node: `>= 18` (root package `engines`); DSH Host dependencies `@deepseek-ai/*@0.2.1-alpha.4`;
|
|
671
714
|
- Host contracts are declared as `peerDependencies`, so the plugin never bundles
|
|
672
715
|
a second copy of Host modules;
|