/* eslint-disable */ /** * @generated by scripts/gen-loop-blobs.mjs — DO NOT EDIT BY HAND. * Canonical sources live in harness-core/src (feature-adr-checkpoints.ts, * feature-adr-routing.ts, challenge-panel.ts, loop-trace.ts). Edit those, then run: * node scripts/gen-loop-blobs.mjs * CI runs `node scripts/gen-loop-blobs.mjs --check` (via loop-blobs-regen.test.ts) and * fails on any diff — "test the generator once" (ADR-004). * * Blob roster: checkpoints, training-pairs (default OFF — the health-advisor PHI * lesson, AM-9), model-resolver (auto-included when any step.model is set), * usage-probes, codex-dispatch, challenge-panel, trace (the 7th — carries the * dispatch/settle seq emitter). All seven names are FIXED; a new subsystem is a new * blob name plus an ADR note, never a silent rename. */ export interface LoopBlob { name: string; version: string; contentHash: string; sourcePath: string; /** Blobs whose declarations this blob depends on when co-injected (shared-helper dedup). */ requires: string[]; exports: string[]; code: string; } export const LOOP_BLOB_NAMES = ["checkpoints","training-pairs","model-resolver","usage-probes","codex-dispatch","challenge-panel","trace","loop-semantics","ha-consult-router"] as const; /** Workflow files the regen-diff gate covers TODAY (AM-5 honest scope): exactly the files * carrying BEGIN BLOB markers. Stage B (whole-file regeneration of feature-adr.js) is a * tracked dz-backlog item, deliberately NOT claimed here. */ export const BLOB_COVERAGE_MANIFEST: { coveredWorkflows: string[] } = { "coveredWorkflows": [ ".claude/workflows/cfr-pipeline.js", ".claude/workflows/feature-adr.js", ".claude/workflows/health-advisor.js", "packages/@dzhechkov/skills-feature-adr/templates/.claude/workflows/feature-adr.js" ] }; export const BLOBS: Record = { "checkpoints": { name: "checkpoints", version: "1.1.0", contentHash: "a44560c6036fd143b7a3f125fec00fa8b91c3c06ac5b9e1ecfb83d27a5211e9b", sourcePath: "packages/@dzhechkov/harness-core/src/feature-adr-checkpoints.ts", requires: [], exports: ["CHECKPOINT_STAGES","STAGE_ARTIFACTS","CHECKPOINT_MAX_RESULT_CHARS","CKPT_SCHEMA_VERSION","fnv1a","fnv1a64","checkpointInputHash","resumeMode","decideCheckpointResume","serializeCheckpoint","CHECKPOINT_LS_SENTINEL","parseCheckpointRead","shellQuote","checkpointReadCmd","checkpointAppendCmd","DESIGN_SUBSTAGES","designStageKey","decideDesignFanResume","parseArtifactProbe","ROUTER_CONTRACT_TOKEN"], code: "const CHECKPOINT_STAGES = ['router', 'design', 'plan', 'code', 'qe', 'fleet'];\nconst STAGE_ARTIFACTS = {\n router: '00_complexity_assessment.md',\n design: '01_requirements.md',\n plan: '06_implementation_plan.md',\n code: '07_code_changes/change_manifest.md',\n qe: '08_qe_report.md',\n fleet: '09_fleet_qe_assessment.md',\n};\nconst CHECKPOINT_MAX_RESULT_CHARS = 12000;\nconst CKPT_SCHEMA_VERSION = 'fa-ckpt-3';\nconst ROUTER_CONTRACT_TOKEN = 'router-writes-00-v1';\nfunction fnv1a(str) {\n let h = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;\n }\n return h.toString(16).padStart(8, '0');\n}\nfunction fnv1a64(str) {\n return fnv1a(str) + fnv1a('fa-ckpt-salt' + str);\n}\nfunction checkpointInputHash(stage, parts) {\n return fnv1a64(JSON.stringify([CKPT_SCHEMA_VERSION, stage, ...parts.map((p) => (p === undefined ? null : p))]));\n}\nfunction resumeMode(raw) {\n return raw === 'never' ? 'never' : raw === 'force' ? 'force' : 'auto';\n}\nconst DESIGN_SUBSTAGES = ['requirements', 'adr', 'qcsd', 'architecture'];\nfunction designStageKey(sub) {\n return 'design:' + sub;\n}\nfunction decideDesignFanResume(opts) {\n const missingSubstages = [];\n opts.required.forEach((sub, i) => {\n const r = opts.results[i];\n if (r === null || r === undefined)\n missingSubstages.push(sub);\n });\n const missingArtifacts = [];\n let probeMissing = false;\n if (opts.artifacts.length > 0) {\n if (opts.postRunListing === null)\n probeMissing = true;\n else\n for (const rel of opts.artifacts)\n if (!opts.postRunListing.has(rel))\n missingArtifacts.push(rel);\n }\n const reason = missingSubstages.length > 0 ? 'substage-missing'\n : probeMissing ? 'probe-not-established'\n : missingArtifacts.length > 0 ? 'artifact-missing'\n : 'ok';\n return { complete: reason === 'ok', missingSubstages, missingArtifacts, reason };\n}\nfunction decideCheckpointResume(opts) {\n if (opts.mode === 'never')\n return { resume: false, reason: 'mode-never' };\n if (!opts.entry || opts.entry.result === null || opts.entry.result === undefined) {\n return { resume: false, reason: 'no-checkpoint' };\n }\n if (opts.entry.inputHash !== opts.inputHash)\n return { resume: false, reason: 'stale-input' };\n if (opts.mode === 'force')\n return { resume: true, reason: 'resumed-force' };\n const required = opts.artifactRel === null ? [] : (typeof opts.artifactRel === 'string' ? [opts.artifactRel] : opts.artifactRel);\n for (const rel of required) {\n if (!opts.listing.has(rel))\n return { resume: false, reason: 'artifact-missing' };\n }\n return { resume: true, reason: 'resumed' };\n}\nfunction serializeCheckpoint(stage, inputHash, result) {\n if (result === null || result === undefined)\n return null;\n let line;\n try {\n line = JSON.stringify({ stage, inputHash, result });\n }\n catch {\n return null;\n }\n if (typeof line !== 'string' || line.length > CHECKPOINT_MAX_RESULT_CHARS)\n return null;\n return line;\n}\nconst CHECKPOINT_LS_SENTINEL = '---FA-CKPT-LS---';\nfunction parseCheckpointRead(text) {\n const out = { entries: {}, listing: new Set(), malformedLines: 0 };\n const raw = String(text ?? '');\n const lines = raw.split('\\n');\n const sentinelAt = lines.findIndex((l) => l.trim() === CHECKPOINT_LS_SENTINEL);\n const body = sentinelAt === -1 ? lines : lines.slice(0, sentinelAt);\n const ls = sentinelAt === -1 ? [] : lines.slice(sentinelAt + 1);\n for (const line of body) {\n const t = line.trim();\n if (t === '')\n continue;\n try {\n const e = JSON.parse(t);\n if (e && typeof e === 'object' && typeof e.stage === 'string' && typeof e.inputHash === 'string' && 'result' in e && e.result !== null && e.result !== undefined) {\n out.entries[e.stage] = e;\n }\n else {\n if (e && typeof e === 'object' && typeof e.stage === 'string')\n delete out.entries[e.stage];\n out.malformedLines++;\n }\n }\n catch {\n out.malformedLines++;\n }\n }\n for (const line of ls) {\n const t = line.trim();\n if (t !== '')\n out.listing.add(t);\n }\n return out;\n}\nfunction shellQuote(s) {\n return \"'\" + String(s).replace(/'/g, \"'\\\\''\") + \"'\";\n}\nfunction checkpointReadCmd(fdirAbs) {\n const q = shellQuote(fdirAbs);\n return ('cat ' + q + '/.fa-state/checkpoints.jsonl 2>/dev/null || true; ' +\n \"echo '\" + CHECKPOINT_LS_SENTINEL + \"'; \" +\n 'cd ' + q + ' 2>/dev/null && find . -maxdepth 2 -type f 2>/dev/null | sed \"s|^\\\\./||\" || true');\n}\nfunction checkpointAppendCmd(fdirAbs, line) {\n const dir = shellQuote(fdirAbs + '/.fa-state');\n const file = shellQuote(fdirAbs + '/.fa-state/checkpoints.jsonl');\n return 'mkdir -p ' + dir + \" && printf '%s\\\\n' \" + shellQuote(line) + ' >> ' + file;\n}\nfunction parseArtifactProbe(opts) {\n if (opts.stdout === null || opts.stdout === undefined)\n return null;\n const known = new Map();\n for (const rel of opts.required)\n known.set('HAVE:' + rel, rel);\n const found = new Set();\n let sentinels = 0;\n for (const raw of String(opts.stdout).split('\\n')) {\n const line = raw.trim();\n if (line === '')\n continue;\n if (line === opts.sentinel) {\n sentinels++;\n continue;\n }\n if (sentinels > 0)\n return null;\n const rel = known.get(line);\n if (rel === undefined)\n return null;\n found.add(rel);\n }\n if (sentinels !== 1)\n return null;\n return found;\n}", }, "training-pairs": { name: "training-pairs", version: "1.1.0", contentHash: "740b733d3d995e7031590f1707b442d0f0f9d7d585ada6f37bbf08c5db3351e9", sourcePath: "packages/@dzhechkov/harness-core/src/feature-adr-checkpoints.ts", requires: ["checkpoints"], exports: ["TRAINPAIR_SCHEMA_VERSION","TRAINPAIR_MAX_IO_CHARS","trainingPairFamily","trainingPairPath","TRAINPAIR_PRIVACY_NOTE","buildTrainingPair","serializeTrainingPair","trainingPairAppendCmd","decideCaptureMode","captureFailureRecord","trainingPairBackfillCmd","TP_BACKFILL_OK","TP_BACKFILL_SKIP"], code: "function decideCaptureMode(opts) {\n if (!opts.enabled)\n return 'skip-disabled';\n if (!Number.isInteger(opts.recordCount) || opts.recordCount <= 0)\n return 'skip-empty';\n return opts.resumed ? 'backfill' : 'capture';\n}\nfunction captureFailureRecord(stage, mode, reason, detail) {\n const normalizedStage = typeof stage === 'string' && stage.trim() !== '' ? stage : 'unknown';\n const normalizedMode = mode === 'capture' || mode === 'backfill' || mode === 'skip-disabled' || mode === 'skip-empty'\n ? mode\n : null;\n const normalizedReason = reason === 'threw' || reason === 'unserializable' || reason === 'unverified' || reason === 'backfill-unverified' || reason === 'empty-output'\n ? reason\n : 'threw';\n let normalizedDetail = null;\n if (detail !== null && detail !== undefined) {\n try {\n const text = String(detail);\n if (text !== '')\n normalizedDetail = text.length > 500 ? text.slice(0, 500) + '…' : text;\n }\n catch {\n normalizedDetail = null;\n }\n }\n return { stage: normalizedStage, mode: normalizedMode, reason: normalizedReason, detail: normalizedDetail };\n}\nconst TRAINPAIR_SCHEMA_VERSION = 'fa-trainpair-2';\nconst TRAINPAIR_MAX_IO_CHARS = 48000;\nfunction trainingPairFamily(spec) {\n return /codex|gpt|openai/i.test(String(spec ?? '')) ? 'codex' : 'claude';\n}\nfunction trainingPairPath(slug, stage) {\n return '.dz/fa-training/' + slug + '/' + stage + '.jsonl';\n}\nconst TRAINPAIR_PRIVACY_NOTE = \"feature-adr TRAINING PAIRS (backlog 70e0f083): per-stage SFT records - STAGE INPUT (full prompt/context) -> STAGE OUTPUT (artifact/result) -> EVALUATION (QE grade + injected lessons) with model+family provenance; one JSONL file per stage per slug. PRIVACY: pairs may contain TARGET-REPO CODE and full prompts. This directory is NOT gitignored yet by explicit owner decision - review contents before sharing or publishing anything that embeds it. ts is the CAPTURE time. On a record with captureMode: 'backfill' that is the RECONSTRUCTION time, NOT the stage's observation time — the original stage's timing lives in that run's .fa-state checkpoint.\";\nfunction coerceText(v) {\n if (typeof v === 'string')\n return v;\n if (v === null || v === undefined)\n return '';\n try {\n const s = JSON.stringify(v);\n return typeof s === 'string' ? s : String(v);\n }\n catch {\n return String(v);\n }\n}\nfunction buildTrainingPair(opts) {\n let input = coerceText(opts.input);\n let output = coerceText(opts.output);\n let truncated = null;\n if (input.length + output.length > TRAINPAIR_MAX_IO_CHARS) {\n truncated = { inputChars: input.length, outputChars: output.length, inputHash: fnv1a64(input), outputHash: fnv1a64(output) };\n const half = Math.floor(TRAINPAIR_MAX_IO_CHARS / 2);\n let inKeep = input.length;\n let outKeep = output.length;\n if (outKeep <= half)\n inKeep = TRAINPAIR_MAX_IO_CHARS - outKeep;\n else if (inKeep <= half)\n outKeep = TRAINPAIR_MAX_IO_CHARS - inKeep;\n else {\n inKeep = half;\n outKeep = TRAINPAIR_MAX_IO_CHARS - half;\n }\n if (inKeep < input.length)\n input = input.slice(0, inKeep) + '\\n…[TRUNCATED ' + (truncated.inputChars - inKeep) + ' chars — full-text fnv1a64=' + truncated.inputHash + ']';\n if (outKeep < output.length)\n output = output.slice(0, outKeep) + '\\n…[TRUNCATED ' + (truncated.outputChars - outKeep) + ' chars — full-text fnv1a64=' + truncated.outputHash + ']';\n }\n const ev = opts.evaluation || {};\n const pv = opts.provenance || {};\n return {\n schema: TRAINPAIR_SCHEMA_VERSION,\n slug: opts.slug,\n stage: opts.stage,\n ts: opts.ts === undefined ? null : opts.ts,\n input,\n output,\n evaluation: {\n grade: typeof ev.grade === 'string' && ev.grade.trim() !== '' ? ev.grade : null,\n gradedBy: typeof ev.gradedBy === 'string' && ev.gradedBy !== '' ? ev.gradedBy : null,\n lessonsInjected: Array.isArray(ev.lessonsInjected) ? ev.lessonsInjected.filter((s) => typeof s === 'string' && s !== '') : [],\n },\n provenance: {\n model: typeof pv.model === 'string' && pv.model !== '' ? pv.model : 'unknown',\n family: pv.family === 'claude' || pv.family === 'codex' ? pv.family : trainingPairFamily(pv.model),\n role: typeof pv.role === 'string' && pv.role !== '' ? pv.role : 'unknown',\n tokens: typeof pv.tokens === 'number' && Number.isFinite(pv.tokens) ? pv.tokens : null,\n minutes: typeof pv.minutes === 'number' && Number.isFinite(pv.minutes) ? pv.minutes : null,\n },\n truncated,\n captureMode: opts.captureMode === 'backfill' ? 'backfill' : 'capture',\n resumed: opts.resumed === true,\n };\n}\nfunction serializeTrainingPair(pair) {\n try {\n const line = JSON.stringify(pair);\n return typeof line === 'string' ? line : null;\n }\n catch {\n return null;\n }\n}\nfunction trainingPairAppendCmd(repoAbs, slug, stage, line) {\n const dirAbs = repoAbs + '/.dz/fa-training/' + slug;\n const readmeAbs = repoAbs + '/.dz/fa-training/README.md';\n const fileAbs = dirAbs + '/' + stage + '.jsonl';\n return ('mkdir -p ' + shellQuote(dirAbs) +\n ' && { [ -f ' + shellQuote(readmeAbs) + ' ] || printf \\'%s\\\\n\\' ' + shellQuote(TRAINPAIR_PRIVACY_NOTE) + ' > ' + shellQuote(readmeAbs) + '; }' +\n \" && printf '%s\\\\n' \" + shellQuote(line) + ' >> ' + shellQuote(fileAbs));\n}\nconst TP_BACKFILL_OK = 'TP-BACKFILL-OK';\nconst TP_BACKFILL_SKIP = 'TP-BACKFILL-SKIP';\nconst TP_BACKFILL_DUP = 'TP-BACKFILL-DUP';\nfunction trainingPairBackfillCmd(repoAbs, slug, stage, lines, markKey) {\n if (typeof repoAbs !== 'string' || repoAbs === '')\n return null;\n if (typeof slug !== 'string' || slug === '')\n return null;\n if (typeof stage !== 'string' || stage === '')\n return null;\n if (!Array.isArray(lines) || lines.length === 0 || !lines.every(line => typeof line === 'string' && line !== ''))\n return null;\n const dirAbs = repoAbs + '/.dz/fa-training/' + slug;\n const readmeAbs = repoAbs + '/.dz/fa-training/README.md';\n const fileAbs = dirAbs + '/' + stage + '.jsonl';\n const markDir = repoAbs + '/.dz/fa-training/.backfill-marks';\n const markStage = stage.replace(/\\.\\./g, '_').replace(/\\//g, '_');\n const resolvedMarkKey = markKey === undefined ? fnv1a64(stage + '\\0' + lines.join('\\n')) : markKey;\n const markPath = markDir + '/' + markStage + '-' + resolvedMarkKey;\n const appends = lines\n .map(line => \"printf '%s\\\\n' \" + shellQuote(line) + ' >> ' + shellQuote(fileAbs))\n .join(' && ');\n return ('mkdir -p ' + shellQuote(dirAbs) +\n ' && { [ -f ' + shellQuote(readmeAbs) + ' ] || printf \\'%s\\\\n\\' ' + shellQuote(TRAINPAIR_PRIVACY_NOTE) + ' > ' + shellQuote(readmeAbs) + '; }' +\n ' && mkdir -p ' + shellQuote(markDir) +\n ' && if mkdir ' + shellQuote(markPath) + ' 2>/dev/null; then ' +\n 'if [ -f ' + shellQuote(fileAbs) + ' ]; then echo ' + shellQuote(TP_BACKFILL_SKIP) +\n '; else { ' + appends + ' && echo ' + shellQuote(TP_BACKFILL_OK) + '; } || { rmdir ' + shellQuote(markPath) + ' 2>/dev/null; false; }; fi' +\n '; else echo ' + shellQuote(TP_BACKFILL_DUP) + '; fi');\n}", }, "model-resolver": { name: "model-resolver", version: "1.0.0", contentHash: "e82ac2137279537f5b65725cbd8de5817fcbc89571068e2df843587352fa83f5", sourcePath: "packages/@dzhechkov/harness-core/src/feature-adr-routing.ts", requires: [], exports: ["specToOpts","resolveStageModel","KNOWN_CODEX","mergeOpts","stageLabel","modelLabel"], code: "const OVERRIDE_REASONING = {\n router: 'high',\n requirements: 'xhigh',\n research: 'xhigh',\n adr: 'xhigh',\n ideation: 'xhigh',\n ddd: 'xhigh',\n architecture: 'xhigh',\n plan: 'xhigh',\n code: 'xhigh',\n qe: 'high',\n fleet: 'high',\n};\nfunction topCodexId(env) {\n let top = env.CODEX_MODEL;\n if (top === 'auto') {\n const ids = Object.keys(KNOWN_CODEX);\n for (let i = 0; i < ids.length; i++) {\n if (ids[i] !== 'auto')\n top = ids[i] || top;\n }\n }\n return top;\n}\nconst KNOWN_CODEX = { auto: 1, 'gpt-5.5': 1, 'gpt-5.6': 1, 'gpt-5.6-luna': 1, 'gpt-5.6-terra': 1, 'gpt-5.6-sol': 1 };\nconst CLAUDE_NAMES = { fable: 1, opus: 1, sonnet: 1, haiku: 1 };\nconst VALID_REASONING = { none: 1, minimal: 1, low: 1, medium: 1, high: 1, xhigh: 1 };\nconst DEFAULT_MODELS = {\n router: 'fable',\n requirements: 'sonnet',\n research: 'sonnet',\n adr: 'opus',\n ideation: 'sonnet',\n ddd: 'opus',\n architecture: 'opus',\n plan: 'sonnet',\n code: null,\n qe: null,\n fleet: 'sonnet',\n};\nfunction specToOpts(spec, env) {\n const log = env.log || function () { };\n if (!spec)\n return {};\n const parts = String(spec).split(':');\n const head = parts[0] || '';\n if (head === 'codex') {\n let id = parts[1] || env.CODEX_MODEL;\n if (id !== 'auto' && !KNOWN_CODEX[id]) {\n log('models: unknown codex id ' + id + ' — using ' + env.CODEX_MODEL);\n id = env.CODEX_MODEL;\n }\n let reasoning = parts[2] || 'high';\n if (!VALID_REASONING[reasoning]) {\n log('models: unknown reasoning ' + reasoning + ' — using high');\n reasoning = 'high';\n }\n return { agentType: 'codex:codex-rescue', codexModel: id, _reasoning: reasoning };\n }\n if (CLAUDE_NAMES[head])\n return { model: head };\n log('models: unknown spec ' + spec + ' — session-inherited');\n return {};\n}\nfunction resolveCoderSpec(env) {\n if (env.CODER === 'codex' || env.CODER === 'codex-fallback')\n return 'codex:' + env.CODEX_MODEL + ':high';\n return 'opus';\n}\nfunction coderIsCodex(env) {\n if (env.CODER === 'codex' || env.CODER === 'codex-fallback')\n return true;\n const codeSpec = env.MODELS.code;\n if (codeSpec && String(codeSpec).split(':')[0] === 'codex')\n return true;\n return false;\n}\nfunction resolveQeSpec(env) {\n if (coderIsCodex(env))\n return 'opus';\n const CODEX_AVAILABLE = env.codexAvailable !== false;\n if (!CODEX_AVAILABLE)\n return 'opus';\n return 'codex:' + topCodexId(env) + ':high';\n}\nfunction routingRequested(env) {\n return (Object.keys(env.MODELS).length > 0 ||\n env.PLANNER === 'codex' ||\n env.CODER === 'codex' ||\n env.CODER === 'codex-fallback' ||\n env.QE_REVIEWER === 'codex' ||\n env.QE_REVIEWER === 'codex-fallback');\n}\nfunction resolveStageModel(stage, env) {\n if (env.usageOverride) {\n const r = (env.usageReasoning && env.usageReasoning[stage]) || OVERRIDE_REASONING[stage] || 'high';\n const o = specToOpts('codex:' + topCodexId(env) + ':' + r, env);\n o._usageSwitched = true;\n return o;\n }\n let spec = env.MODELS[stage];\n if (spec === undefined) {\n if (!routingRequested(env))\n return {};\n spec = DEFAULT_MODELS[stage];\n }\n if (stage === 'code' && (spec === null || spec === undefined))\n return specToOpts(resolveCoderSpec(env), env);\n if (stage === 'qe' && (spec === null || spec === undefined))\n return specToOpts(resolveQeSpec(env), env);\n return specToOpts(spec, env);\n}\nfunction modelLabel(opts) {\n if (opts && opts.agentType === 'codex:codex-rescue') {\n const base = 'codex:' + opts.codexModel + ':' + opts._reasoning;\n return opts._usageSwitched ? base + ' (usage-switched)' : base;\n }\n if (opts && opts.model)\n return opts.model;\n return 'session';\n}\nfunction stageLabel(base, opts) {\n const m = modelLabel(opts);\n return m === 'session' ? base : base + ' · ' + m;\n}\nfunction mergeOpts(base, extra) {\n const out = {};\n for (const k in base)\n out[k] = base[k];\n for (const k in extra)\n out[k] = extra[k];\n return out;\n}", }, "usage-probes": { name: "usage-probes", version: "1.0.0", contentHash: "4ae2504a50fe05aad4383e223d460b21396805b17dfefab50e60022d58cdd19d", sourcePath: "packages/@dzhechkov/harness-core/src/feature-adr-routing.ts", requires: ["model-resolver"], exports: ["decideUsageAction","OVERRIDE_REASONING","topCodexId"], code: "function decideUsageAction(prevOverride, signal, threshold) {\n if (signal === null || signal === undefined) {\n if (prevOverride)\n return { override: true, action: 'keep' };\n return { override: true, action: 'fail-safe-switch' };\n }\n const s = signal.sessionPct;\n const w = signal.weeklyPct;\n const sKnown = typeof s === 'number' && isFinite(s) && s >= 0;\n const wKnown = typeof w === 'number' && isFinite(w) && w >= 0;\n if ((sKnown && s >= threshold) || (wKnown && w >= threshold)) {\n return { override: true, action: prevOverride ? 'keep' : 'switch' };\n }\n if (sKnown && wKnown) {\n return { override: false, action: prevOverride ? 'restore' : 'none' };\n }\n return { override: prevOverride, action: prevOverride ? 'keep' : 'none' };\n}", }, "codex-dispatch": { name: "codex-dispatch", version: "1.0.0", contentHash: "f203268da376fa993ce61d38b8fc6a24db4ac1e3edb6b90662f86ae4351a30e7", sourcePath: "packages/@dzhechkov/harness-core/src/feature-adr-routing.ts", requires: [], exports: ["codexDispatchMode","codexExecPlan","needsCodeLandedBarrier","decideCodeLanding"], code: "const CODE_LANDING_PIPELINE_PREFIXES = ['features/', '.dz/', '.agentic-qe/', 'roam/'];\nfunction codeLandingEmptySignal(seconds) {\n return 'changed=0 after ' + seconds + 's — genuinely not landed';\n}\nfunction needsCodeLandedBarrier(coderUsed) {\n return coderUsed === 'codex' || coderUsed === 'codex-fallback';\n}\nfunction stripCodeLandingPath(path) {\n let p = String(path || '').trim().replace(/\\\\/g, '/');\n while (p.indexOf('./') === 0)\n p = p.slice(2);\n return p.replace(/\\/+/g, '/');\n}\nfunction classifyCodeLandingPathReject(path) {\n const p = stripCodeLandingPath(path);\n if (!p)\n return 'empty-after-strip';\n if (p[0] === '/')\n return 'absolute-path';\n if (p === '..' || p.indexOf('../') === 0 || p.indexOf('/../') >= 0 || p.endsWith('/..'))\n return 'traversal';\n if (/[\\0\\r\\n\\t \"'\\x60$;&|<>*?()[\\]{}!]/.test(p))\n return 'not-a-path';\n if (p.endsWith('/'))\n return 'not-a-path';\n for (const prefix of CODE_LANDING_PIPELINE_PREFIXES) {\n const bare = prefix.slice(0, -1);\n if (p === bare || p.indexOf(prefix) === 0)\n return 'pipeline-artifact-path';\n }\n return null;\n}\nfunction normalizeCodeLandingPath(path) {\n return classifyCodeLandingPathReject(path) === null ? stripCodeLandingPath(path) : '';\n}\nfunction filterPollableCodePaths(paths) {\n const out = [];\n const seen = new Set();\n for (const path of paths || []) {\n const normalized = normalizeCodeLandingPath(path);\n if (!normalized || seen.has(normalized))\n continue;\n seen.add(normalized);\n out.push(normalized);\n }\n return out;\n}\nfunction isNewlyChanged(path, baseline, currentHashes) {\n if (!baseline || !baseline.ok)\n return false;\n let recorded = null;\n for (const entry of baseline.entries) {\n if (entry.path === path) {\n recorded = entry.hash;\n break;\n }\n }\n if (recorded === null)\n return true;\n const now = currentHashes ? currentHashes[path] : undefined;\n if (now === undefined)\n return false;\n return now !== recorded;\n}\nfunction decideCodeLanding(snapshot) {\n const maxWaitMs = Math.max(0, snapshot.maxWaitMs);\n const elapsedMs = Math.max(0, snapshot.elapsedMs);\n const elapsedSeconds = Math.floor(elapsedMs / 1000);\n const expectedPaths = filterPollableCodePaths(snapshot.expectedPaths);\n const changedPaths = filterPollableCodePaths(snapshot.changedEntries.map(function (entry) { return entry.path; }));\n if (expectedPaths.length === 0) {\n return {\n status: 'inconclusive',\n reason: 'empty-plan-block',\n changed: 0,\n elapsedMs: elapsedMs,\n elapsedSeconds: elapsedSeconds,\n expectedPaths: expectedPaths,\n matchedExpectedPaths: [],\n changedPaths: changedPaths,\n predicate: 'no-expected-targets',\n qeSignalLine: 'CODEX-LANDING-SIGNAL status=inconclusive predicate=no-expected-targets reason=empty-plan-block',\n };\n }\n const baseline = snapshot.baseline;\n if (!baseline || !baseline.ok) {\n const reason = baseline && baseline.reason ? baseline.reason : 'no-baseline';\n return {\n status: 'inconclusive',\n reason: reason,\n changed: 0,\n elapsedMs: elapsedMs,\n elapsedSeconds: elapsedSeconds,\n expectedPaths: expectedPaths,\n matchedExpectedPaths: [],\n changedPaths: changedPaths,\n predicate: 'newly-changed',\n qeSignalLine: 'CODEX-LANDING-SIGNAL status=inconclusive predicate=newly-changed reason=' + reason,\n };\n }\n const changed = new Set(changedPaths);\n const matchedExpectedPaths = expectedPaths.filter(function (path) {\n return changed.has(path) && isNewlyChanged(path, baseline, snapshot.currentHashes);\n });\n if (matchedExpectedPaths.length > 0) {\n return {\n status: 'landed',\n changed: matchedExpectedPaths.length,\n elapsedMs: elapsedMs,\n elapsedSeconds: elapsedSeconds,\n expectedPaths: expectedPaths,\n matchedExpectedPaths: matchedExpectedPaths,\n changedPaths: changedPaths,\n predicate: 'newly-changed',\n qeSignalLine: 'CODEX-LANDING-SIGNAL status=landed changed=' +\n matchedExpectedPaths.length +\n ' after=' +\n elapsedSeconds +\n 's predicate=newly-changed matched=' +\n matchedExpectedPaths.join(','),\n };\n }\n if (elapsedMs < maxWaitMs) {\n return {\n status: 'not-yet-flushed',\n changed: 0,\n elapsedMs: elapsedMs,\n elapsedSeconds: elapsedSeconds,\n expectedPaths: expectedPaths,\n matchedExpectedPaths: [],\n changedPaths: changedPaths,\n predicate: 'empty-before-timeout',\n qeSignalLine: 'CODEX-LANDING-SIGNAL status=not-yet-flushed changed=0 after ' + elapsedSeconds + 's — not yet flushed',\n };\n }\n const terminalSeconds = Math.ceil(maxWaitMs / 1000);\n return {\n status: 'genuinely-not-landed',\n changed: 0,\n elapsedMs: elapsedMs,\n elapsedSeconds: terminalSeconds,\n expectedPaths: expectedPaths,\n matchedExpectedPaths: [],\n changedPaths: changedPaths,\n predicate: 'empty-after-timeout',\n qeSignalLine: 'CODEX-LANDING-SIGNAL status=genuinely-not-landed ' + codeLandingEmptySignal(terminalSeconds),\n };\n}\nconst WRAPPER_STAGES = { code: 1, plan: 1 };\nfunction codexDispatchMode(stage) {\n return WRAPPER_STAGES[stage] ? 'wrapper' : 'exec';\n}\nconst CODEX_EXEC_PROMPT_CEILING_CHARS = 24000;\nfunction codexExecPlan(input) {\n if (codexDispatchMode(input.stage) === 'wrapper') {\n return { mode: 'wrapper', reason: 'deliverable is a file written out-of-band' };\n }\n if (!input.probedId) {\n return { mode: 'claude', reason: 'no codex model id answered the probe' };\n }\n if (input.stage === 'qe' && input.scoped !== true) {\n return {\n mode: 'claude',\n reason: 'qe prompt is not SCOPED — an unscoped codex exec QE buys reconnaissance, not review ' +\n '(MEASURED 2026-08-21: 19038 chars, 280s, exit 124, no verdict)',\n };\n }\n if (input.promptChars > CODEX_EXEC_PROMPT_CEILING_CHARS) {\n return {\n mode: 'claude',\n reason: 'prompt is ' +\n input.promptChars +\n ' chars, over the ' +\n CODEX_EXEC_PROMPT_CEILING_CHARS +\n '-char codex exec ceiling (it would stall)',\n };\n }\n return { mode: 'exec', reason: 'codex exec on ' + input.probedId };\n}\nconst SCOPED_QE_MAX_FILES = 3;\nconst SCOPED_QE_MAX_QUESTIONS = 4;\nconst SCOPED_QE_MAX_PATH_CHARS = 200;\nconst SCOPED_QE_MAX_QUESTION_CHARS = 200;\nfunction scopedQePrompt(input) {\n const o = input || {};\n const rawFiles = Array.isArray(o.files) ? o.files : [];\n const files = [];\n for (const f of rawFiles) {\n const s = String(f === undefined || f === null ? '' : f).trim();\n if (s === '')\n continue;\n if (files.indexOf(s) !== -1)\n continue;\n files.push(s.slice(0, SCOPED_QE_MAX_PATH_CHARS));\n if (files.length >= SCOPED_QE_MAX_FILES)\n break;\n }\n if (files.length === 0)\n return '';\n const rawQuestions = Array.isArray(o.questions) ? o.questions : [];\n const questions = [];\n for (const q of rawQuestions) {\n const s = String(q === undefined || q === null ? '' : q).trim().replace(/\\s+/g, ' ');\n if (s === '')\n continue;\n questions.push(s.slice(0, SCOPED_QE_MAX_QUESTION_CHARS));\n if (questions.length >= SCOPED_QE_MAX_QUESTIONS)\n break;\n }\n if (questions.length === 0) {\n questions.push('Is this change correct, and does the test named by its ADR actually DISCRIMINATE (would it fail if the protection were deleted)?');\n }\n const slug = String(o.slug === undefined || o.slug === null ? '' : o.slug).trim().slice(0, 60);\n let out = 'Read ONLY these files: ' + files.join(', ') + '. Do NOT open any other file and do NOT explore the repository.';\n if (slug !== '')\n out += ' They are the changed files of feature ' + slug + '.';\n out += '\\n\\nAnswer these ' + questions.length + ' questions about them:\\n';\n for (let i = 0; i < questions.length; i++)\n out += i + 1 + '. ' + questions[i] + '\\n';\n out += '\\nFinish with a single final line: Grade: ';\n return out;\n}", }, "challenge-panel": { name: "challenge-panel", version: "1.0.0", contentHash: "a015a5f45933352a3a2508fc35fb8df09d6b403566b4e33738904c52f3fa07fc", sourcePath: "packages/@dzhechkov/harness-core/src/challenge-panel.ts", requires: [], exports: ["CHALLENGE_QUESTIONS","CHALLENGE_VERDICT_SCHEMA","buildChallengeBrief","sanitizeFinding","sanitizeVerdict","findingsNeedingCrossValidation","confirmedVerdict","renderVerdict","pickAdversaryModel","classifyModelFamily"], code: "const SEV_RANK = { P0: 3, P1: 2, P2: 1 };\nconst VALID_CID = new Set(['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8']);\nconst isValidSeverity = (s) => s === 'P0' || s === 'P1' || s === 'P2';\nconst CHALLENGE_QUESTIONS = Object.freeze([\n Object.freeze({\n id: 'C1',\n title: 'Architecture anti-cement',\n prompt: 'Does this plan cement a NEW bad pattern, a wrong boundary, or a shortcut that later work will be ' +\n 'forced to copy? Check it against the product map + vision. IMPORTANT: deviating from a pattern that ' +\n 'is REGISTERED in the accepted-degradations registry is NOT a finding — that debt is already owned. ' +\n 'A genuinely new degradation the plan introduces → name it and propose it for the registry.',\n }),\n Object.freeze({\n id: 'C2',\n title: 'Production-ready',\n prompt: 'Where would this fall over in production? Missing error handling, unhandled failure modes, ' +\n 'resource leaks, missing observability, config/secret handling, migration/rollback. Name the ' +\n 'concrete input or condition that breaks it, not a general worry.',\n }),\n Object.freeze({\n id: 'C3',\n title: 'Test sufficiency + honesty (both ways)',\n prompt: 'Attack the test plan from BOTH sides. Under-testing: which claim — especially a safety property the ' +\n 'ADR NAMES (\"never X\") — has no falsifying test? A test that cannot fail (a wrapper, a tautology, ' +\n 'asserting the mock) is not coverage. Over-testing: which tests are theater — restating the ' +\n 'implementation, testing the framework, brittle snapshots that verify nothing a user cares about?',\n }),\n Object.freeze({\n id: 'C4',\n title: 'Overengineering sweep',\n prompt: 'What in this plan is built for a requirement nobody stated? Speculative generality, an abstraction ' +\n 'with one caller, a config knob no one asked for, a plugin seam for a single case. For each: what is ' +\n 'the simpler thing that meets the ACTUAL requirement?',\n }),\n Object.freeze({\n id: 'C5',\n title: 'Silent decisions',\n prompt: 'Which load-bearing decisions did the plan make WITHOUT surfacing them as a decision? A default that ' +\n 'is really a policy, a chosen tradeoff presented as the only option, a dependency added in passing. ' +\n 'Each silent decision the owner did not get to refuse is a finding.',\n }),\n Object.freeze({\n id: 'C6',\n title: 'Runtime consistency',\n prompt: 'Will this behave consistently with how the rest of the system already works — same error shape, ' +\n 'same config source, same module/ESM conventions, same logging, same naming? Point to the specific ' +\n 'existing convention the plan contradicts.',\n }),\n Object.freeze({\n id: 'C7',\n title: 'Scope',\n prompt: 'Is the plan more than ~1.5× the size the request actually needs? If so, what is the concrete cut ' +\n 'list — which files/steps/abstractions to drop to hit the real requirement — and what is genuinely ' +\n 'load-bearing and must stay?',\n }),\n Object.freeze({\n id: 'C8',\n title: 'Executability',\n prompt: 'Could an executor who is NOT the plan author complete every step without coming back to ask what was ' +\n 'meant? Find the steps that are under-specified, assume unstated context, or hide a research task ' +\n 'behind an imperative verb (\"integrate X\", \"wire up Y\") with no concrete how.',\n }),\n]);\nconst CHALLENGE_VERDICT_SCHEMA = Object.freeze({\n type: 'object',\n required: ['findings', 'summary'],\n properties: {\n findings: {\n type: 'array',\n items: {\n type: 'object',\n required: ['c', 'severity', 'title', 'why'],\n properties: {\n c: { type: 'string', enum: ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8'] },\n severity: { type: 'string', enum: ['P0', 'P1', 'P2'] },\n title: { type: 'string' },\n why: { type: 'string', description: 'concrete failing input/condition, not a general worry' },\n where: { type: 'string', description: 'plan section / file:line if locatable' },\n },\n },\n },\n summary: { type: 'string' },\n },\n});\nconst HR = '─'.repeat(72);\nconst section = (title, body) => body === undefined ? `## ${title}\\n(not provided — panel runs with less calibration)\\n` : `## ${title}\\n${body}\\n`;\nfunction buildChallengeBrief(ctx) {\n const lines = [];\n lines.push('# CHALLENGE PANEL — adversarial plan-gate');\n lines.push('');\n lines.push('You are a FRESH adversarial reviewer. You did NOT write this plan. Your job is to BREAK it, not to ' +\n 'confirm it — find the concrete way each answer fails, or state plainly that you could not. A finding ' +\n 'is a specific failing input/condition/omission, never a general worry. Every P0/P1 you raise will be ' +\n 'independently cross-validated, so do not pad — theory that cannot be reproduced will be dropped.');\n lines.push('');\n lines.push(HR);\n lines.push(section('PLAN UNDER REVIEW (' + ctx.planPath + ')', ctx.plan === '' ? undefined : ctx.plan));\n lines.push(section('PRODUCT VISION (boundaries + principles)', ctx.vision));\n lines.push(section('TESTING POLICY (what \"done\" + honest tests mean here)', ctx.testing));\n lines.push(section('PRODUCT MAP (subsystems + existing conventions)', ctx.map));\n lines.push(section('ACCEPTED-DEGRADATIONS REGISTRY (deviating from THESE is NOT a finding)', ctx.degradations));\n lines.push(section('CODE HINTS', ctx.codeHints));\n lines.push(HR);\n lines.push('');\n lines.push('## Ask each question in \"break it, don\\'t confirm it\" mode');\n for (const q of CHALLENGE_QUESTIONS) {\n lines.push('');\n lines.push(`### ${q.id} — ${q.title}`);\n lines.push(q.prompt);\n }\n lines.push('');\n lines.push(HR);\n lines.push('## Output');\n lines.push('Return findings tagged by C-number with severity P0 (would ship a serious defect / cements bad ' +\n 'architecture), P1 (real gap, fix before code), or P2 (worth noting). For each: a concrete `why` ' +\n '(the failing input/condition) and `where` if locatable. Then a one-paragraph `summary`. This gate ' +\n 'ADVISES — it does not block; the owner decides.');\n lines.push('');\n lines.push('Verdict JSON schema: ' + JSON.stringify(CHALLENGE_VERDICT_SCHEMA));\n return lines.join('\\n');\n}\nfunction sanitizeFinding(raw) {\n if (raw === null || typeof raw !== 'object')\n return null;\n const r = raw;\n if (typeof r.c !== 'string' || !VALID_CID.has(r.c))\n return null;\n if (!isValidSeverity(r.severity))\n return null;\n if (typeof r.title !== 'string' || r.title === '')\n return null;\n if (typeof r.why !== 'string' || r.why === '')\n return null;\n const out = { c: r.c, severity: r.severity, title: r.title, why: r.why };\n return typeof r.where === 'string' && r.where !== '' ? { ...out, where: r.where } : out;\n}\nfunction sanitizeVerdict(raw) {\n if (raw === null || typeof raw !== 'object')\n return null;\n const r = raw;\n if (!Array.isArray(r.findings))\n return null;\n const findings = r.findings.map(sanitizeFinding).filter((f) => f !== null);\n return { findings, summary: typeof r.summary === 'string' ? r.summary : '' };\n}\nfunction findingsNeedingCrossValidation(v) {\n return [...v.findings]\n .filter((f) => f.severity === 'P0' || f.severity === 'P1')\n .sort(cmpFinding);\n}\nfunction cmpFinding(a, b) {\n const s = SEV_RANK[b.severity] - SEV_RANK[a.severity];\n if (s !== 0)\n return s;\n if (a.c !== b.c)\n return a.c < b.c ? -1 : 1;\n return a.title < b.title ? -1 : a.title > b.title ? 1 : 0;\n}\nfunction confirmedVerdict(v, realFlags) {\n const need = findingsNeedingCrossValidation(v);\n const kept = v.findings.filter((f) => f.severity === 'P2');\n need.forEach((f, i) => {\n if (realFlags[i] === true)\n kept.push({ ...f, crossValidated: true });\n });\n kept.sort(cmpFinding);\n return { findings: kept, summary: v.summary };\n}\nfunction renderVerdict(v) {\n if (v.findings.length === 0) {\n return `Challenge panel: no cross-validated findings. ${v.summary}`.trim();\n }\n const byId = (s) => v.findings.filter((f) => f.severity === s).sort(cmpFinding);\n const out = ['Challenge panel verdict (advisory — you decide):', ''];\n for (const sev of ['P0', 'P1', 'P2']) {\n const group = byId(sev);\n if (group.length === 0)\n continue;\n out.push(`### ${sev} (${group.length})`);\n for (const f of group) {\n const cv = f.crossValidated ? ' ✓cross-validated' : '';\n const where = f.where ? ` [${f.where}]` : '';\n out.push(`- ${f.c} ${f.title}${where}${cv}`);\n out.push(` why: ${f.why}`);\n }\n out.push('');\n }\n out.push(v.summary);\n return out.join('\\n').trim();\n}\nfunction pickAdversaryModel(plannerModel) {\n const fam = classifyModelFamily(plannerModel);\n if (fam === 'claude')\n return { model: 'codex', note: `plan authored on ${plannerModel} (Claude) → Codex adversary (cross-family)` };\n if (fam === 'openai')\n return { model: 'claude', note: `plan authored on ${plannerModel} (OpenAI/Codex) → fresh Claude adversary (cross-family)` };\n return { model: 'claude', note: `plan author family UNKNOWN (${plannerModel}) → Claude adversary by default; verify it is cross-family before trusting the verdict` };\n}\nfunction classifyModelFamily(model) {\n const m = String(model).toLowerCase();\n if (/claude|opus|sonnet|haiku|fable/.test(m))\n return 'claude';\n if (/codex|gpt|openai|\\bo[1-9]\\b/.test(m))\n return 'openai';\n return 'unknown';\n}", }, "trace": { name: "trace", version: "1.1.0", contentHash: "1270f9aac5fbe5693af8bcc26af55e81aeb41ef4b911dbda72c23ea248072344", sourcePath: "packages/@dzhechkov/harness-core/src/loop-trace.ts", requires: [], exports: ["LOOP_TRACE_SCHEMA_VERSION","TRACE_RUNID_RE","TRACE_KEY_RE","traceShellQuote","traceValidateEvent","traceInit","traceOnDispatch","traceOnSettle","traceClose","traceFlushCmd","traceFaRecordCmd","traceLedgerLine","traceLedgerAppendCmd"], code: "const LOOP_TRACE_SCHEMA_VERSION = 1;\nconst TRACE_RUNID_RE = /^[a-z0-9-]{1,40}$/;\nconst TRACE_KEY_RE = /^[a-z0-9_.:-]{1,64}$/i;\nfunction traceShellQuote(s) {\n return \"'\" + String(s).replace(/'/g, \"'\\\\''\") + \"'\";\n}\nfunction traceValidateEvent(e) {\n if (typeof e !== 'object' || e === null || Array.isArray(e))\n return 'event must be an object';\n const ev = e;\n if (ev['v'] !== 1)\n return 'v must be 1';\n if (typeof ev['runId'] !== 'string' || !TRACE_RUNID_RE.test(ev['runId']))\n return 'runId fails its VO regex';\n if (typeof ev['seq'] !== 'number' || !Number.isInteger(ev['seq']) || ev['seq'] < 1)\n return 'seq must be a positive integer';\n const kind = ev['event'];\n if (kind === 'dispatched') {\n if (typeof ev['invocationId'] !== 'string' || ev['invocationId'] === '')\n return 'invocationId required';\n if (typeof ev['stepId'] !== 'string' || !TRACE_KEY_RE.test(ev['stepId']))\n return 'stepId fails its VO regex';\n if (ev['itemKey'] !== null && (typeof ev['itemKey'] !== 'string' || !TRACE_KEY_RE.test(ev['itemKey'])))\n return 'itemKey fails its VO regex';\n if (typeof ev['attempt'] !== 'number' || ev['attempt'] < 1)\n return 'attempt must be >= 1';\n if (typeof ev['phase'] !== 'string' || ev['phase'] === '')\n return 'phase required';\n if (!Array.isArray(ev['causedBy']) || ev['causedBy'].some((n) => typeof n !== 'number'))\n return 'causedBy must be a number array';\n return null;\n }\n if (kind === 'settled') {\n if (typeof ev['invocationId'] !== 'string' || ev['invocationId'] === '')\n return 'invocationId required';\n if (ev['outcome'] !== 'ok' && ev['outcome'] !== 'null' && ev['outcome'] !== 'error')\n return 'outcome must be ok|null|error';\n return null;\n }\n if (kind === 'run.opened') {\n if (typeof ev['planDigest'] !== 'string' || typeof ev['execFp'] !== 'string')\n return 'run.opened needs planDigest + execFp';\n const ep = ev['emitterPath'];\n if (ep !== undefined && ep !== 'dz-process' && ep !== 'rendered-script')\n return 'emitterPath must be dz-process|rendered-script';\n return null;\n }\n if (kind === 'run.closed') {\n const c = ev['counts'];\n if (typeof c !== 'object' || c === null)\n return 'run.closed needs counts';\n return null;\n }\n return 'unknown event kind';\n}\nfunction traceInit(runId, planDigest, execFp, emitterPath) {\n if (!TRACE_RUNID_RE.test(runId))\n throw new Error('loop-trace: runId fails ' + String(TRACE_RUNID_RE));\n const state = { runId, seq: 0, dispatched: 0, settled: 0, buffer: [] };\n const opened = { v: 1, runId, seq: ++state.seq, event: 'run.opened', planDigest, execFp, emitterPath };\n traceBuffer(state, opened);\n return state;\n}\nfunction traceBuffer(state, e) {\n const err = traceValidateEvent(e);\n if (err !== null)\n throw new Error('loop-trace: refusing non-conforming event (' + err + ') — the authoritative ordering source is never repaired later');\n state.buffer.push(JSON.stringify(e));\n}\nfunction traceOnDispatch(state, e) {\n const seq = ++state.seq;\n state.dispatched++;\n traceBuffer(state, {\n v: 1,\n runId: state.runId,\n seq,\n event: 'dispatched',\n invocationId: e.invocationId,\n stepId: e.stepId,\n itemKey: e.itemKey,\n attempt: e.attempt,\n phase: e.phase,\n model: e.model,\n causedBy: e.causedBy,\n });\n return seq;\n}\nfunction traceOnSettle(state, e) {\n const seq = ++state.seq;\n state.settled++;\n traceBuffer(state, { v: 1, runId: state.runId, seq, event: 'settled', invocationId: e.invocationId, outcome: e.outcome });\n return seq;\n}\nfunction traceClose(state) {\n const closed = {\n v: 1,\n runId: state.runId,\n seq: ++state.seq,\n event: 'run.closed',\n counts: { dispatched: state.dispatched, settled: state.settled },\n };\n traceBuffer(state, closed);\n}\nfunction traceFlushCmd(state, traceFileAbs) {\n if (state.buffer.length === 0)\n return null;\n const lines = state.buffer.splice(0, state.buffer.length);\n const file = traceShellQuote(traceFileAbs);\n const dir = traceShellQuote(traceFileAbs.replace(/\\/[^/]*$/, ''));\n const printfs = lines\n .map((l) => \"printf '%s\\\\n' \" + traceShellQuote(l) + ' | sed \"s/}$/,\\\\\"wallTime\\\\\":\\\\\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\\\\\"}/\" >> ' + file)\n .join(' && ');\n return 'mkdir -p ' + dir + ' && ' + printfs;\n}\nfunction traceFaRecordCmd(dzBin, slug, stepLabel, projectAbs) {\n if (typeof slug !== 'string' || slug === ''\n || typeof stepLabel !== 'string' || stepLabel === ''\n || typeof projectAbs !== 'string' || projectAbs === '')\n return null;\n const bin = typeof dzBin === 'string' && dzBin !== '' ? dzBin : 'dz';\n const cmd = traceShellQuote(bin) + ' statusline --fa-record --slug ' + traceShellQuote(slug)\n + ' --step ' + traceShellQuote(stepLabel) + ' --kind loop --project ' + traceShellQuote(projectAbs);\n return cmd + ' >/dev/null 2>&1';\n}\nfunction traceLedgerLine(opts) {\n try {\n if (typeof opts.slug !== 'string' || opts.slug === '')\n return null;\n const agents = typeof opts.agents === 'number'\n && Number.isFinite(opts.agents)\n && Number.isInteger(opts.agents)\n && opts.agents >= 0\n ? opts.agents\n : 0;\n const date = typeof opts.date === 'string' && /^\\d{4}-\\d{2}-\\d{2}$/.test(opts.date) ? opts.date : null;\n const outcome = typeof opts.outcome === 'string' && opts.outcome !== '' ? opts.outcome : 'unknown';\n const line = JSON.stringify({\n slug: opts.slug,\n stage: 'loop-run',\n tier: null,\n tokens: null,\n minutes: null,\n agents,\n coder: null,\n grade: null,\n date,\n auto: true,\n outcome,\n runId: typeof opts.runId === 'string' ? opts.runId : null,\n planDigest: typeof opts.planDigest === 'string' ? opts.planDigest : null,\n });\n return line.length <= 4000 ? line : null;\n }\n catch {\n return null;\n }\n}\nfunction traceLedgerAppendCmd(repoAbs, line) {\n if (typeof repoAbs !== 'string' || repoAbs === '' || typeof line !== 'string' || line === '')\n return null;\n const dir = traceShellQuote(repoAbs + '/.dz/feature-adr');\n const file = traceShellQuote(repoAbs + '/.dz/feature-adr/run-cost-ledger.jsonl');\n return 'mkdir -p ' + dir\n + \" && printf '%s' \" + traceShellQuote(line)\n + ' | sed \"s/\\\\\"date\\\\\":null/\\\\\"date\\\\\":\\\\\"$(date -u +%Y-%m-%d)\\\\\"/\" >> ' + file\n + \" && printf '\\\\n' >> \" + file\n + ' && echo LEDGER-OK';\n}\nfunction invocations(run) {\n const out = new Map();\n for (const e of run.events) {\n if (e.event === 'dispatched') {\n out.set(e.invocationId, {\n invocationId: e.invocationId,\n stepId: e.stepId,\n itemKey: e.itemKey,\n dispatchSeq: e.seq,\n settleSeq: null,\n causedBy: e.causedBy,\n });\n }\n else if (e.event === 'settled') {\n const inv = out.get(e.invocationId);\n if (inv)\n inv.settleSeq = e.seq;\n }\n }\n return [...out.values()];\n}", }, "loop-semantics": { name: "loop-semantics", version: "1.0.0", contentHash: "d918ba8d29d9dc20e2467ddb0ba126d537bc9e4560547e2ae52d28979ee6ea9c", sourcePath: "packages/@dzhechkov/harness-core/src/loop-run-semantics.ts", requires: [], exports: ["errText","causeChain","errSnap","classifyFailure","gateVerdict","joinRegion"], code: "function errText(err) {\n try {\n if (err !== null && typeof err === 'object') {\n const m = err.message;\n if (typeof m === 'string')\n return m;\n }\n return String(err);\n }\n catch (_e) {\n try {\n return Object.prototype.toString.call(err);\n }\n catch (_e2) {\n return '[unrenderable error]';\n }\n }\n}\nfunction causeChain(err) {\n const chain = [];\n let cur = err;\n for (let d = 0; d < 5; d++) {\n if (cur === null || cur === undefined)\n break;\n if (chain.indexOf(cur) !== -1)\n break;\n chain.push(cur);\n try {\n cur = typeof cur === 'object' ? cur.cause : undefined;\n }\n catch (_e) {\n cur = undefined;\n }\n }\n return chain.length > 0 ? chain : [err];\n}\nfunction errSnap(err) {\n const chain = causeChain(err);\n const snap = [];\n for (let ci = 0; ci < chain.length; ci++) {\n let code = null;\n try {\n const c = chain[ci] !== null && typeof chain[ci] === 'object' ? chain[ci].code : null;\n code = typeof c === 'string' ? c.toUpperCase() : null;\n }\n catch (_e) {\n code = null;\n }\n let name = null;\n try {\n const n = chain[ci] !== null && typeof chain[ci] === 'object' ? chain[ci].name : null;\n name = typeof n === 'string' ? n : null;\n }\n catch (_e) {\n name = null;\n }\n snap.push({ code: code, name: name, text: errText(chain[ci]) });\n }\n return snap;\n}\nfunction classifyFailure(outcome, snap) {\n if (outcome === 'null')\n return 'transport';\n const links = Array.isArray(snap) ? snap : [];\n for (let ci = 0; ci < links.length; ci++) {\n const code = links[ci].code;\n if (code === 'ETIMEDOUT' || code === 'ECONNRESET' || code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'EPIPE' || code === 'ECONNABORTED' || code === 'EAI_AGAIN')\n return 'transport';\n }\n for (let ci = 0; ci < links.length; ci++) {\n if (links[ci].name === 'SyntaxError')\n return 'malformed-output';\n }\n let msg = '';\n for (let ci = 0; ci < links.length; ci++)\n msg += (ci > 0 ? '\\n' : '') + links[ci].text;\n msg = msg.toLowerCase();\n if (/\\btransport\\b|\\beconnreset\\b|\\beconnrefused\\b|\\benotfound\\b|\\bepipe\\b|\\betimedout\\b|\\bsocket hang up\\b|\\bnetwork error\\b|\\brate[ -]?limit(ed|ing|s)?\\b|\\boverloaded\\b|\\bhttp 5[0-9][0-9]\\b/.test(msg))\n return 'transport';\n if (/\\bpolicy\\b|\\brefus(e|ed|es|al|ing)\\b|\\bdeclin(e|ed|es|ing)\\b|\\bcontent filter\\b|\\bsafety block\\b/.test(msg))\n return 'policy-refusal';\n if (/\\bmalformed\\b|\\bunparseable\\b|\\bparse error\\b|\\binvalid json\\b|\\bunexpected token\\b|\\bunexpected end of json\\b|\\bschema mismatch\\b/.test(msg))\n return 'malformed-output';\n if (/\\btimeout\\b|\\btimed out\\b/.test(msg))\n return 'timeout';\n return null;\n}\nfunction gateVerdict(reply) {\n if (typeof reply !== 'string')\n return 'invalid';\n const vLines = reply.split('\\n');\n const vRe = /^\\s*GATE:\\s*(PASS|FAIL)\\s*$/;\n let vCount = 0;\n let vLast = '';\n for (let i = 0; i < vLines.length; i++) {\n if (vRe.test(vLines[i]))\n vCount++;\n if (vLines[i].trim() !== '')\n vLast = vLines[i];\n }\n const vEnd = vRe.exec(vLast);\n if (vCount !== 1 || vEnd === null)\n return 'invalid';\n return vEnd[1] === 'PASS' ? 'pass' : 'fail';\n}\nfunction joinRegion(results, o) {\n const policy = o && o.policy ? o.policy : 'all-activated';\n const failures = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i] === null || results[i] === undefined)\n failures.push(i);\n }\n if (policy === 'any') {\n if (failures.length === results.length)\n throw new Error('join ' + o.region + ': every branch failed (policy any)');\n return { ok: true, values: results, failures: failures };\n }\n const quorum = /^quorum:([1-9][0-9]*)$/.exec(policy);\n if (quorum) {\n const okN = results.length - failures.length;\n if (okN < Number(quorum[1]))\n throw new Error('join ' + o.region + ': quorum ' + quorum[1] + ' not met (' + okN + ' ok)');\n return { ok: true, values: results, failures: failures };\n }\n if (failures.length > 0)\n throw new Error('join ' + o.region + ': ' + failures.length + ' dispatched branch(es) failed under policy ' + policy + ' — a dispatched branch is never skippable');\n return { ok: true, values: results, failures: [] };\n}", }, "ha-consult-router": { name: "ha-consult-router", version: "1.0.0", contentHash: "1df9e5582f8ec888cf2d8c0f38a6dac18c970489addbb1bfd203949f3e343195", sourcePath: ".claude/workflows/lib/ha-consult-router.mjs", requires: [], exports: ["CONSULT_PHASES","activeMedications","interactionFlaggedFor","anyMedIndicationOverlaps","reconciliationUncertain","polypharmacyIsRelevant","distinctClinicalSpecialties","hasCrossDepartmentContradiction","abnormalAnalyteDepartments","TEAM_CRITERIA","shouldRouteTeam"], code: "const CONSULT_PHASES = Object.freeze([\n 'ESCALATED_IMMEDIATE', // terminal — ambulance hit, zero specialist agents (INV-10)\n 'ESCALATED_URGENT', // non-terminal — doctor_24h hit: banner at position 0, rides every later payload (INV-10b)\n 'ROUTED_RESTRICTED', // terminal — pregnant / child → referral out\n 'ROUTED_SOLO', // terminal — today's solo flow, untouched\n 'AWAITING_TRIAGE_RESPONSE', // pause 1 of exactly 2\n 'AWAITING_SYNTHESIS_APPROVAL',// pause 2 of exactly 2\n 'FAILED_GATE', // terminal — enforce gate failed twice, loud\n 'COMPLETED', // terminal\n]);\n\nfunction activeMedications(profile) {\n return ((profile && profile.medications) || []).filter((m) => m && m.active !== false);\n}\n\nfunction interactionFlaggedFor(complaint) {\n return (((complaint && complaint.interaction_flags) || []).length > 0);\n}\n\nfunction anyMedIndicationOverlaps(profile, complaint) {\n const systems = new Set(((complaint && complaint.systems) || []).map(String));\n return activeMedications(profile).some((m) => ((m.indication_systems || []).some((s) => systems.has(String(s)))));\n}\n\nfunction reconciliationUncertain(profile) {\n return Boolean(profile) && profile.med_list_reconciled === false;\n}\n\nfunction polypharmacyIsRelevant(profile, complaint) {\n if (activeMedications(profile).length < 5) return false;\n return interactionFlaggedFor(complaint)\n || anyMedIndicationOverlaps(profile, complaint)\n || reconciliationUncertain(profile);\n}\n\nfunction distinctClinicalSpecialties(complaintMap) {\n return new Set(((complaintMap && complaintMap.specialties) || []).map(String)).size;\n}\n\nfunction hasCrossDepartmentContradiction(profile) {\n return (((profile && profile.contradictions) || []).length > 0);\n}\n\nfunction abnormalAnalyteDepartments(profile) {\n return new Set(((profile && profile.abnormal_departments) || []).map(String)).size;\n}\n\nconst TEAM_CRITERIA = Object.freeze(['multi_system', 'contradiction', 'relevant_polypharmacy', 'volume']);\n\nfunction shouldRouteTeam(complaintMap, profile, complaint) {\n const teamCriteria = [];\n if (distinctClinicalSpecialties(complaintMap) >= 2) teamCriteria.push('multi_system');\n if (hasCrossDepartmentContradiction(profile)) teamCriteria.push('contradiction');\n if (polypharmacyIsRelevant(profile, complaint)) teamCriteria.push('relevant_polypharmacy');\n if (abnormalAnalyteDepartments(profile) >= 3) teamCriteria.push('volume');\n // The acknowledged FALSE NEGATIVE (high-stakes single-specialty question) is handled at\n // checkpoint A — the user can force a team; it is named in the checkpoint banner, not patched\n // with a vaguer criterion (that would make routing subjective and circular, B2).\n return { route: teamCriteria.length > 0 ? 'team' : 'solo', criteria: teamCriteria };\n}", }, };